WeixiangYan/CodeTransOcean huggingface dataset:
Task: Look-and-say sequence



C#: using System;
using System.Text;
using System.Linq;

class Program
{
    static string lookandsay(string number)
    {
        StringBuilder result = new StringBuilder();

        char repeat = number[0];
        number = number.Substring(1, number.Length-1)+" ";
        int times = 1;
      
        foreach (char actual in number)
        {
            if (actual != repeat)
            {
                result.Append(Convert.ToString(times)+repeat);
                times = 1;
                repeat = actual;
            }
            else
            {
                times += 1;
            }
        }
        return result.ToString();
    }

    static void Main(string[] args)
    {
        string num = "1"; 

        foreach (int i in Enumerable.Range(1, 10)) {
             Console.WriteLine(num);
             num = lookandsay(num);             
        }
    }
}



Java: public static String lookandsay(String number){
	StringBuilder result= new StringBuilder();

	char repeat= number.charAt(0);
	number= number.substring(1) + " ";
	int times= 1;

	for(char actual: number.toCharArray()){
		if(actual != repeat){
			result.append(times + "" + repeat);
			times= 1;
			repeat= actual;
		}else{
			times+= 1;
		}
	}
	return result.toString();
}
Task: Stack



C#: 
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek(); 
top = stack.Pop();


System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek(); 
top = stack.Pop();



Java: import java.util.Stack;

public class StackTest {
    public static void main( final String[] args ) {
        final Stack<String> stack = new Stack<String>();

        System.out.println( "New stack empty? " + stack.empty() );

        stack.push( "There can be only one" );
        System.out.println( "Pushed stack empty? " + stack.empty() );
        System.out.println( "Popped single entry: " + stack.pop() );

        stack.push( "First" );
        stack.push( "Second" );
        System.out.println( "Popped entry should be second: " + stack.pop() );

        
        stack.pop();
        stack.pop();
    }
}
Task: Totient function



C#: using static System.Console;
using static System.Linq.Enumerable;

public class Program
{
    static void Main()
    {
        for (int i = 1; i <= 25; i++) {
            int t = Totient(i);
            WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
        }
        WriteLine();
        for (int i = 100; i <= 100_000; i *= 10) {
            WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
        }
    }

    static int Totient(int n) {
        if (n < 3) return 1;
        if (n == 3) return 2;

        int totient = n;

        if ((n & 1) == 0) {
            totient >>= 1;
            while (((n >>= 1) & 1) == 0) ;
        }

        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0) {
                totient -= totient / i;
                while ((n /= i) % i == 0) ;
            }
        }
        if (n > 1) totient -= totient / n;
        return totient;
    }
}



Java: public class TotientFunction {

    public static void main(String[] args) {
        computePhi();
        System.out.println("Compute and display phi for the first 25 integers.");
        System.out.printf("n  Phi  IsPrime%n");
        for ( int n = 1 ; n <= 25 ; n++ ) {
            System.out.printf("%2d  %2d  %b%n", n, phi[n], (phi[n] == n-1));
        }
        for ( int i = 2 ; i < 8 ; i++ ) {
            int max = (int) Math.pow(10, i);
            System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max));
        }
    }
    
    private static int countPrimes(int min, int max) {
        int count = 0;
        for ( int i = min ; i <= max ; i++ ) {
            if ( phi[i] == i-1 ) {
                count++;
            }
        }
        return count;
    }

    private static final int max = 10000000;
    private static final int[] phi = new int[max+1];

    private static final void computePhi() {
        for ( int i = 1 ; i <= max ; i++ ) {
            phi[i] = i;
        }
        for ( int i = 2 ; i <= max ; i++ ) {
            if (phi[i] < i) continue;
            for ( int j = i ; j <= max ; j += i ) {
                phi[j] -= phi[j] / i;
            }
        }
    }

}
Task: Conditional structures



C#: if (condition)
{
   
}

if (condition)
{
  
}
else if (condition2)
{
  
}
else
{
  
}



Java: if (s == 'Hello World') {
    foo();
} else if (s == 'Bye World') {
    bar();
} else {
    deusEx();
}
Task: Sort using a custom comparator



C#: using System;
using System.Collections.Generic;

namespace RosettaCode {
    class SortCustomComparator {
        
        public void CustomSort() {
            String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
            List<String> list = new List<string>(items);

            DisplayList("Unsorted", list);
            
            list.Sort(CustomCompare);
            DisplayList("Descending Length", list);

            list.Sort();
            DisplayList("Ascending order", list);
        }

        
        public int CustomCompare(String x, String y) {
            int result = -x.Length.CompareTo(y.Length);
            if (result == 0) {
                result = x.ToLower().CompareTo(y.ToLower());
            }

            return result;
        }

        
        public void DisplayList(String header, List<String> theList) {
            Console.WriteLine(header);
            Console.WriteLine("".PadLeft(header.Length, '*'));
            foreach (String str in theList) {
                Console.WriteLine(str);
            }
            Console.WriteLine();
        }
    }
}



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

public class Test {
  public static void main(String[] args) {
    String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};

    Arrays.sort(strings, new Comparator<String>() {
      public int compare(String s1, String s2) {
        int c = s2.length() - s1.length();
        if (c == 0)
          c = s1.compareToIgnoreCase(s2);
        return c;
      }
    });

    for (String s: strings)
      System.out.print(s + " ");
  }
}
Task: Sorting algorithms_Radix sort



C#: using System;

namespace RadixSort
{
    class Program
    {
        static void Sort(int[] old)
        {
            int i, j;
            int[] tmp = new int[old.Length];
            for (int shift = 31; shift > -1; --shift)
            {
                j = 0;
                for (i = 0; i < old.Length; ++i)
                {
                    bool move = (old[i] << shift) >= 0;
                    if (shift == 0 ? !move : move)  
                        old[i-j] = old[i];
                    else                            
                        tmp[j++] = old[i];
                }
                Array.Copy(tmp, 0, old, old.Length-j, j);
            }
        }
        static void Main(string[] args)
        {
            int[] old = new int[] { 2, 5, 1, -3, 4 };
            Console.WriteLine(string.Join(", ", old));
            Sort(old);
            Console.WriteLine(string.Join(", ", old));
            Console.Read();
        }
    }
}



Java: public static int[] sort(int[] old) {
    
    for (int shift = Integer.SIZE - 1; shift > -1; shift--) {
        
        int[] tmp = new int[old.length];
        
        int j = 0;

        
        for (int i = 0; i < old.length; i++) {
            
            boolean move = old[i] << shift >= 0;

            
            if (shift == 0 ? !move : move) {
                tmp[j] = old[i];
                j++;
            } else {
                
                old[i - j] = old[i];
            }
        }

        
        for (int i = j; i < tmp.length; i++) {
            tmp[i] = old[i - j];
        }

        
        old = tmp;
    }

    return old;
}
Task: List comprehensions



C#: using System.Linq;

static class Program
{
  static void Main()
  {
    var ts =
      from a in Enumerable.Range(1, 20)
      from b in Enumerable.Range(a, 21 - a)
      from c in Enumerable.Range(b, 21 - b)
      where a * a + b * b == c * c
      select new { a, b, c };

      foreach (var t in ts)
        System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
  }
}



Java: 
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
    static void main(String... args){
        System.out.println(run(20));
    }

    static List<List<Integer>> run(int n){
        return
            
            
            range(1, n).mapToObj(
                x -> range(x, n).mapToObj(
                    y -> range(y, n).mapToObj(
                        z -> new Integer[]{x, y, z}
                    )
                )
            )
                .flatMap(identity())
                .flatMap(identity())
                
                .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
                
                .map(Arrays::asList)
                
                .collect(toList())
        ;
    }
}
Task: Sorting algorithms_Selection sort



C#: class SelectionSort<T> where T : IComparable {
    public T[] Sort(T[] list) {
        int k;
        T temp;

        for (int i = 0; i < list.Length; i++) {
            k = i;
            for (int j=i + 1; j < list.Length; j++) {
                if (list[j].CompareTo(list[k]) < 0) {
                    k = j;
                }
            }
            temp = list[i];
            list[i] = list[k];
            list[k] = temp;
        }

        return list;
    }
}



Java: public static void sort(int[] nums){
	for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
		int smallest = Integer.MAX_VALUE;
		int smallestAt = currentPlace+1;
		for(int check = currentPlace; check<nums.length;check++){
			if(nums[check]<smallest){
				smallestAt = check;
				smallest = nums[check];
			}
		}
		int temp = nums[currentPlace];
		nums[currentPlace] = nums[smallestAt];
		nums[smallestAt] = temp;
	}
}
Task: Apply a callback to an array



C#: int[] intArray = { 1, 2, 3, 4, 5 };

int[] squares1 = intArray.Select(x => x * x).ToArray();


int[] squares2 = (from x in intArray
                  select x * x).ToArray();


foreach (var i in intArray)
    Console.WriteLine(i * i);



Java: public class ArrayCallback7 {

    interface IntConsumer {
        void run(int x);
    }

    interface IntToInt {
        int run(int x);
    }

    static void forEach(int[] arr, IntConsumer consumer) {
        for (int i : arr) {
            consumer.run(i);
        }
    }

    static void update(int[] arr, IntToInt mapper) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = mapper.run(arr[i]);
        }
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        forEach(numbers, new IntConsumer() {
            public void run(int x) {
                System.out.println(x);
            }
        });

        update(numbers, new IntToInt() {
            @Override
            public int run(int x) {
                return x * x;
            }
        });

        forEach(numbers, new IntConsumer() {
            public void run(int x) {
                System.out.println(x);
            }
        });
    }
}
Task: Singleton



C#: public sealed class Singleton1 
{
    private static Singleton1 instance;
    private static readonly object lockObj = new object();
    
    public static Singleton1 Instance {
        get {
            lock(lockObj) {
                if (instance == null) {
                    instance = new Singleton1();
                }
            }
            return instance;
        }
    }
}



Java: class Singleton
{
    private static Singleton myInstance;
    public static Singleton getInstance()
    {
        if (myInstance == null)
        {
            synchronized(Singleton.class)
            {
                if (myInstance == null)
                {
                    myInstance = new Singleton();
                }
            }
        }

        return myInstance;
    }

    protected Singleton()
    {
        
    }

    
}
Task: Safe addition



C#: using System;

namespace SafeAddition {
    class Program {
        static float NextUp(float d) {
            if (d == 0.0) return float.Epsilon;
            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;

            byte[] bytes = BitConverter.GetBytes(d);
            int dl = BitConverter.ToInt32(bytes, 0);
            dl++;
            bytes = BitConverter.GetBytes(dl);

            return BitConverter.ToSingle(bytes, 0);
        }

        static float NextDown(float d) {
            if (d == 0.0) return -float.Epsilon;
            if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;

            byte[] bytes = BitConverter.GetBytes(d);
            int dl = BitConverter.ToInt32(bytes, 0);
            dl--;
            bytes = BitConverter.GetBytes(dl);

            return BitConverter.ToSingle(bytes, 0);
        }

        static Tuple<float, float> SafeAdd(float a, float b) {
            return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
        }

        static void Main(string[] args) {
            float a = 1.20f;
            float b = 0.03f;

            Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
        }
    }
}



Java: public class SafeAddition {
    private static double stepDown(double d) {
        return Math.nextAfter(d, Double.NEGATIVE_INFINITY);
    }

    private static double stepUp(double d) {
        return Math.nextUp(d);
    }

    private static double[] safeAdd(double a, double b) {
        return new double[]{stepDown(a + b), stepUp(a + b)};
    }

    public static void main(String[] args) {
        double a = 1.2;
        double b = 0.03;
        double[] result = safeAdd(a, b);
        System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]);
    }
}
Task: Loops_Downward for



C#: for (int i = 10; i >= 0; i--)
{
   Console.WriteLine(i);
}



Java: for (int i = 10; i >= 0; i--) {
    System.out.println(i);
}
Task: Write entire file



C#: System.IO.File.WriteAllText("filename.txt", "This file contains a string.");



Java: import java.io.*;

public class Test {

    public static void main(String[] args) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
            bw.write("abc");
        }
    }
}
Task: Loops_For



C#: using System;

class Program {
    static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                Console.Write("*");
            }
            Console.WriteLine();
        }
    }
}



Java: for (Integer i = 0; i < 5; i++) {
    String line = '';

    for (Integer j = 0; j < i; j++) {
        line += '*';
    }

    System.debug(line);
}

List<String> lines = new List<String> {
    '*',
    '**',
    '***',
    '****',
    '*****'
};

for (String line : lines) {
    System.debug(line);
}
Task: Non-continuous subsequences



C#: using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void Main() {
        var sequence = new[] { "A", "B", "C", "D" };
        foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {
            Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i])));
        }
    }
    
    static IEnumerable<List<int>> Subsets(int length) {
        int[] values = Enumerable.Range(0, length).ToArray();
        var stack = new Stack<int>(length);
        for (int i = 0; stack.Count > 0 || i < length; ) {
            if (i < length) {
                stack.Push(i++);
                yield return (from index in stack.Reverse() select values[index]).ToList();
            } else {
                i = stack.Pop() + 1;
                if (stack.Count > 0) i = stack.Pop() + 1;
            }
        }
    }

    static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;

}



Java: public class NonContinuousSubsequences {

    public static void main(String args[]) {
        seqR("1234", "", 0, 0);
    }

    private static void seqR(String s, String c, int i, int added) {
        if (i == s.length()) {
            if (c.trim().length() > added)
                System.out.println(c);
        } else {
            seqR(s, c + s.charAt(i), i + 1, added + 1);
            seqR(s, c + ' ', i + 1, added);
        }
    }
}
Task: Twin primes



C#: using System;

class Program {

    static uint[] res = new uint[10];
    static uint ri = 1, p = 10, count = 0;

    static void TabulateTwinPrimes(uint bound) {
        if (bound < 5) return; count++;
        uint cl = (bound - 1) >> 1, i = 1, j,
             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;
        var comp = new bool[cl]; bool lp;
        for (j = 3; j < cl; j += 3) comp[j] = true;
        while (i < limit) {
            if (lp = !comp[i]) {
                uint pr = (i << 1) + 3;
                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
                    comp[j] = true;
            }
            if (!comp[++i]) {
                uint pr = (i << 1) + 3;
                if (lp) {
                    if (pr > p) {
                        res[ri++] = count;
                        p *= 10;
                    }
                    count++;
                    i++;
                }
                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
                    comp[j] = true; 
            }
        }
        cl--;
        while (i < cl) {
            lp = !comp[i++];
            if (!comp[i] && lp) {
                if ((i++ << 1) + 3 > p) {
                    res[ri++] = count;
                    p *= 10;
                }
                count++;
            }
        }
        res[ri] = count;
    }

    static void Main(string[] args) {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        string fmt = "{0,9:n0} twin primes below {1,-13:n0}";
        TabulateTwinPrimes(1_000_000_000);
        sw.Stop();
        p = 1;
        for (var j = 1; j <= ri; j++)
            Console.WriteLine(fmt, res[j], p *= 10);
        Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
    }
}



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

public class twinPrimes {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Search Size: ");
        BigInteger max = input.nextBigInteger();
        int counter = 0;
        for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
            }
        }
        System.out.println(counter + " twin prime pairs.");
    }
    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
                return false;
            }
        }
        return true;
    }
}
Task: Roots of unity



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

class Program
{
    static IEnumerable<Complex> RootsOfUnity(int degree)
    {
        return Enumerable
            .Range(0, degree)
            .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
    }

    static void Main()
    {
        var degree = 3;
        foreach (var root in RootsOfUnity(degree))
        {
            Console.WriteLine(root);
        }
    }
}



Java: import java.util.Locale;

public class Test {

    public static void main(String[] a) {
        for (int n = 2; n < 6; n++)
            unity(n);
    }

    public static void unity(int n) {
        System.out.printf("%n%d: ", n);

        
        for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) {

            double real = Math.cos(angle); 

            if (Math.abs(real) < 1.0E-3)
                real = 0.0; 

            double imag = Math.sin(angle); 

            if (Math.abs(imag) < 1.0E-3)
                imag = 0.0;

            System.out.printf(Locale.US, "(%9f,%9f) ", real, imag);
        }
    }
}
Task: Long multiplication



C#: using System;
using static System.Console;
using BI = System.Numerics.BigInteger;

class Program {

  static decimal mx = 1E28M, hm = 1E14M, a;

  
  struct bi { public decimal hi, lo; }

  
  static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }

  
  static string toStr(bi a, bool comma = false) {
    string r = a.hi == 0 ? string.Format("{0:0}", a.lo) :
                           string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo);
    if (!comma) return r;  string rc = "";
    for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc;
    return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }

  
  static decimal Pow_dec(decimal bas, uint exp) {
    if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
    if ((exp & 1) == 0) return tmp; return tmp * bas; }

  static void Main(string[] args) {
    for (uint p = 64; p < 95; p += 30) {        
      bi x = set4sq(a = Pow_dec(2M, p)), y;     
      WriteLine("The square of (2^{0}):                    {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2);
      y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;   
      a = x.hi * x.lo * 2M;                     
      y.hi += Math.Floor(a / hm);               
      y.lo += (a % hm) * hm;                    
      while (y.lo > mx) { y.lo -= mx; y.hi++; } 
      WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true),
          BS.ToString() == toStr(y) ? "does" : "fails to"); } }

}



Java: public class LongMult {

	private static byte[] stringToDigits(String num) {
		byte[] result = new byte[num.length()];
		for (int i = 0; i < num.length(); i++) {
			char c = num.charAt(i);
			if (c < '0' || c > '9') {
				throw new IllegalArgumentException("Invalid digit " + c
						+ " found at position " + i);
			}
			result[num.length() - 1 - i] = (byte) (c - '0');
		}
		return result;
	}

	public static String longMult(String num1, String num2) {
		byte[] left = stringToDigits(num1);
		byte[] right = stringToDigits(num2);
		byte[] result = new byte[left.length + right.length];
		for (int rightPos = 0; rightPos < right.length; rightPos++) {
			byte rightDigit = right[rightPos];
			byte temp = 0;
			for (int leftPos = 0; leftPos < left.length; leftPos++) {
				temp += result[leftPos + rightPos];
				temp += rightDigit * left[leftPos];
				result[leftPos + rightPos] = (byte) (temp % 10);
				temp /= 10;
			}
			int destPos = rightPos + left.length;
			while (temp != 0) {
				temp += result[destPos] & 0xFFFFFFFFL;
				result[destPos] = (byte) (temp % 10);
				temp /= 10;
				destPos++;
			}
		}
		StringBuilder stringResultBuilder = new StringBuilder(result.length);
		for (int i = result.length - 1; i >= 0; i--) {
			byte digit = result[i];
			if (digit != 0 || stringResultBuilder.length() > 0) {
				stringResultBuilder.append((char) (digit + '0'));
			}
		}
		return stringResultBuilder.toString();
	}

	public static void main(String[] args) {
		System.out.println(longMult("18446744073709551616",
				"18446744073709551616"));
	}
}