WeixiangYan/CodeTransOcean huggingface dataset:
Task: Numbers with equal rises and falls





Java: public class EqualRisesFalls {
    public static void main(String[] args) {
        final int limit1 = 200;
        final int limit2 = 10000000;
        System.out.printf("The first %d numbers in the sequence are:\n", limit1);
        int n = 0;
        for (int count = 0; count < limit2; ) {
            if (equalRisesAndFalls(++n)) {
                ++count;
                if (count <= limit1)
                    System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' ');
            }
        }
        System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n);
    }

    private static boolean equalRisesAndFalls(int n) {
        int total = 0;
        for (int previousDigit = -1; n > 0; n /= 10) {
            int digit = n % 10;
            if (previousDigit > digit)
                ++total;
            else if (previousDigit >= 0 && previousDigit < digit)
                --total;
            previousDigit = digit;
        }
        return total == 0;
    }
}






Fortran:       PROGRAM A296712
          INTEGER IDX, NUM, I
*         Index and number start out at zero
          IDX = 0
          NUM = 0 
*         Find and write the first 200 numbers
          WRITE (*,'(A)') 'The first 200 numbers are: '
          DO 100 I = 1, 200
              CALL NEXT NUM(IDX, NUM)
              WRITE (*,'(I4)',ADVANCE='NO') NUM
              IF (MOD(I,20).EQ.0) WRITE (*,*)
  100     CONTINUE
*         Find the 10,000,000th number
          WRITE (*,*)
          WRITE (*,'(A)',ADVANCE='NO') 'The 10,000,000th number is: '
  200     CALL NEXT NUM(IDX, NUM)
          IF (IDX.NE.10000000) GOTO 200
          WRITE (*,'(I8)') NUM
          STOP
      END    

*     Given index and current number, retrieve the next number
*     in the sequence.
      SUBROUTINE NEXT NUM(IDX, NUM) 
          INTEGER IDX, NUM
          LOGICAL IN SEQ
  100     NUM = NUM + 1
          IF (.NOT. IN SEQ(NUM)) GOTO 100
          IDX = IDX + 1           
      END
    
*     See whether N is in the sequence
      LOGICAL FUNCTION IN SEQ(N)
          INTEGER N, DL, DR, VAL, HEIGHT
*         Get first digit and divide value by 10
          DL = MOD(N, 10)
          VAL = N / 10
          HEIGHT = 0
  100     IF (VAL.NE.0) THEN
*             Retrieve digits by modulo and division
              DR = DL
              DL = MOD(VAL, 10)
              VAL = VAL / 10
*             Record rise or fall
              IF (DL.LT.DR) HEIGHT = HEIGHT + 1
              IF (DL.GT.DR) HEIGHT = HEIGHT - 1
              GOTO 100
          END IF
*         N is in the sequence if the final height is 0
          IN SEQ = HEIGHT.EQ.0
          RETURN
      END
Task: Length of an arc between two angles





Java: public static double arcLength(double r, double a1, double a2){
    return (360.0 - Math.abs(a2-a1))*Math.PI/180.0 * r;
}






Fortran: *-----------------------------------------------------------------------
* given:  polar coordinates of two points on a circle of known radius
* find:  length of the major arc between these points
*
*___Name_____Type___I/O___Description___________________________________
*   RAD      Real   In    Radius of circle, any unit of measure
*   ANG1     Real   In    Angle of first point, degrees
*   ANG2     Real   In    Angle of second point, degrees
*   MAJARC   Real   Out   Length of major arc, same units as RAD
*-----------------------------------------------------------------------
      FUNCTION MAJARC (RAD, ANG1, ANG2)
       IMPLICIT NONE
       REAL RAD, ANG1, ANG2, MAJARC

       REAL FACT                          
       PARAMETER (FACT = 3.1415926536 / 180.)
       REAL DIF

*       Begin
       MAJARC = 0.
       IF (RAD .LE. 0.) RETURN
       DIF = MOD(ABS(ANG1 - ANG2), 360.)   
       DIF = MAX(DIF, 360. - DIF)          
       MAJARC = RAD * DIF * FACT           
       RETURN
      END  

*-----------------------------------------------------------------------
      PROGRAM TMA
       IMPLICIT NONE
       INTEGER J
       REAL ANG1, ANG2, RAD, MAJARC, ALENG
       REAL DATARR(3,3)     
       DATA DATARR / 120.,  10., 10.,
     $                10., 120., 10.,
     $               180., 270., 10. /

       DO J = 1, 3
         ANG1 = DATARR(1,J)
         ANG2 = DATARR(2,J)
         RAD = DATARR(3,J)
         ALENG = MAJARC (RAD, ANG1, ANG2)        
         PRINT *, 'first angle: ', ANG1, ' second angle: ', ANG2, 
     $     ' radius: ', RAD, ' Length of major arc: ', ALENG
       END DO
      END
Task: Matrix with two diagonals





Java: package example.diagdiag;

public class Program {

    public static void main(String[] args) {
        DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7);
        System.out.println(A);
    }

}

class DiagonalDiagonalMatrix {

    final int n;
    private double[][] a = null;

    public Matrix(int n) {
        this.n = n;
    }

    public double get(int i, int j) {
        if (a == null) {
            return (i == j || i == n - j + 1) ? 1.0 : 0.0;
        } else {
            return a[i - 1][j - 1];
        }
    }















    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sb.append('\t');
                sb.append(get(i, j));
            }
            sb.append('\n');
        }
        return sb.toString();
    }

}






Fortran: program prog

    dimension a(100, 100)

    n = 7
	
    j1 = 1
    j2 = n
    do i = 1, n
        do j = 1, n
            a(i, j) = 0.
        end do
        a(i, j1) = 1
        a(i, j2) = 1
        j1 = j1 + 1
        j2 = j2 - 1
    end do

    do i = 1, n
        print *, (a(i, j), j=1,n)
    end do

end
Task: Here document





Java: package rosettacode.heredoc;
public class MainApp {
	public static void main(String[] args) {
		String hereDoc = """
				This is a multiline string.
				It includes all of this text,
				but on separate lines in the code.
				 """;
		System.out.println(hereDoc);
	}
}






Fortran:       INTEGER I         
      CHARACTER*666 I AM    
      I AM =                                                           "<col72
C              111111111122222222223333333333444444444455555555556666666666
C     123456789012345678901234567890123456789012345678901234567890123456789
     1                                                                  <col72
     2              I AM                                                <col72
     3                                                                  <col72
     4           THAT I AM                                              <col72
     5"

Chug through the text blob.
      DO I = 0,600,66   
        WRITE (6,1) I AM(I + 1:I + 66)  
    1   FORMAT (A66)            
      END DO                
      END
Task: Loops_Infinite





Java: while (true) {
   System.out.println("SPAM");
}






Fortran:       
   10 WRITE(*,*) 'SPAM'
      GO TO 10
      END
Task: Assertions in design by contract





Java: (...)
int feedForward(double[] inputs) {
    assert inputs.length == weights.length : "weights and input length mismatch";

    double sum = 0;
    for (int i = 0; i < weights.length; i++) {
        sum += inputs[i] * weights[i];
    }
    return activate(sum);
}
(...)






Fortran:       SUBROUTINE AFFIRM(CONDITION,MESSAGE)
        LOGICAL CONDITION
        CHARACTER*(*) MESSAGE
         IF (CONDITION) RETURN      
         WRITE (6,*) MESSAGE
         STOP "Oops. Confusion
       END
Task: Function definition





Java: module MultiplyExample
    {
    static <Value extends Number> Value multiply(Value n1, Value n2)
        {
        return n1 * n2;
        }

    void run()
        {
        (Int i1, Int i2) = (7, 3);
        Int i3 = multiply(i1, i2);
        (Double d1, Double d2) = (2.7182818, 3.1415);
        Double d3 = multiply(d1, d2);
        @Inject Console console;
        console.print($"{i1}*{i2}={i3}, {d1}*{d2}={d3}");
        }
    }






Fortran:      XMULTF(X,Y)=X*Y
Task: Determinant and permanent





Java: import java.util.Scanner;

public class MatrixArithmetic {
	public static double[][] minor(double[][] a, int x, int y){
		int length = a.length-1;
		double[][] result = new double[length][length];
		for(int i=0;i<length;i++) for(int j=0;j<length;j++){
			if(i<x && j<y){
				result[i][j] = a[i][j];
			}else if(i>=x && j<y){
				result[i][j] = a[i+1][j];
			}else if(i<x && j>=y){
				result[i][j] = a[i][j+1];
			}else{ 
				result[i][j] = a[i+1][j+1];
			}
		}
		return result;
	}
	public static double det(double[][] a){
		if(a.length == 1){
			return a[0][0];
		}else{
			int sign = 1;
			double sum = 0;
			for(int i=0;i<a.length;i++){
				sum += sign * a[0][i] * det(minor(a,0,i));
				sign *= -1;
			}
			return sum;
		}
	}
	public static double perm(double[][] a){
		if(a.length == 1){
			return a[0][0];
		}else{
			double sum = 0;
			for(int i=0;i<a.length;i++){
				sum += a[0][i] * perm(minor(a,0,i));
			}
			return sum;
		}
	}
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int size = sc.nextInt();
		double[][] a = new double[size][size];
		for(int i=0;i<size;i++) for(int j=0;j<size;j++){
			a[i][j] = sc.nextDouble();
		}
		sc.close();
		System.out.println("Determinant: "+det(a));
		System.out.println("Permanent: "+perm(a));
	}
}






Fortran: 



































program f
  implicit none
  real, dimension(3,3) :: j, m
  data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/
  data m/2, 9, 4, 7, 5, 3, 6, 1, 8/
  write(6,*) 'j example, determinant: ',det(j,3,-1)
  write(6,*) 'j example, permanent:   ',det(j,3,1)
  write(6,*) 'maxima, determinant:    ',det(m,3,-1)
  write(6,*) 'maxima, permanent:      ',det(m,3,1)

contains

  recursive function det(a,n,permanent) result(accumulation)
    
    
    real, dimension(n,n), intent(in) :: a
    integer, intent(in) :: n, permanent
    real, dimension(n-1, n-1) :: b
    real :: accumulation
    integer :: i, sgn
    if (n .eq. 1) then
      accumulation = a(1,1)
    else
      accumulation = 0
      sgn = 1
      do i=1, n
        b(:, :(i-1)) = a(2:, :i-1)
        b(:, i:) = a(2:, i+1:)
        accumulation = accumulation + sgn * a(1, i) * det(b, n-1, permanent)
        sgn = sgn * permanent
      enddo
    endif
  end function det

end program f
Task: Sum of divisors





Java: public class DivisorSum {
    private static long divisorSum(long n) {
        var total = 1L;
        var power = 2L;
        
        for (; (n & 1) == 0; power <<= 1, n >>= 1) {
            total += power;
        }
        
        for (long p = 3; p * p <= n; p += 2) {
            long sum = 1;
            for (power = p; n % p == 0; power *= p, n /= p) {
                sum += power;
            }
            total *= sum;
        }
        
        if (n > 1) {
            total *= n + 1;
        }
        return total;
    }

    public static void main(String[] args) {
        final long limit = 100;
        System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
        for (long n = 1; n <= limit; ++n) {
            System.out.printf("%4d", divisorSum(n));
            if (n % 10 == 0) {
                System.out.println();
            }
        }
    }
}






Fortran:        program DivSum
       implicit none
       integer i, j, col, divs(100)
       
       do 10 i=1, 100, 1
 10        divs(i) = 1
 
       do 20 i=2, 100, 1
           do 20 j=i, 100, i
 20            divs(j) = divs(j) + i
 
       col = 0
       do 30 i=1, 100, 1
           write (*,'(I4)',advance='no') divs(i)
           col = col + 1
           if (col .eq. 10) then
               col = 0
               write (*,*)
           end if
 30    continue
       end program
Task: Sorting algorithms_Bead sort





Java: public class BeadSort 
{
	public static void main(String[] args)
	{
		BeadSort now=new BeadSort();
		int[] arr=new int[(int)(Math.random()*11)+5];
		for(int i=0;i<arr.length;i++)
			arr[i]=(int)(Math.random()*10);
		System.out.print("Unsorted: ");
		now.display1D(arr);
		
		int[] sort=now.beadSort(arr);
		System.out.print("Sorted: ");
		now.display1D(sort);
	}
	int[] beadSort(int[] arr)
	{
		int max=a[0];
		for(int i=1;i<arr.length;i++)
			if(arr[i]>max)
				max=arr[i];
		
		
		char[][] grid=new char[arr.length][max];
		int[] levelcount=new int[max];
		for(int i=0;i<max;i++)
		{
			levelcount[i]=0;
			for(int j=0;j<arr.length;j++)
				grid[j][i]='_';
		}
		
		
		
		for(int i=0;i<arr.length;i++)
		{
			int num=arr[i];
			for(int j=0;num>0;j++)
			{
				grid[levelcount[j]++][j]='*';
				num--;
			}
		}
		System.out.println();
		display2D(grid);
		
		int[] sorted=new int[arr.length];
		for(int i=0;i<arr.length;i++)
		{
			int putt=0;
			for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++)
				putt++;
			sorted[i]=putt;
		}
		
		return sorted;
	}
	void display1D(int[] arr)
	{
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}
	void display1D(char[] arr)
	{
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}
	void display2D(char[][] arr)
	{
		for(int i=0;i<arr.length;i++)
			display1D(arr[i]);
		System.out.println();
	}
}






Fortran: program BeadSortTest
  use iso_fortran_env 
  
  
  
  

  integer, dimension(7) :: a = (/ 7, 3, 5, 1, 2, 1, 20 /)

  call beadsort(a)
  print *, a

contains

  subroutine beadsort(a)
    integer, dimension(:), intent(inout) :: a

    integer, dimension(maxval(a), maxval(a)) :: t
    integer, dimension(maxval(a)) :: s
    integer :: i, m

    m = maxval(a)
    
    if ( any(a < 0) ) then
       write(ERROR_UNIT,*) "can't sort"
       return
    end if

    t = 0
    forall(i=1:size(a)) t(i, 1:a(i)) = 1  
    forall(i=1:m)             
       s(i) = sum(t(:, i))    
       t(:, i) = 0            
       t(1:s(i), i) = 1       
    end forall
    
    forall(i=1:size(a)) a(i) = sum(t(i,:))
    
  end subroutine beadsort

end program BeadSortTest
Task: Möbius function





Java: public class MöbiusFunction {

    public static void main(String[] args) {
        System.out.printf("First 199 terms of the möbius function are as follows:%n    ");
        for ( int n = 1 ; n < 200 ; n++ ) {
            System.out.printf("%2d  ", möbiusFunction(n));
            if ( (n+1) % 20 == 0 ) {
                System.out.printf("%n");
            }
        }
    }
    
    private static int MU_MAX = 1_000_000;
    private static int[] MU = null;
    
    
    private static int möbiusFunction(int n) {
        if ( MU != null ) {
            return MU[n];
        }
        
        
        MU = new int[MU_MAX+1];
        int sqrt = (int) Math.sqrt(MU_MAX);
        for ( int i = 0 ; i < MU_MAX ; i++ ) {
            MU[i] = 1;
        }
        
        for ( int i = 2 ; i <= sqrt ; i++ ) {
            if ( MU[i] == 1 ) {
                
                for ( int j = i ; j <= MU_MAX ; j += i ) {
                    MU[j] *= -i;
                }
                
                for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {
                    MU[j] = 0;
                }
            }
        }
        
        for ( int i = 2 ; i <= MU_MAX ; i++ ) {
            if ( MU[i] == i ) {
                MU[i] = 1;
            }
            else if ( MU[i] == -i ) {
                MU[i] = -1;
            }
            else if ( MU[i] < 0 ) {
                MU[i] = 1;               
            }
            else if ( MU[i] > 0 ) {
                MU[i] = -1;
            }
        }
        return MU[n];
    }

}






Fortran: program moebius
    use iso_fortran_env, only: output_unit

    integer, parameter          :: mu_max=1000000, line_break=20
    integer, parameter          :: sqroot=int(sqrt(real(mu_max)))
    integer                     :: i, j
    integer, dimension(mu_max)  :: mu

    mu = 1

    do i = 2, sqroot
        if (mu(i) == 1) then
            do j = i, mu_max, i
                mu(j) = mu(j) * (-i)
            end do

            do j = i**2, mu_max, i**2
                mu(j) = 0
            end do
        end if
    end do

    do i = 2, mu_max
        if (mu(i) == i) then
            mu(i) = 1
        else if (mu(i) == -i) then
            mu(i) = -1
        else if (mu(i) < 0) then
            mu(i) = 1
        else if (mu(i) > 0) then
            mu(i) = -1
        end if
    end do

    write(output_unit,*) "The first 199 terms of the Möbius sequence are:"
    write(output_unit,'(3x)', advance="no") 
    do i = 1, 199
        write(output_unit,'(I2,x)', advance="no") mu(i)
        if (modulo(i+1, line_break) == 0) write(output_unit,*)
    end do
end program moebius
Task: Product of divisors





Java: public class ProductOfDivisors {
    private static long divisorCount(long n) {
        long total = 1;
        
        for (; (n & 1) == 0; n >>= 1) {
            ++total;
        }
        
        for (long p = 3; p * p <= n; p += 2) {
            long count = 1;
            for (; n % p == 0; n /= p) {
                ++count;
            }
            total *= count;
        }
        
        if (n > 1) {
            total *= 2;
        }
        return total;
    }

    private static long divisorProduct(long n) {
        return (long) Math.pow(n, divisorCount(n) / 2.0);
    }

    public static void main(String[] args) {
        final long limit = 50;
        System.out.printf("Product of divisors for the first %d positive integers:%n", limit);
        for (long n = 1; n <= limit; n++) {
            System.out.printf("%11d", divisorProduct(n));
            if (n % 5 == 0) {
                System.out.println();
            }
        }
    }
}






Fortran:        program divprod
       implicit none
       integer divis(50), i, j
       do 10 i=1, 50
 10        divis(i) = 1
       do 20 i=1, 50
           do 20 j=i, 50, i
 20            divis(j) = divis(j)*i
       do 30 i=1, 50
           write (*,'(I10)',advance='no') divis(i)
 30        if (i/5 .ne. (i-1)/5) write (*,*)            
       end program
Task: Playing cards





Java: public enum Pip { Two, Three, Four, Five, Six, Seven, 
    Eight, Nine, Ten, Jack, Queen, King, Ace }






Fortran: MODULE Cards

IMPLICIT NONE

  TYPE Card
    CHARACTER(5) :: value
    CHARACTER(8) :: suit
  END TYPE Card

  TYPE(Card) :: deck(52), hand(52)
  TYPE(Card) :: temp

  CHARACTER(5) :: pip(13) = (/"Two  ", "Three", "Four ", "Five ", "Six  ", "Seven", "Eight", "Nine ", "Ten  ", &
                              "Jack ", "Queen", "King ", "Ace  "/)
  CHARACTER(8) :: suits(4) = (/"Clubs   ", "Diamonds", "Hearts  ", "Spades  "/)
  INTEGER :: i, j, n, rand, dealt = 0
  REAL :: x

CONTAINS
 
  SUBROUTINE Init_deck
  
    DO i = 1, 4
      DO j = 1, 13
        deck((i-1)*13+j) = Card(pip(j), suits(i))
      END DO
    END DO
  END SUBROUTINE Init_deck
 
  SUBROUTINE Shuffle_deck
  
    DO i = 52-dealt, 1, -1
      CALL RANDOM_NUMBER(x)
      rand = INT(x * i) + 1
      temp = deck(rand)
      deck(rand) = deck(i)
      deck(i) = temp
    END DO
  END SUBROUTINE Shuffle_deck

  SUBROUTINE Deal_hand(number)
  
    INTEGER :: number
    DO i = 1, number
      hand(i) = deck(dealt+1)
      dealt = dealt + 1
    END DO
  END SUBROUTINE

  SUBROUTINE Print_hand
  
    DO i = 1, dealt
      WRITE (*, "(3A)") TRIM(deck(i)%value), " of ", TRIM(deck(i)%suit)
    END DO
    WRITE(*,*)
  END SUBROUTINE Print_hand
 
  SUBROUTINE Print_deck
  
    DO i = dealt+1, 52
      WRITE (*, "(3A)") TRIM(deck(i)%value), " of ", TRIM(deck(i)%suit)
    END DO
    WRITE(*,*)
  END SUBROUTINE Print_deck

END MODULE Cards
Task: Two sum





Java: import java.util.Arrays;

public class TwoSum {

    public static void main(String[] args) {
        long sum = 21;
        int[] arr = {0, 2, 11, 19, 90};

        System.out.println(Arrays.toString(twoSum(arr, sum)));
    }

    public static int[] twoSum(int[] a, long target) {
        int i = 0, j = a.length - 1;
        while (i < j) {
            long sum = a[i] + a[j];
            if (sum == target)
                return new int[]{i, j};
            if (sum < target) i++;
            else j--;
        }
        return null;
    }
}






Fortran: program twosum
  implicit none

  integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/)
  integer, parameter :: target_val = 21
  integer :: nelem
  integer :: i, j
  logical :: success = .false.

  nelem = size(list)
  outer:do i = 1,nelem
     do j = i+1,nelem
        success = list(i) + list(j) == target_val
        if (success) exit outer
     end do
  end do outer

  if (success) then
     
     print('("(",2(i3.1,1X),")",3(A1,i3.1))'), i,j, ":", list(i), "+", list(j), "=", target_val
  else
     print*, "Failed"
  end if

end program twosum
Task: Find the last Sunday of each month





Java: import java.util.Scanner;

public class LastSunday 
{
	static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"};
	
	public static int[] findLastSunday(int year)
	{
		boolean isLeap = isLeapYear(year);
		
		int[] days={31,isLeap?29:28,31,30,31,30,31,31,30,31,30,31};
		int[] lastDay=new int[12];
		
		for(int m=0;i<12;i++)
		{
			int d;
			for(d=days[m]; getWeekDay(year,m,d)!=0; d--)
				;
			lastDay[m]=d;
		}
		
		return lastDay;
	}
	
	private static boolean isLeapYear(int year)
	{
		if(year%4==0)
		{
			if(year%100!=0)
				return true;
			else if (year%400==0)
				return true;
		}
		return false;
	}
	
	private static int getWeekDay(int y, int m, int d)
	{
		int f=y+d+3*m-1;
		m++;
		
		if(m<3)
			y--;
		else
			f-=(int)(0.4*m+2.3);
		
		f+=(int)(y/4)-(int)((y/100+1)*0.75);
		f%=7;
		
		return f;
	}
	
	private static void display(int year, int[] lastDay)
	{
		System.out.println("\nYEAR: "+year);
		for(int m=0;i<12;i++)
			System.out.println(months[m]+": "+lastDay[m]);
	}
	
	public static void main(String[] args) throws Exception
	{
		System.out.print("Enter year: ");
		Scanner s=new Scanner(System.in);
		
		int y=Integer.parseInt(s.next());
		
		int[] lastDay = findLastSunday(y);
		display(y, lastDay);
		
		s.close();
	}
}






Fortran:       D = DAYNUM(Y,M,D)    
      DAYNUM(Y,M,D) = D