WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting Algorithms_Circle Sort







Python: 




def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
    
    n = R-L
    if n < 2:
        return 0
    swaps = 0
    m = n//2
    for i in range(m):
        if A[R-(i+1)] < A[L+i]:
            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
            swaps += 1
    if (n & 1) and (A[L+m] < A[L+m-1]):
        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
        swaps += 1
    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)

def circle_sort(L:list)->'sort A in place, returning the number of swaps':
    swaps = 0
    s = 1
    while s:
        s = circle_sort_backend(L, 0, len(L))
        swaps += s
    return swaps


if __name__ == '__main__':
    from random import shuffle
    for i in range(309):
        L = list(range(i))
        M = L[:]
        shuffle(L)
        N = L[:]
        circle_sort(L)
        if L != M:
            print(len(L))
            print(N)
            print(L)




Fortran: 
module circlesort






  implicit none
  logical, private :: csr
  public :: circle_sort
 
contains
 
  recursive logical function csr(a, left, right,n) result(swapped)
    implicit none
    integer, intent(in) :: left, right,n
    integer, intent(inout) :: a(n)
    integer :: lo, hi, mid
    integer :: temp
    logical :: lefthalf,righthalf

    swapped = .FALSE.
    if (right <= left) return
    lo = left   
    hi = right  

    do while (lo < hi)

       if (a(hi) < a(lo)) then
          swapped = .TRUE.
          temp = a(lo)
          a(lo) = a(hi)
          a(hi) = temp
       endif
       lo = lo + 1
       hi = hi - 1
    end do

    if (lo == hi)then
       if(a(hi+1) .lt. a(lo))then
           swapped = .TRUE.
           temp = a(hi+1)
           a(hi+1) = a(lo)
           a(lo) = temp
       endif
    endif
    mid = (left + right) / 2 
    lefthalf = csr(a, left, mid,n)
    righthalf = csr(a, mid + 1, right,n)
    swapped = swapped .or. lefthalf .or. righthalf
  end function csr

  subroutine circle_sort(a, n)
    use iso_c_binding, only: c_ptr, c_loc
    implicit none
    integer, intent(in) :: n
    integer, target,intent(inout) :: a(n)

    do while ( csr(a, 1, n,n))



    end do
  end subroutine circle_sort
 
end module circlesort
program sort
  use circlesort
  implicit none
  integer :: a(9)
  data a/6,7,8,9,2,5,3,4,1/
  call circle_sort(a, size(a))
  print *, a
end program sort
Task: I before E except after C







Python: import urllib.request
import re

PLAUSIBILITY_RATIO = 2

def plausibility_check(comment, x, y):
    print('\n  Checking plausibility of: %s' % comment)
    if x > PLAUSIBILITY_RATIO * y:
        print('    PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
              % (x, y, x / y))
    else:
        if x > y:
            print('    IMPLAUSIBLE. As although we have counts of %i vs %i, a ratio of %4.1f times does not make it plausible'
                  % (x, y, x / y))
        else:
            print('    IMPLAUSIBLE, probably contra-indicated. As we have counts of %i vs %i, a ratio of %4.1f times'
                  % (x, y, x / y))
    return x > PLAUSIBILITY_RATIO * y

def simple_stats(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):
    words = urllib.request.urlopen(url).read().decode().lower().split()
    cie = len({word for word in words if 'cie' in word})
    cei = len({word for word in words if 'cei' in word})
    not_c_ie = len({word for word in words if re.search(r'(^ie|[^c]ie)', word)})
    not_c_ei = len({word for word in words if re.search(r'(^ei|[^c]ei)', word)})
    return cei, cie, not_c_ie, not_c_ei

def print_result(cei, cie, not_c_ie, not_c_ei):
    if ( plausibility_check('I before E when not preceded by C', not_c_ie, not_c_ei)
         & plausibility_check('E before I when preceded by C', cei, cie) ):
        print('\nOVERALL IT IS PLAUSIBLE!')
    else:
        print('\nOVERALL IT IS IMPLAUSIBLE!')
    print('(To be plausible, one count must exceed another by %i times)' % PLAUSIBILITY_RATIO)

print('Checking plausibility of "I before E except after C":')
print_result(*simple_stats())




Fortran: 













program cia
  implicit none
  character (len=256) :: s
  integer :: ie, ei, cie, cei
  integer :: ios
  data ie, ei, cie, cei/4*0/
  do while (.true.)
    read(5,*,iostat = ios)s
    if (0 .ne. ios) then
      exit
    endif
    call lower_case(s)
    cie = cie + occurrences(s, 'cie')
    cei = cei + occurrences(s, 'cei')
    ie = ie + occurrences(s, 'ie')
    ei = ei + occurrences(s, 'ei')
  enddo
  write(6,'(1x,4(a4,1x))') 'ie','ei','cie','cei'
  write(6,'(1x,4(i4,1x))') ie,ei,cie,cei 
  write(6,'(1x,2(a,1x))') '        [^c]ie',plausibility(ie,ei)
  write(6,'(1x,2(a,1x))') '           cei',plausibility(cei,cie)
  write(6,'(1x,2(a,1x))') '([^c]ie)|(cei)',plausibility(ie+cei,ei+cie)

contains

  subroutine lower_case(s)
    character(len=*), intent(inout) :: s
    integer :: i
    do i=1, len_trim(s)
      s(i:i) = achar(ior(iachar(s(i:i)),32))
    enddo
  end subroutine lower_case

  integer function occurrences(a,b)
    character(len=*), intent(in) :: a, b
    integer :: i, j, n
    n = 0
    i = 0
    j = index(a, b)
    do while (0 .lt. j)
      n = n+1
      i = i+len(b)+j-1
      j = index(a(i:), b)
    end do
    occurrences = n
  end function occurrences

  character*(32) function plausibility(da, nyet)
    integer, intent(in) :: da, nyet
    
    if (nyet*2 .lt. da) then
      plausibility = 'plausible'
    else
      plausibility = 'implausible'
    endif
  end function plausibility
end program cia
Task: Abelian sandpile model







Python: import numpy as np
import matplotlib.pyplot as plt


def iterate(grid):
    changed = False
    for ii, arr in enumerate(grid):
        for jj, val in enumerate(arr):
            if val > 3:
                grid[ii, jj] -= 4
                if ii > 0:
                    grid[ii - 1, jj] += 1
                if ii < len(grid)-1:
                    grid[ii + 1, jj] += 1
                if jj > 0:
                    grid[ii, jj - 1] += 1
                if jj < len(grid)-1:
                    grid[ii, jj + 1] += 1
                changed = True
    return grid, changed


def simulate(grid):
    while True:
        grid, changed = iterate(grid)
        if not changed:
            return grid


if __name__ == '__main__':
    start_grid = np.zeros((10, 10))
    start_grid[4:5, 4:5] = 64
    final_grid = simulate(start_grid.copy())
    plt.figure()
    plt.gray()
    plt.imshow(start_grid)
    plt.figure()
    plt.gray()
    plt.imshow(final_grid)




Fortran: module abelian_sandpile_m

  implicit none

  private
  public :: pile

  type :: pile
    
    
    

    integer, allocatable :: grid(:,:)
    integer              :: n(2)

  contains
    procedure :: init
    procedure :: run

    procedure, private :: process_node
    procedure, private :: inside
  end type

contains

  logical function inside(this, i)
    class(pile), intent(in) :: this
    integer,     intent(in) :: i(2)

    inside = ((i(1) > 0) .and. (i(1) <= this%n(1)) .and. (i(2) > 0) .and. (i(2) <= this%n(2)) )
  end function

  recursive subroutine process_node(this, i)
    

    class(pile), intent(inout) :: this
    integer,     intent(in)    :: i(2)
      

    integer :: i0(2,2), j(2), d, k

    
    if (this%grid(i(1),i(2)) >= 4) then
      
      i0 = reshape([1,0,0,1], [2,2])

      
      this%grid(i(1),i(2)) = this%grid(i(1),i(2))-4

      
      do d = 1, 2               
        do k = -1, 1, 2         
          j = i+k*i0(:,d)       
          if (this%inside(j)) this%grid(j(1),j(2)) = this%grid(j(1),j(2)) + 1
        end do
      end do

      
      do d = 1, 2               
        do k = -1, 1, 2         
          j = i+k*i0(:,d)       
          if (this%inside(j)) call this%process_node(j)
        end do
      end do

      
      call this%process_node(i)
    end if
  end subroutine

  subroutine run(this)
    

    class(pile), intent(inout) :: this

    
    call this%process_node(this%n/2)
  end subroutine

  subroutine init(this, nx, ny, h)
    class(pile), intent(out) :: this
    integer,     intent(in)  :: nx, ny
      
    integer,     intent(in)  :: h
      

    this%n = [nx, ny]
    allocate (this%grid(nx,ny), source=0)
    this%grid(nx/2, ny/2) = h
  end subroutine

end module
Task: Zhang-Suen thinning algorithm







Python: 


beforeTxt = 


smallrc01 = 

rc01 = 

def intarray(binstring):
    
    return [[1 if ch == '1' else 0 for ch in line] 
            for line in binstring.strip().split()]

def chararray(intmatrix):
    
    return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)

def toTxt(intmatrix):
    Return 8-neighbours of point p1 of picture, in order'''
    i = image
    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
    
    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  
            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  

def transitions(neighbours):
    n = neighbours + neighbours[0:1]    
    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))

def zhangSuen(image):
    changing1 = changing2 = [(-1, -1)]
    while changing1 or changing2:
        
        changing1 = []
        for y in range(1, len(image) - 1):
            for x in range(1, len(image[0]) - 1):
                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
                if (image[y][x] == 1 and    
                    P4 * P6 * P8 == 0 and   
                    P2 * P4 * P6 == 0 and   
                    transitions(n) == 1 and 
                    2 <= sum(n) <= 6):      
                    changing1.append((x,y))
        for x, y in changing1: image[y][x] = 0
        
        changing2 = []
        for y in range(1, len(image) - 1):
            for x in range(1, len(image[0]) - 1):
                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
                if (image[y][x] == 1 and    
                    P2 * P6 * P8 == 0 and   
                    P2 * P4 * P8 == 0 and   
                    transitions(n) == 1 and 
                    2 <= sum(n) <= 6):      
                    changing2.append((x,y))
        for x, y in changing2: image[y][x] = 0
        
        
    return image
            

if __name__ == '__main__':
    for picture in (beforeTxt, smallrc01, rc01):
        image = intarray(picture)
        print('\nFrom:\n%s' % toTxt(image))
        after = zhangSuen(image)
        print('\nTo thinned:\n%s' % toTxt(after))




Fortran: A(2:N - 1) = (A(1:N - 2) + A(2:N - 1) + A(3:N))/3
Task: Generate Chess960 starting position







Python: >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
                     if p.index('B') % 2 != p.index('b') % 2 		
                     and ( p.index('r') < p.index('K') < p.index('R')	
                           or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>




Fortran: program chess960
    implicit none
    
    integer, pointer  :: a,b,c,d,e,f,g,h
    integer, target   :: p(8)
    a => p(1)
    b => p(2)
    c => p(3)
    d => p(4)
    e => p(5)
    f => p(6)
    g => p(7)
    h => p(8)

    king: do a=2,7                                        
        r1: do b=1,a-1                                    
            r2: do c=a+1,8                                
                b1: do d=1,7,2                            
                    if (skip_pos(d,4)) cycle
                    b2: do e=2,8,2                        
                        if (skip_pos(e,5)) cycle
                        queen: do f=1,8                   
                            if (skip_pos(f,6)) cycle
                            n1: do g=1,7                  
                                if (skip_pos(g,7)) cycle
                                n2: do h=g+1,8            
                                    if (skip_pos(h,8)) cycle
                                    if (sum(p) /= 36) stop 'Loop error'  
                                    call write_position
                                end do n2
                            end do n1
                        end do queen
                    end do b2
                end do b1
            end do r2
        end do r1
    end do king
    
contains

    logical function skip_pos(i, n)
        integer, intent(in) :: i, n
        skip_pos = any(p(1:n-1) == i)
    end function skip_pos

    subroutine write_position
        integer           :: i, j
        character(len=15) :: position = ' '
        character(len=1), parameter  :: names(8) = ['K','R','R','B','B','Q','N','N']
        do i=1,8
            j = 2*p(i)-1
            position(j:j) = names(i)
        end do
        write(*,'(a)') position
    end subroutine write_position
    
end program chess960
Task: Mersenne primes







Python: import random


def MillerRabinPrimalityTest(number):
    
    if number == 2:
        return True
    elif number == 1 or number % 2 == 0:
        return False
    
    
    
    
    oddPartOfNumber = number - 1
    
    
    timesTwoDividNumber = 0
    
    
    while oddPartOfNumber % 2 == 0:
        oddPartOfNumber = oddPartOfNumber / 2
        timesTwoDividNumber = timesTwoDividNumber + 1 
     
    
    for time in range(3):
        
        
        while True:
            
            randomNumber = random.randint(2, number)-1
            if randomNumber != 0 and randomNumber != 1:
                break
        
        
        randomNumberWithPower = pow(randomNumber, oddPartOfNumber, number)
        
        
        if (randomNumberWithPower != 1) and (randomNumberWithPower != number - 1):
            
            iterationNumber = 1
            
            
            while (iterationNumber <= timesTwoDividNumber - 1) and (randomNumberWithPower != number - 1):
                
                randomNumberWithPower = pow(randomNumberWithPower, 2, number)
                
                
                iterationNumber = iterationNumber + 1
            
            if (randomNumberWithPower != (number - 1)):
                return False
            
    
    return True


MAX = 20
p = 2
count = 0
while True:
    m = (2 << (p - 1)) - 1
    if MillerRabinPrimalityTest(m):
        print "2 ^ {} - 1".format(p)
        count = count + 1
        if count == MAX:
            break
    
    while True:
        p = p + 2 if (p > 2) else 3
        if MillerRabinPrimalityTest(p):
            break
print "done"




Fortran: program mersenne
    use iso_fortran_env, only: output_unit, INT64
    implicit none

    integer, parameter  :: l=INT64
    integer(kind=l)     :: base
    integer             :: pow

    base = 2

    do pow = 1, 32
        if (is_prime(base-1)) then
            write(output_unit,'(A2,x,I0,x,A3)') "2^", pow, "- 1"
        end if
        base = base * 2
    end do
contains
    pure function is_prime(n)
        integer(kind=l), intent(in) :: n
        logical                     :: is_prime
        integer(kind=l)             :: test

        is_prime = .false.
        if (n < 2) return
        if (modulo(n, 2) == 0) then
            is_prime = n==2
            return
        end if
        if (modulo(n, 3) == 0) then
            is_prime = n==3
            return
        end if

        test = 5
        do
            if (test**2 >= n) then
                is_prime = .true.
                return
            end if

            if (modulo(n, test) == 0) return
            test = test + 2
            if (modulo(n, test) == 0) return
            test = test + 4
        end do
    end function is_prime
end program mersenne
Task: Taxicab numbers







Python: from collections import defaultdict
from itertools import product
from pprint import pprint as pp

cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
	if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
	
taxied = sorted((k, v) for k,v in sum2cubes.items() if len(v) >= 2)


for t in enumerate(taxied[:25], 1):
    pp(t)
print('...')    
for t in enumerate(taxied[2000-1:2000+6], 2000):
    pp(t)




Fortran: 
     PROGRAM POOKA
      IMPLICIT NONE



      INTEGER , PARAMETER  ::  NVARS = 25



      REAL  ::  f1
      REAL  ::  f2
      INTEGER  ::  hits
      INTEGER  ::  s
      INTEGER  ::  TAXICAB

      hits = 0
      s = 0
      f1 = SECOND()
      DO WHILE ( hits<NVARS )
         s = s + 1
         hits = hits + TAXICAB(s)
      END DO
      f2 = SECOND()
      PRINT * , 'elapsed time = ' , f2 - f1 , 'For ' , NVARS , ' Variables'
      STOP
      END PROGRAM POOKA
 
      FUNCTION TAXICAB(N)
      IMPLICIT NONE



      INTEGER  ::  N
      INTEGER  ::  TAXICAB
      INTENT (IN) N



      INTEGER  ::  holder
      INTEGER  ::  oldx
      INTEGER  ::  oldy
      INTEGER  ::  s
      INTEGER  ::  x
      INTEGER  ::  y
      real*8,parameter :: xpon=(1.0D0/3.0D0)

      x = 0
      holder = 0
      oldx = 0
      oldy = 0
      TAXICAB = 0
      y = INT(N**xpon)
      DO WHILE ( x<=y )
         s = x**3 + y**3
         IF( s<N )THEN
            x = x + 1
         ELSE IF( s>N )THEN
            y = y - 1
         ELSE
            IF( holder==s )THEN 
               WRITE(6 , 34)s , '(' , x**3 , y**3 , ')' , '(' , oldx**3 , oldy**3 , ')'
 34            FORMAT(1x , i12 , 10x , 1A1 , i12 , 2x , i12 , 1A1 , 10x , 1A1 , i12 , 2x ,&
                    & i12 , 1A1)
               TAXICAB = 1  
            END IF
            holder = s      
            oldx = x       
            oldy = y
            x = x + 1       
            y = y - 1
         END IF
      END DO
      RETURN
      END FUNCTION TAXICAB
Task: Left factorials







Python: from itertools import islice

def lfact():
    yield 0
    fact, summ, n = 1, 0, 1 
    while 1:
        fact, summ, n = fact*n, summ + fact, n + 1
        yield summ

print('first 11:\n  %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10):
    print(lf)
print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n  %r' 
      % [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] )




Fortran:       MODULE LAIROTCAF	
       CONTAINS		
        INTEGER*8 FUNCTION FACT(N)	
         INTEGER N	
         INTEGER I	
          FACT = 1	
          DO I = 2,N		
            FACT = FACT*I		
            IF (FACT.LE.0) STOP "Factorial: Overflow
          END DO		
        END FUNCTION FACT	

        INTEGER*8 FUNCTION LFACT(N)	
         INTEGER N	
         INTEGER K	
          LFACT = 0	
          DO K = 0,N - 1	
            LFACT = LFACT + FACT(K)	
            IF (LFACT.LE.0) STOP "Lfact: Overflow
          END DO		
        END FUNCTION LFACT	
      END MODULE LAIROTCAF	

      PROGRAM POKE
      USE LAIROTCAF
      INTEGER I

      WRITE (6,*) "Left factorials, from 0 to 10..."
      DO I = 0,10
        WRITE (6,1) I,LFACT(I)
    1   FORMAT ("
      END DO

      WRITE (6,*) "Left factorials, from 20 to 110 by tens..."
      DO I = 20,110,10
        WRITE (6,1) I,LFACT(I)
      END DO
      END
Task: Increasing gaps between consecutive Niven numbers







Python: 





def digit_sum(n, sum):
    sum += 1
    while n > 0 and n % 10 == 0:
        sum -= 9
        n /= 10
    
    return sum
    
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
 
print("Gap index  Gap    Niven index    Niven number")

niven = 1

while gap_index <= 22:
    sum = digit_sum(niven, sum)
    if niven % sum == 0:
        if niven > previous + gap:
            gap = niven - previous;
            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))
            gap_index += 1
        previous = niven
        niven_index += 1
    niven += 1




Fortran:        program nivengaps      
       implicit none
       integer*8 prev /1/, gap /0/, sum /0/
       integer*8 nividx /0/, niven /1/
       integer gapidx /1/
       
       character*13 idxfmt
       character*14 nivfmt
       write (*,*) 'Gap no  Gap   Niven index    Niven number '
       write (*,*) '------  ---  -------------  --------------'
       
 10    call divsum(niven, sum)
       if (mod(niven, sum) .EQ. 0) then
          if (niven .GT. prev + gap) then
             gap = niven - prev
             call fmtint(nividx,13,idxfmt)
             call fmtint(prev,14,nivfmt)
             write (*,20) gapidx,gap,idxfmt,nivfmt
             gapidx = gapidx + 1
          end if
          prev = niven
          nividx = nividx + 1
       end if          
       niven = niven + 1
       if (gapidx .LE. 32) go to 10
       
       stop
 20    format (i7,'  ',i3,'  ',a13,'  ',a14)       
       end program

C      Sum of divisors of NN, given the sum of divisors of NN-1       
       subroutine divsum(nn,sum)
          implicit none
          integer*8 n,nn,sum
          n = nn          
          sum = sum + 1
 30       if (n.GT.0 .AND. mod(n,10).EQ.0) then
             sum = sum - 9
             n = n / 10
             go to 30
          end if
       end subroutine  
 
       integer*8 function mod(a,b)
          implicit none
          integer*8 a,b
          mod = a - a/b * b
       end function

C      Format a positive integer with ',' as the thousands separator.
       subroutine fmtint(num, len, str)
          implicit none 
          integer*8 n, num
          integer pos, len, th
          character(*) str
          n=num
          pos=len
          th=2
 40       if (pos.GT.0) then
             if (n.EQ.0) then
                str(pos:pos) = ' '
             else
                str(pos:pos) = achar(mod(n,10) + iachar('0'))
                if (th.EQ.0 .AND. n.GE.10 .AND. pos.GT.1) then
                    th = 2
                    pos = pos-1
                    str(pos:pos) = ','
                else
                    th = th-1
                end if
            end if
            pos = pos - 1
            n = n/10
            go to 40
          end if    
       end subroutine