WeixiangYan/CodeTransOcean huggingface dataset:
Task: Benford's law





Java: import java.math.BigInteger;
import java.util.Locale;

public class BenfordsLaw {

    private static BigInteger[] generateFibonacci(int n) {
        BigInteger[] fib = new BigInteger[n];
        fib[0] = BigInteger.ONE;
        fib[1] = BigInteger.ONE;
        for (int i = 2; i < fib.length; i++) {
            fib[i] = fib[i - 2].add(fib[i - 1]);
        }
        return fib;
    }

    public static void main(String[] args) {
        BigInteger[] numbers = generateFibonacci(1000);

        int[] firstDigits = new int[10];
        for (BigInteger number : numbers) {
            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
        }

        for (int i = 1; i < firstDigits.length; i++) {
            System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
        }
    }
}







Ada: with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; 

procedure Benford is
   
   subtype Nonzero_Digit is Natural range 1 .. 9;
   function First_Digit(S: String) return Nonzero_Digit is
      (if S(S'First) in '1' .. '9' 
         then Nonzero_Digit'Value(S(S'First .. S'First))
         else First_Digit(S(S'First+1 .. S'Last)));
      
   package N_IO is new Ada.Text_IO.Integer_IO(Natural);  
      
   procedure Print(D: Nonzero_Digit; Counted, Sum: Natural) is
      package Math is new Ada.Numerics.Generic_Elementary_Functions(Float);
      package F_IO is new Ada.Text_IO.Float_IO(Float);
      Actual: constant Float := Float(Counted) / Float(Sum);
      Expected: constant Float := Math.Log(1.0 + 1.0 / Float(D), Base => 10.0);
      Deviation: constant Float := abs(Expected-Actual);
   begin
      N_IO.Put(D, 5);
      N_IO.Put(Counted, 14);
      F_IO.Put(Float(Sum)*Expected, Fore => 16, Aft => 1, Exp => 0);
      F_IO.Put(100.0*Actual, Fore => 9, Aft => 2, Exp => 0); 
      F_IO.Put(100.0*Expected, Fore => 11, Aft => 2, Exp => 0); 
      F_IO.Put(100.0*Deviation, Fore => 13, Aft => 2, Exp => 0);
   end Print;
   
   Cnt: array(Nonzero_Digit) of Natural := (1 .. 9 => 0);   
   D: Nonzero_Digit;
   Sum: Natural := 0;
   Counter: Positive;       
       
begin     
   while not Ada.Text_IO.End_Of_File loop
      
      N_IO.Get(Counter); 
        
      D := First_Digit(Ada.Text_IO.Get_Line); 
        
      Cnt(D) := Cnt(D)+1;
      Sum := Sum + 1;
   end loop;
   Ada.Text_IO.Put_Line(" Digit  Found[total]   Expected[total]    Found[%]" 
                                          & "   Expected[%]   Difference[%]");
   for I in Nonzero_Digit loop
      Print(I, Cnt(I), Sum);
      Ada.Text_IO.New_Line;
   end loop;
end Benford;
Task: Hickerson series of almost integers





Java: import java.math.*;

public class Hickerson {

    final static String LN2 = "0.693147180559945309417232121458";

    public static void main(String[] args) {
        for (int n = 1; n <= 17; n++)
            System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
    }

    static boolean almostInteger(int n) {
        BigDecimal a = new BigDecimal(LN2);
        a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));

        long f = n;
        while (--n > 1)
            f *= n;

        BigDecimal b = new BigDecimal(f);
        b = b.divide(a, MathContext.DECIMAL128);

        BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);

        return c.toString().matches("0|9");
    }
}







Ada: with Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;

procedure Almost_Integers is

   type Real is new Long_Long_Float;

   package Real_IO is
      new Ada.Text_IO.Float_IO (Real);
   package Integer_IO is
      new Ada.Text_IO.Integer_IO (Integer);

   function Faculty (N : in Long_Long_Integer) return Long_Long_Integer is
      (if N < 2 then N else N * Faculty (N - 1));

   function Hickerson (N : in Integer) return Real
   is
      package Math is
         new Ada.Numerics.Generic_Elementary_Functions (Real);
      LN2         : constant Real := Math.Log (2.0, Base => Ada.Numerics.E);
      Numerator   : constant Real := Real (Faculty (Long_Long_Integer (N)));
      Denominator : constant Real := 2.0 * LN2 ** (N + 1);
   begin
      return Numerator / Denominator;
   end Hickerson;

   function Is_Almost_Integer (N : Real) return Boolean is
      Image : String (1 .. 100);
   begin
      Real_IO.Put (Image, N, Exp => 0, Aft => 2);

      pragma Assert (Image (Image'Last - 2) = '.');
      case Image (Image'Last - 1) is
         when '0' | '9' =>  return True;
         when others    =>  return False;
      end case;
   end Is_Almost_Integer;

   use Ada.Text_IO;
   Placeholder : String := " n                         h(n)  almost";
   Image_N : String renames Placeholder ( 1 ..  2);
   Image_H : String renames Placeholder ( 4 .. 31);
   Image_A : String renames Placeholder (34 .. 39);
begin
   Put_Line (Placeholder);
   Image_N := (others => '-');
   Image_H := (others => '-');
   Image_A := (others => '-');
   Put_Line (Placeholder);

   for N in 1 .. 17 loop
      declare
         H : constant Real    := Hickerson (N);
         I : constant Boolean := Is_Almost_Integer (H);
      begin
         Integer_IO.Put (Image_N, N);
         Real_IO.Put (Image_H, H, Exp => 0, Aft => 4);
         Image_A := (if I then "TRUE " else "FALSE");
         Put_Line (Placeholder);
      end;
   end loop;
end Almost_Integers;
Task: Additive primes





Java: public class additivePrimes {

    public static void main(String[] args) {
        int additive_primes = 0;
        for (int i = 2; i < 500; i++) {
            if(isPrime(i) && isPrime(digitSum(i))){
                additive_primes++;
                System.out.print(i + " ");
            }
        }
        System.out.print("\nFound " + additive_primes + " additive primes less than 500");
    }

    static boolean isPrime(int n) {
        int counter = 1;
        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {
            return false;
        }
        while (counter * 6 - 1 <= Math.sqrt(n)) {
            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {
                return false;
            } else {
                counter++;
            }
        }
        return true;
    }

    static int digitSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }
}







Ada: with Ada.Text_Io;

procedure Additive_Primes is

   Last    : constant := 499;
   Columns : constant := 12;

   type Prime_List is array (2 .. Last) of Boolean;

   function Get_Primes return Prime_List is
      Prime : Prime_List := (others => True);
   begin
      for P in Prime'Range loop
         if Prime (P) then
            for N in 2 .. Positive'Last loop
               exit when N * P not in Prime'Range;
               Prime (N * P) := False;
            end loop;
         end if;
      end loop;
      return Prime;
   end Get_Primes;

   function Sum_Of (N : Natural) return Natural is
      Image : constant String := Natural'Image (N);
      Sum   : Natural := 0;
   begin
      for Char of Image loop
         Sum := Sum + (if Char in '0' .. '9'
                       then Natural'Value ("" & Char)
                       else 0);
      end loop;
      return Sum;
   end Sum_Of;

   package Natural_Io is new Ada.Text_Io.Integer_Io (Natural);
   use Ada.Text_Io, Natural_Io;

   Prime : constant Prime_List := Get_Primes;
   Count : Natural := 0;
begin
   Put_Line ("Additive primes <500:");
   for N in Prime'Range loop
      if Prime (N) and then Prime (Sum_Of (N)) then
         Count := Count + 1;
         Put (N, Width => 5);
         if Count mod Columns = 0 then
            New_Line;
         end if;
      end if;
   end loop;
   New_Line;

   Put ("There are ");
   Put (Count, Width => 2);
   Put (" additive primes.");
   New_Line;
end Additive_Primes;
Task: Case-sensitivity of identifiers





Java: String dog = "Benjamin"; 
String Dog = "Samba";    
String DOG = "Bernie";   
@Inject Console console;
console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");







Ada: with Ada.Text_IO;
procedure Dogs is
   Dog : String := "Bernie";
begin
   Ada.Text_IO.Put_Line ("There is just one dog named " & DOG);
end Dogs;
Task: Sorting algorithms_Stooge sort





Java: import java.util.Arrays;

public class Stooge {
    public static void main(String[] args) {
        int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};
        stoogeSort(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static void stoogeSort(int[] L) {
        stoogeSort(L, 0, L.length - 1);
    }

    public static void stoogeSort(int[] L, int i, int j) {
        if (L[j] < L[i]) {
            int tmp = L[i];
            L[i] = L[j];
            L[j] = tmp;
        }
        if (j - i > 1) {
            int t = (j - i + 1) / 3;
            stoogeSort(L, i, j - t);
            stoogeSort(L, i + t, j);
            stoogeSort(L, i, j - t);
        }
    }
}







Ada: with Ada.Text_IO;
procedure Stooge is
   type Integer_Array is array (Positive range <>) of Integer;
   procedure Swap (Left, Right : in out Integer) is
      Temp : Integer := Left;
   begin
      Left  := Right;
      Right := Temp;
   end Swap;
   procedure Stooge_Sort (List : in out Integer_Array) is
      T : Natural := List'Length / 3;
   begin
      if List (List'Last) < List (List'First) then
         Swap (List (List'Last), List (List'First));
      end if;
      if List'Length > 2 then
         Stooge_Sort (List (List'First     .. List'Last - T));
         Stooge_Sort (List (List'First + T .. List'Last));
         Stooge_Sort (List (List'First     .. List'Last - T));
      end if;
   end Stooge_Sort;
   Test_Array : Integer_Array := (1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7);
begin
   Stooge_Sort (Test_Array);
   for I in Test_Array'Range loop
      Ada.Text_IO.Put (Integer'Image (Test_Array (I)));
      if I /= Test_Array'Last then
         Ada.Text_IO.Put (", ");
      end if;
   end loop;
   Ada.Text_IO.New_Line;
end Stooge;
Task: Truncate a file





Java: import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class TruncFile {
	public static void main(String[] args) throws IOException{
		if(args.length < 2){
			System.out.println("Usage: java TruncFile fileName newSize");
			return;
		}
		
		FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
		long newSize = Long.parseLong(args[1]);
		outChan.truncate(newSize);
		outChan.close();
	}
}







Ada: with Ada.Command_Line, Ada.Sequential_IO, Ada.Directories;

procedure Truncate_File is

   type Byte is mod 256;
   for Byte'Size use 8;

   package Byte_IO is new Ada.Sequential_IO(Byte);

   function Arg(N: Positive) return String renames Ada.Command_Line.Argument;
   function Args return Natural renames Ada.Command_Line.Argument_Count;

begin
   
   if Args < 2 or else Args > 3 then
      raise Program_Error
        with "usage: truncate_file <filename> <length> [<temp_file>]";
   end if;

   
   declare
      File_Name: String := Arg(1);
      Temp_Name: String := (if Args = 2 then Arg(1) & ".tmp" else Arg(3));
                             
      File, Temp: Byte_IO.File_Type;
      Count: Natural := Natural'Value(Arg(2));
      Value: Byte;
   begin
      
      Byte_IO.Open  (File => File, Mode => Byte_IO.In_File,  Name => File_Name);
      Byte_IO.Create(File => Temp, Mode => Byte_IO.Out_File, Name => Temp_Name);

      
      while (not Byte_IO.End_Of_File(File)) and Count > 0 loop
         Byte_IO.Read (File, Value);
         Byte_IO.Write(Temp, Value);
         Count := Count - 1;
      end loop;

      
      Byte_IO.Close(Temp);
      Byte_IO.Close(File);

      if Count = 0 then 
         
         Ada.Directories.Delete_File(Name => File_Name);
         Ada.Directories.Rename(Old_Name => Temp_Name, New_Name => File_Name);
      else 
         
         Ada.Directories.Delete_File(Name => Temp_Name);
         raise Program_Error
           with "Size of """ & File_Name & """ less than " & Arg(2);
      end if;
   end;
end Truncate_File;
Task: Sorting algorithms_Shell sort





Java: public static void shell(int[] a) {
	int increment = a.length / 2;
	while (increment > 0) {
		for (int i = increment; i < a.length; i++) {
			int j = i;
			int temp = a[i];
			while (j >= increment && a[j - increment] > temp) {
				a[j] = a[j - increment];
				j = j - increment;
			}
			a[j] = temp;
		}
		if (increment == 2) {
			increment = 1;
		} else {
			increment *= (5.0 / 11);
		}
	}
}







Ada: generic
   type Element_Type is digits <>;
   type Index_Type is (<>);
   type Array_Type is array(Index_Type range <>) of Element_Type;
package Shell_Sort is
   procedure Sort(Item : in out Array_Type);
end Shell_Sort;
Task: Deconvolution_1D





Java: import java.util.Arrays;

public class Deconvolution1D {
    public static int[] deconv(int[] g, int[] f) {
        int[] h = new int[g.length - f.length + 1];
        for (int n = 0; n < h.length; n++) {
            h[n] = g[n];
            int lower = Math.max(n - f.length + 1, 0);
            for (int i = lower; i < n; i++)
                h[n] -= h[i] * f[n - i];
            h[n] /= f[0];
        }
        return h;
    }

    public static void main(String[] args) {
        int[] h = { -8, -9, -3, -1, -6, 7 };
        int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 };
        int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
                96, 31, 55, 36, 29, -43, -7 };

        StringBuilder sb = new StringBuilder();
        sb.append("h = " + Arrays.toString(h) + "\n");
        sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n");
        sb.append("f = " + Arrays.toString(f) + "\n");
        sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n");
        System.out.println(sb.toString());
    }
}







Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   package real_io is new Float_IO (Long_Float);
   use real_io;

   type Vector is array (Natural range <>) of Long_Float;

   function deconv (g, f : Vector) return Vector is
      len : Positive :=
        Integer'Max ((g'Length - f'length), (f'length - g'length));
      h     : Vector (0 .. len);
      Lower : Natural := 0;
   begin
      for n in h'range loop
         h (n) := g (n);
         if n >= f'length then
            Lower := n - f'length + 1;
         end if;
         for i in Lower .. n - 1 loop
            h (n) := h (n) - (h (i) * f (n - i));
         end loop;
         h (n) := h (n) / f (0);
      end loop;
      return h;
   end deconv;

   procedure print (v : Vector) is
   begin
      Put ("(");
      for I in v'range loop
         Put (Item => v (I), Fore => 1, Aft => 1, Exp => 0);
         if I < v'Last then
            Put (" ");
         else
            Put_Line (")");
         end if;
      end loop;
   end print;

   h : Vector := (-8.0, -9.0, -3.0, -1.0, -6.0, 7.0);
   f : Vector :=
     (-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0, -9.0, 3.0, -2.0, 5.0, 2.0,
      -2.0, -7.0, -1.0);
   g : Vector :=
     (24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0, 23.0, 245.0, 25.0, 52.0, 25.0,
      -67.0, -96.0, 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0);
begin
   print (h);
   print (deconv (g, f));
   print (f);
   print (deconv (g, h));
end Main;
Task: Read a specific line from a file





Java: package linenbr7;

import java.io.*;

public class LineNbr7 {

    public static void main(String[] args) throws Exception {
        File f = new File(args[0]);
        if (!f.isFile() || !f.canRead())
            throw new IOException("can't read " + args[0]);

        BufferedReader br = new BufferedReader(new FileReader(f));
        try (LineNumberReader lnr = new LineNumberReader(br)) {
            String line = null;
            int lnum = 0;
            while ((line = lnr.readLine()) != null
                    && (lnum = lnr.getLineNumber()) < 7) {
            }

            switch (lnum) {
                case 0:
                    System.out.println("the file has zero length");
                    break;
                case 7:
                    boolean empty = "".equals(line);
                    System.out.println("line 7: " + (empty ? "empty" : line));
                    break;
                default:
                    System.out.println("the file has only " + lnum + " line(s)");
            }
        }
    }
}







Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Rosetta_Read is
   File : File_Type;
begin
   Open (File => File,
         Mode => In_File,
         Name => "rosetta_read.adb");
   Set_Line (File, To => 7);

   declare
      Line_7 : constant String := Get_Line (File);
   begin
      if Line_7'Length = 0 then
         Put_Line ("Line 7 is empty.");
      else
         Put_Line (Line_7);
      end if;
   end;

   Close (File);
exception
   when End_Error =>
      Put_Line ("The file contains fewer than 7 lines.");
      Close (File);
   when Storage_Error =>
      Put_Line ("Line 7 is too long to load.");
      Close (File);
end Rosetta_Read;
Task: URL encoding





Java: import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Main
{
    public static void main(String[] args) throws UnsupportedEncodingException
    {
        String normal = "http:
        String encoded = URLEncoder.encode(normal, "utf-8");
        System.out.println(encoded);
    }
}







Ada: with AWS.URL;
with Ada.Text_IO; use Ada.Text_IO;
procedure Encode is
   Normal : constant String := "http://foo bar/";
begin
   Put_Line (AWS.URL.Encode (Normal));
end Encode;
Task: LU decomposition





Java: import static java.util.Arrays.stream;
import java.util.Locale;
import static java.util.stream.IntStream.range;

public class Test {

    static double dotProduct(double[] a, double[] b) {
        return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum();
    }

    static double[][] matrixMul(double[][] A, double[][] B) {
        double[][] result = new double[A.length][B[0].length];
        double[] aux = new double[B.length];

        for (int j = 0; j < B[0].length; j++) {

            for (int k = 0; k < B.length; k++)
                aux[k] = B[k][j];

            for (int i = 0; i < A.length; i++)
                result[i][j] = dotProduct(A[i], aux);
        }
        return result;
    }

    static double[][] pivotize(double[][] m) {
        int n = m.length;
        double[][] id = range(0, n).mapToObj(j -> range(0, n)
                .mapToDouble(i -> i == j ? 1 : 0).toArray())
                .toArray(double[][]::new);

        for (int i = 0; i < n; i++) {
            double maxm = m[i][i];
            int row = i;
            for (int j = i; j < n; j++)
                if (m[j][i] > maxm) {
                    maxm = m[j][i];
                    row = j;
                }

            if (i != row) {
                double[] tmp = id[i];
                id[i] = id[row];
                id[row] = tmp;
            }
        }
        return id;
    }

    static double[][][] lu(double[][] A) {
        int n = A.length;
        double[][] L = new double[n][n];
        double[][] U = new double[n][n];
        double[][] P = pivotize(A);
        double[][] A2 = matrixMul(P, A);

        for (int j = 0; j < n; j++) {
            L[j][j] = 1;
            for (int i = 0; i < j + 1; i++) {
                double s1 = 0;
                for (int k = 0; k < i; k++)
                    s1 += U[k][j] * L[i][k];
                U[i][j] = A2[i][j] - s1;
            }
            for (int i = j; i < n; i++) {
                double s2 = 0;
                for (int k = 0; k < j; k++)
                    s2 += U[k][j] * L[i][k];
                L[i][j] = (A2[i][j] - s2) / U[j][j];
            }
        }
        return new double[][][]{L, U, P};
    }

    static void print(double[][] m) {
        stream(m).forEach(a -> {
            stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n));
            System.out.println();
        });
        System.out.println();
    }

    public static void main(String[] args) {
        double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}};

        double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1},
        {2.0, 5, 7, 1}};

        for (double[][] m : lu(a))
            print(m);

        System.out.println();

        for (double[][] m : lu(b))
            print(m);
    }
}







Ada: with Ada.Numerics.Generic_Real_Arrays;
generic
   with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>);
package Decomposition is

   
   procedure Decompose (A : Matrix.Real_Matrix; P, L, U : out Matrix.Real_Matrix);

end Decomposition;
Task: Sum data type





Java: import java.util.Arrays;

public class SumDataType {

    public static void main(String[] args) {
        for ( ObjectStore<?> e : Arrays.asList(new ObjectStore<String>("String"), new ObjectStore<Integer>(23), new ObjectStore<Float>(new Float(3.14159))) ) {
            System.out.println("Object : " + e);
        }
    }
    
    public static class ObjectStore<T> {
        private T object;
        public ObjectStore(T object) {
            this.object = object;
        }
        @Override
        public String toString() {
            return "value [" + object.toString() + "], type = " + object.getClass();
        }
    }

}







Ada: type Ret_Val (Found : Boolean) is record
   case Found is
      when True =>
         Position : Positive;
      when False =>
         null;
   end case;
end record;
Task: Optional parameters





Java: module OptionalParameters
    {
    typedef Type<String  >.Orderer as ColumnOrderer;
    typedef Type<String[]>.Orderer as RowOrderer;

    static String[][] sort(String[][]     table,
                           ColumnOrderer? orderer = Null,
                           Int            column  = 0,
                           Boolean        reverse = False,
                          )
        {
        
        orderer ?:= (s1, s2) -> s1 <=> s2;

        
        ColumnOrderer byString = reverse
                ? ((s1, s2) -> orderer(s1, s2).reversed)
                : orderer;

        
        RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);

        return table.sorted(byColumn);
        }

    void run()
        {
        String[][] table =
            [
            ["c", "x", "i"],
            ["a", "y", "p"],
            ["b", "z", "a"],
            ];

        show("original input", table);
        show("by default sort on column 0", sort(table));
        show("by column 2", sort(table, column=2));
        show("by column 2 reversed", sort(table, column=2, reverse=True));
        }

    void show(String title, String[][] table)
        {
        @Inject Console console;
        console.print($"{title}:");
        for (val row : table)
            {
            console.print($"  {row}");
            }
        console.print();
        }
    }







Ada: package Tables is

   type Table is private;

   type Ordering is (Lexicographic, Psionic, ...); 

   procedure Sort (It               : in out Table;
                   Order_By         : in Ordering := Lexicographic;
                   Column           : in Positive := 1;
                   Reverse_Ordering : in Boolean  := False);

private
   ... 
end Tables;