WeixiangYan/CodeTransOcean huggingface dataset:
Task: Cycle detection





Java: import java.util.function.*;
import static java.util.stream.IntStream.*;

public class CycleDetection {

    public static void main(String[] args) {
        brent(i -> (i * i + 1) % 255, 3);
    }

    static void brent(IntUnaryOperator f, int x0) {
        int cycleLength;
        int hare = x0;
        FOUND:
        for (int power = 1; ; power *= 2) {
            int tortoise = hare;
            for (int i = 1; i <= power; i++) {
                hare = f.applyAsInt(hare);
                 if (tortoise == hare) {
                    cycleLength = i;
                    break FOUND;
                }
            }
        }

        hare = x0;
        for (int i = 0; i < cycleLength; i++)
            hare = f.applyAsInt(hare);

        int cycleStart = 0;
        for (int tortoise = x0; tortoise != hare; cycleStart++) {
            tortoise = f.applyAsInt(tortoise);
            hare = f.applyAsInt(hare);
        }

        printResult(x0, f, cycleLength, cycleStart);
    }

    static void printResult(int x0, IntUnaryOperator f, int len, int start) {
        System.out.printf("Cycle length: %d%nCycle: ", len);
        iterate(x0, f).skip(start).limit(len)
                .forEach(n -> System.out.printf("%s ", n));
    }
}







Ada: generic
   type Element_Type is private;
package Brent is
   type Brent_Function is access function (X : Element_Type) return Element_Type;
   procedure Brent(F : Brent_Function; X0 : Element_Type; Lambda : out Integer; Mu : out Integer);
end Brent;
Task: Input_Output for pairs of numbers





Java: import java.util.Scanner;

public class Main {

	public static int doStuff(int a, int b){
	    int sum = a+b;
	    return sum;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		int n = in.nextInt();
		for(int i=0; i<n; i++){
			int a = in.nextInt();
			int b= in.nextInt();
			int result = doStuff(a, b);
			System.out.println(result);
		}
	}
}







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

procedure Main is
   count  : Integer;
   First  : Integer;
   Second : Integer;
begin
   Get (count);
   for I in 1 .. count loop
      Get (First);
      Get (Second);
      Put (Item => First + Second, Width => 1);
      New_Line;
   end loop;
end Main;
Task: Kahan summation





Java: public class KahanSummation {
    private static float kahanSum(float... fa) {
        float sum = 0.0f;
        float c = 0.0f;
        for (float f : fa) {
            float y = f - c;
            float t = sum + y;
            c = (t - sum) - y;
            sum = t;
        }
        return sum;
    }

    private static float epsilon() {
        float eps = 1.0f;
        while (1.0f + eps != 1.0f) eps /= 2.0f;
        return eps;
    }

    public static void main(String[] args) {
        float a = 1.0f;
        float b = epsilon();
        float c = -b;
        System.out.println("Epsilon      = " + b);
        System.out.println("(a + b) + c  = " + ((a + b) + c));
        System.out.println("Kahan sum    = " + kahanSum(a, b, c));
    }
}







Ada: with Ada.Text_Io; use Ada.Text_Io;

procedure Kahan is

   type Kahan_Summer is
      record
         Sum  : Float := 0.0;
         C    : Float := 0.0;
      end record;

   procedure Add (Acc : in out Kahan_Summer; Right : Float) is
      Y : constant Float := Right - Acc.C;
      T : constant Float := Acc.Sum + Y;
   begin
      Acc.C   := (T - Acc.Sum) - Y;
      acc.Sum := T;
   end Add;

   function Sum (Acc : Kahan_Summer) return Float
   is (Acc.Sum);

   function Epsilon return Float is
      E : Float := 1.000;
   begin
      while 1.0 + E /= 1.0 loop
         E := E / 2.0;
      end loop;
      return E;
   end Epsilon;

   A : constant Float := 1.000;
   B : constant Float := Epsilon;
   C : constant Float := -B;
   D : constant Float := (A + B) + C;
   K : Kahan_Summer;

   package Float_Io is new Ada.Text_Io.Float_Io (Float);
   use Float_Io;
begin
   Add (K, A);
   Add (K, B);
   Add (K, C);

   Default_Exp := 0;
   Default_Aft := 12;
   Put ("Epsilon     : "); Put (B); New_Line;
   Put ("(A + B) - C : "); Put (D); New_Line;
   Put ("Kahan sum   : "); Put (Sum (K)); New_Line;
end Kahan;
Task: ABC words





Java: import java.io.BufferedReader;
import java.io.FileReader;

public class AbcWords {
    public static void main(String[] args) {
        String fileName = "unixdict.txt";
        String chars = "abc";
        for (int i = 0; i + 1 < args.length
                && args[i].length() > 1
                && args[i].charAt(0) == '-'; ++i) {
            switch (args[i].charAt(1)) {
            case 'f':
                fileName = args[++i];
                break;
            case 'c':
                chars = args[++i];
                break;
            }
        }
        
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            int n = 0;
            while ((line = reader.readLine()) != null) {
                if (match(line, chars)) {
                    ++n;
                    System.out.printf("%3d: %-20s", n, line);
                    if (n % 3 == 0)
                        System.out.println();
                }
            }
            if (n > 0 && n % 3 != 0)
                System.out.println();
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }

    
    
    private static boolean match(String word, String chars) {
        int length = chars.length();
        boolean[] seen = new boolean[length];
        int wordLength = word.length();
        for (int w = 0; w < wordLength; ++w) {
            char ch = word.charAt(w);
            int index = -1;
            for (int c = 0; c < length; ++c) {
                if (ch == chars.charAt(c) && !seen[c]) {
                    index = c;
                    break;
                }
            }
            if (index == -1)
                continue;
            if (index + 1 == length)
                return index == 0 ? true : seen[index - 1];
            if (index > 0 && !seen[index - 1])
                return false;
            seen[index] = true;
        }
        return false;
    }
}







Ada: with Ada.Text_Io;
with Ada.Strings.Fixed;

procedure Abc_Words is
   use Ada.Text_Io;

   function Is_Abc_Word (Word : String) return Boolean is
      use Ada.Strings.Fixed;
      Pos_A : constant Natural := Index (Word, "a");
      Pos_B : constant Natural := Index (Word, "b");
      Pos_C : constant Natural := Index (Word, "c");
   begin
      return
        Pos_B > Pos_A and Pos_C > Pos_B and
        Pos_A /= 0 and Pos_B /= 0 and Pos_C /= 0;
   end Is_Abc_Word;

   Filename : constant String := "unixdict.txt";
   File     : File_Type;
   Column   : Ada.Text_Io.Count := 0;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word : constant String := Get_Line (File);
      begin
         if Is_Abc_Word (Word) then
            Set_Col (1 + Column);
            Column := (Column + 15) mod 120;
            Put (Word);
         end if;
      end;
   end loop;
   Close (File);
end Abc_Words;
Task: Two identical strings





Java: public class TwoIdenticalStrings {
    public static void main(String[] args) {
        System.out.println("Decimal Binary");
        for (int i = 0; i < 1_000; i++) {
            String binStr = Integer.toBinaryString(i);
            if (binStr.length() % 2 == 0) {
                int len = binStr.length() / 2;
                if (binStr.substring(0, len).equals(binStr.substring(len))) {
                    System.out.printf("%7d %s%n", i, binStr);
                }
            }
        }
    }
}







Ada: with Ada.Text_Io;        use Ada.Text_Io;
with Ada.Strings.Fixed;  use Ada.Strings.Fixed;

procedure Two_Identical is
   package Integer_Io is
     new Ada.Text_Io.Integer_Io (Integer);
   use Integer_Io;

   Image : String (1 .. 16);
   Pos_1, Pos_2 : Natural;
   Mid  : Natural;
begin
   for N in 1 .. 1000 loop
      Put (Image, N, Base => 2);
      Pos_1 := Index (Image, "#");
      Pos_2 := Index (Image, "#", Pos_1 + 1);
      Mid := (Pos_1 + Pos_2) / 2;
      if Image (Pos_1 + 1 .. Mid) = Image (Mid + 1 .. Pos_2 - 1) then
         Put (N, Width => 3); Put ("  "); Put (Image); New_Line;
      end if;
   end loop;
end Two_Identical;
Task: Verify distribution uniformity_Chi-squared test





Java: import static java.lang.Math.pow;
import java.util.Arrays;
import static java.util.Arrays.stream;
import org.apache.commons.math3.special.Gamma;

public class Test {

    static double x2Dist(double[] data) {
        double avg = stream(data).sum() / data.length;
        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));
        return sqs / avg;
    }

    static double x2Prob(double dof, double distance) {
        return Gamma.regularizedGammaQ(dof / 2, distance / 2);
    }

    static boolean x2IsUniform(double[] data, double significance) {
        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;
    }

    public static void main(String[] a) {
        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},
        {522573, 244456, 139979, 71531, 21461}};

        System.out.printf(" %4s %12s  %12s %8s   %s%n",
                "dof", "distance", "probability", "Uniform?", "dataset");

        for (double[] ds : dataSets) {
            int dof = ds.length - 1;
            double dist = x2Dist(ds);
            double prob = x2Prob(dof, dist);
            System.out.printf("%4d %12.3f  %12.8f    %5s    %6s%n",
                    dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO",
                    Arrays.toString(ds));
        }
    }
}







Ada: package Chi_Square is
   
   type Flt is digits 18;
   type Bins_Type is array(Positive range <>) of Natural;
   
   function Distance(Bins: Bins_Type) return Flt;
   
end Chi_Square;
Task: CSV to HTML translation





Java: 

grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body   : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row    : field ',' field '\r'? '\n';
field  : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");};
Field  : ~[,\n\r]+;







Ada: with Ada.Strings.Fixed;
with Ada.Text_IO;
with Templates_Parser;

procedure Csv2Html is
   use type Templates_Parser.Vector_Tag;

   Chars : Templates_Parser.Vector_Tag;
   Speeches : Templates_Parser.Vector_Tag;

   CSV_File : Ada.Text_IO.File_Type;
begin
   
   Ada.Text_IO.Open (File => CSV_File,
                     Mode => Ada.Text_IO.In_File,
                     Name => "data.csv");

   
   while not Ada.Text_IO.End_Of_File (CSV_File) loop
      declare
         Whole_Line : String := Ada.Text_IO.Get_Line (CSV_File);
         Comma_Pos : Natural := Ada.Strings.Fixed.Index (Whole_Line, ",");
      begin
         Chars := Chars & Whole_Line (Whole_Line'First .. Comma_Pos - 1);
         Speeches := Speeches & Whole_Line (Comma_Pos + 1 .. Whole_Line'Last);
      end;
   end loop;

   Ada.Text_IO.Close (CSV_File);

   
   declare
      Translations : constant Templates_Parser.Translate_Table :=
        (1 => Templates_Parser.Assoc ("CHAR", Chars),
         2 => Templates_Parser.Assoc ("SPEECH", Speeches));
   begin
      Ada.Text_IO.Put_Line
        (Templates_Parser.Parse ("table.tmplt", Translations));
   end;
end Csv2Html;
Task: Alternade words





Java: import java.io.*;
import java.util.*;

public class AlternadeWords {
    public static void main(String[] args) {
        try {
            Set<String> dictionary = new TreeSet<>();
            try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
                String line;
                while ((line = reader.readLine()) != null)
                    dictionary.add(line);
            }
            StringBuilder word1 = new StringBuilder();
            StringBuilder word2 = new StringBuilder();
            for (String word : dictionary) {
                int length = word.length();
                if (length < 6)
                    continue;
                word1.setLength(0);
                word2.setLength(0);
                for (int i = 0; i < length; i += 2) {
                    word1.append(word.charAt(i));
                    if (i + 1 < length)
                        word2.append(word.charAt(i + 1));
                }
                String w1 = word1.toString();
                String w2 = word2.toString();
                if (dictionary.contains(w1) && dictionary.contains(w2))
                    System.out.printf("%-10s%-6s%s\n", word, w1, w2);
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }
}







Ada: with Ada.Text_Io;
with Ada.Containers.Indefinite_Ordered_Maps;

procedure Alternade_Words is
   use Ada.Text_Io;

   package String_Maps is
     new Ada.Containers.Indefinite_Ordered_Maps (Key_Type     => String,
                                                 Element_Type => String);

   function Get_Odd (Word : String) return String is
      Odd : String (1 .. (Word'Length + 1) / 2);
   begin
      for Index in Odd'Range loop
         Odd (Index) := Word (1 + 2 * (Index - 1));
      end loop;
      return Odd;
   end Get_Odd;

   function Get_Even (Word : String) return String is
      Even : String (1 .. Word'Length / 2);
   begin
      for Index in Even'Range loop
         Even (Index) := Word (1 + 1 + 2 * (Index - 1));
      end loop;
      return Even;
   end Get_Even;

   Filename : constant String := "unixdict.txt";
   Words    : String_Maps.Map;
   File     : File_Type;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word : constant String := Get_Line (File);
      begin
         Words.Insert (Word, Word);
      end;
   end loop;
   Close (File);

   for Word of Words loop
      declare
         Odd  : constant String := Get_Odd  (Word);
         Even : constant String := Get_Even (Word);
      begin
         if
           Word'Length >= 6       and then
             Words.Contains (Odd) and then
             Words.Contains (Even)
         then
            Put (Word);
            Set_Col (15); Put (Odd);
            Set_Col (25); Put (Even);
            New_Line;
         end if;
      end;
   end loop;
end Alternade_Words;
Task: Pythagorean triples





Java: import java.math.BigInteger;
import static java.math.BigInteger.ONE;

public class PythTrip{

    public static void main(String[] args){
        long tripCount = 0, primCount = 0;

        
        BigInteger periLimit = BigInteger.valueOf(100),
                peri2 = periLimit.divide(BigInteger.valueOf(2)),
                peri3 = periLimit.divide(BigInteger.valueOf(3));

        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){
            BigInteger aa = a.multiply(a);
            
            for(BigInteger b = a.add(ONE);
                    b.compareTo(peri2) < 0; b = b.add(ONE)){
                BigInteger bb = b.multiply(b);
                BigInteger ab = a.add(b);
                BigInteger aabb = aa.add(bb);
                
                for(BigInteger c = b.add(ONE);
                        c.compareTo(peri2) < 0; c = c.add(ONE)){

                    int compare = aabb.compareTo(c.multiply(c));
                    
                    if(ab.add(c).compareTo(periLimit) > 0){
                        break;
                    }
                    
                    if(compare < 0){
                        break;
                    }else if (compare == 0){
                        tripCount++;
                        System.out.print(a + ", " + b + ", " + c);

                        
                        if(a.gcd(b).equals(ONE)){
                            System.out.print(" primitive");
                            primCount++;
                        }
                        System.out.println();
                    }
                }
            }
        }
        System.out.println("Up to a perimeter of " + periLimit + ", there are "
                + tripCount + " triples, of which " + primCount + " are primitive.");
    }
}







Ada: with Ada.Text_IO;

procedure Pythagorean_Triples is

   type Large_Natural is range 0 .. 2**63-1;
     

   procedure New_Triangle(A, B, C: Large_Natural;
                          Max_Perimeter: Large_Natural;
                          Total_Cnt, Primitive_Cnt: in out Large_Natural) is
      Perimeter: constant Large_Natural := A + B + C;
   begin
      if Perimeter <= Max_Perimeter then
         Primitive_Cnt := Primitive_Cnt + 1;
         Total_Cnt     := Total_Cnt + Max_Perimeter / Perimeter;
         New_Triangle(A-2*B+2*C,     2*A-B+2*C,    2*A-2*B+3*C,   Max_Perimeter, Total_Cnt, Primitive_Cnt);
         New_Triangle(A+2*B+2*C,     2*A+B+2*C,    2*A+2*B+3*C,   Max_Perimeter, Total_Cnt, Primitive_Cnt);
         New_Triangle(2*B+2*C-A,     B+2*C-2*A,    2*B+3*C-2*A,   Max_Perimeter, Total_Cnt, Primitive_Cnt);
      end if;
   end New_Triangle;

   T_Cnt, P_Cnt: Large_Natural;

begin
   for I in 1 .. 9 loop
      T_Cnt := 0;
      P_Cnt := 0;
      New_Triangle(3,4,5, 10**I, Total_Cnt => T_Cnt, Primitive_Cnt => P_Cnt);
      Ada.Text_IO.Put_Line("Up to 10 **" & Integer'Image(I) & " :" &
                             Large_Natural'Image(T_Cnt) & " Triples," &
                             Large_Natural'Image(P_Cnt) & " Primitives");
   end loop;
end Pythagorean_Triples;
Task: Call a foreign-language function





Java: public class JNIDemo
{
  static
  {  System.loadLibrary("JNIDemo");  }
  
  public static void main(String[] args)
  {
    System.out.println(callStrdup("Hello World!"));
  }
  
  private static native String callStrdup(String s);
}







Ada: with Ada.Text_IO;           use Ada.Text_IO;
with Interfaces.C;          use Interfaces.C;
with Interfaces.C.Strings;  use Interfaces.C.Strings;

procedure Test_C_Interface is
   function strdup (s1 : Char_Array) return Chars_Ptr;
   pragma Import (C, strdup, "_strdup");

   S1 : constant String := "Hello World!";
   S2 : Chars_Ptr;
begin
   S2 := strdup (To_C (S1));
   Put_Line (Value (S2));
   Free (S2);
end Test_C_Interface;
Task: Gray code





Java: public class Gray {
	public static long grayEncode(long n){
		return n ^ (n >>> 1);
	}
	
	public static long grayDecode(long n) {
		long p = n;
		while ((n >>>= 1) != 0)
			p ^= n;
		return p;
	}
	public static void main(String[] args){
		System.out.println("i\tBinary\tGray\tDecoded");
		for(int i = -1; i < 32;i++){
			System.out.print(i +"\t");
			System.out.print(Integer.toBinaryString(i) + "\t");
			System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
			System.out.println(grayDecode(grayEncode(i)));
		}
	}
}







Ada: with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;

procedure Gray is

   Bits : constant := 5; 
   subtype Values is Unsigned_8 range 0 .. 2 ** Bits - 1;
   package Values_Io is new Ada.Text_IO.Modular_IO (Values);

   function Encode (Binary : Values) return Values is
   begin
      return Binary xor Shift_Right (Binary, 1);
   end Encode;
   pragma Inline (Encode);

   function Decode (Gray : Values) return Values is
      Binary, Bit : Values;
      Mask        : Values := 2 ** (Bits - 1);
   begin
      Bit    := Gray and Mask;
      Binary := Bit;
      for I in 2 .. Bits loop
         Bit    := Shift_Right (Bit, 1);
         Mask   := Shift_Right (Mask, 1);
         Bit    := (Gray and Mask) xor Bit;
         Binary := Binary + Bit;
      end loop;
      return Binary;
   end Decode;
   pragma Inline (Decode);

   HT : constant Character := Character'Val (9);
   J  : Values;
begin
   Put_Line ("Num" & HT & "Binary" & HT & HT & "Gray" & HT & HT & "decoded");
   for I in Values'Range loop
      J := Encode (I);
      Values_Io.Put (I, 4);
      Put (": " & HT);
      Values_Io.Put (I, Bits + 2, 2);
      Put (" =>" & HT);
      Values_Io.Put (J, Bits + 2, 2);
      Put (" => " & HT);
      Values_Io.Put (Decode (J), 4);
      New_Line;
   end loop;
end Gray;
Task: File extension is in extensions list





Java: import java.util.Arrays;
import java.util.Comparator;

public class FileExt{
	public static void main(String[] args){
		String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"};
		String[] exts = {".txt",".gz","",".bat"};
		
		System.out.println("Extensions: " + Arrays.toString(exts) + "\n");
		
		for(String test:tests){
			System.out.println(test +": " + extIsIn(test, exts));
		}
	}
	
	public static boolean extIsIn(String test, String... exts){
		int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); 
		String filename = test.substring(lastSlash + 1);
		
		
		int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');
		String ext = filename.substring(lastDot);
		
		Arrays.sort(exts);
		
		return Arrays.binarySearch(exts, ext, new Comparator<String>() { 
			@Override                                                
			public int compare(String o1, String o2) {
				return o1.compareToIgnoreCase(o2);
			}
		}) >= 0;
	}
}







Ada: with Ada.Text_IO;                              use Ada.Text_IO;
with Ada.Strings.Fixed.Equal_Case_Insensitive; use Ada.Strings.Fixed;
with Ada.Strings.Bounded;

procedure Main is

   package B_String is new Ada.Strings.Bounded.Generic_Bounded_Length (30);
   use B_String;
   function is_equal (left, right : String) return Boolean renames
     Ada.Strings.Fixed.Equal_Case_Insensitive;

   type extension_list is array (Positive range <>) of Bounded_String;
   Ext_List : extension_list :=
     (To_Bounded_String ("zip"), To_Bounded_String ("rar"),
      To_Bounded_String ("7z"), To_Bounded_String ("gz"),
      To_Bounded_String ("archive"), To_Bounded_String ("A##"),
      To_Bounded_String ("tar.bz2"));
   type filename_list is array (Positive range <>) of Bounded_String;
   fnames : filename_list :=
     (To_Bounded_String ("MyData.a##"), To_Bounded_String ("MyData.tar.Gz"),
      To_Bounded_String ("MyData.gzip"), To_Bounded_String ("MyData..."),
      To_Bounded_String ("Mydata"), To_Bounded_String ("MyData_V1.0.tar.bz2"),
      To_Bounded_String ("MyData_v1.0.bz2"));
   Valid_Extension : Boolean;
begin
   for name of fnames loop
      Valid_Extension := False;
      Put (To_String (name));
      for ext of Ext_List loop
         declare
            S : String := "." & To_String (ext);
            T : String := Tail (Source => To_String (name), Count => S'Length);
         begin
            if is_equal (S, T) then
               Valid_Extension := True;
            end if;
         end;
      end loop;
      Set_Col (22);
      Put_Line (": " & Valid_Extension'Image);
   end loop;
end Main;
Task: Extreme floating point values





Java: public class Extreme {
    public static void main(String[] args) {
        double negInf = -1.0 / 0.0; 
        double inf = 1.0 / 0.0; 
        double nan = 0.0 / 0.0; 
        double negZero = -2.0 / inf;

        System.out.println("Negative inf: " + negInf);
        System.out.println("Positive inf: " + inf);
        System.out.println("NaN: " + nan);
        System.out.println("Negative 0: " + negZero);
        System.out.println("inf + -inf: " + (inf + negInf));
        System.out.println("0 * NaN: " + (0 * nan));
        System.out.println("NaN == NaN: " + (nan == nan));
    }
}







Ada: subtype Consistent_Float is Float range Float'Range;