WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Bubble sort



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

namespace RosettaCode.BubbleSort
{
    public static class BubbleSortMethods
    {
        
        
        
        public static void BubbleSort<T>(this List<T> list) where T : IComparable
        {
            bool madeChanges;
            int itemCount = list.Count;
            do
            {
                madeChanges = false;
                itemCount--;
                for (int i = 0; i < itemCount; i++)
                {
                    if (list[i].CompareTo(list[i + 1]) > 0)
                    {
                        T temp = list[i + 1];
                        list[i + 1] = list[i];
                        list[i] = temp;
                        madeChanges = true;
                    }
                }
            } while (madeChanges);
        }
    }

    
    
    class Program
    {
        static void Main()
        {
            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
            testList.BubbleSort();
            foreach (var t in testList) Console.Write(t + " ");
        }
    }
}



Java: public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
    boolean changed = false;
    do {
        changed = false;
        for (int a = 0; a < comparable.length - 1; a++) {
            if (comparable[a].compareTo(comparable[a + 1]) > 0) {
                E tmp = comparable[a];
                comparable[a] = comparable[a + 1];
                comparable[a + 1] = tmp;
                changed = true;
            }
        }
    } while (changed);
}
Task: File input_output



C#: using System;
using System.IO;

namespace FileIO
{
  class Program
  {
    static void Main()
    {
      String s = scope .();
      File.ReadAllText("input.txt", s);
      File.WriteAllText("output.txt", s);
    }
  }
}



Java: import java.io.*;

public class FileIODemo {
  public static void main(String[] args) {
    try {
      FileInputStream in = new FileInputStream("input.txt");
      FileOutputStream out = new FileOutputStream("ouput.txt");
      int c;
      while ((c = in.read()) != -1) {
        out.write(c);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e){
      e.printStackTrace();
    }
  }
}
Task: Arithmetic_Integer



C#: using System;

class Program
{
    static void Main(string[] args)
    {
        int a = Convert.ToInt32(args[0]);
        int b = Convert.ToInt32(args[1]);

        Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
        Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
        Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
        Console.WriteLine("{0} / {1} = {2}", a, b, a / b); 
        Console.WriteLine("{0} % {1} = {2}", a, b, a % b); 
        Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
    }
}



Java: import java.util.Scanner;

public class IntegerArithmetic {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        int sum = a + b;        
        int difference = a - b; 
        int product = a * b;    
        int division = a / b;   
        int remainder = a % b;  

        System.out.println("a + b = " + sum);
        System.out.println("a - b = " + difference);
        System.out.println("a * b = " + product);
        System.out.println("quotient of a / b = " + division);   
        System.out.println("remainder of a / b = " + remainder);   
    }
}
Task: Matrix transposition



C#: using System;
using System.Text;

namespace prog
{
	class MainClass
	{						
		public static void Main (string[] args)
		{
			double[,] m = { {1,2,3},{4,5,6},{7,8,9} };
			
			double[,] t = Transpose( m );	
			
			for( int i=0; i<t.GetLength(0); i++ )
			{
				for( int j=0; j<t.GetLength(1); j++ )		
					Console.Write( t[i,j] + "  " );
				Console.WriteLine("");
			}
		}
		
		public static double[,] Transpose( double[,] m )
		{
			double[,] t = new double[m.GetLength(1),m.GetLength(0)];
			for( int i=0; i<m.GetLength(0); i++ )
				for( int j=0; j<m.GetLength(1); j++ )
					t[j,i] = m[i,j];			
			
			return t;
		}
	}
}



Java: import java.util.Arrays;
public class Transpose{
       public static void main(String[] args){
               double[][] m = {{1, 1, 1, 1},
                               {2, 4, 8, 16},
                               {3, 9, 27, 81},
                               {4, 16, 64, 256},
                               {5, 25, 125, 625}};
               double[][] ans = new double[m[0].length][m.length];
               for(int rows = 0; rows < m.length; rows++){
                       for(int cols = 0; cols < m[0].length; cols++){
                               ans[cols][rows] = m[rows][cols];
                       }
               }
               for(double[] i:ans){
                       System.out.println(Arrays.toString(i));
               }
       }
}
Task: Man or boy test



C#: using System;
 
delegate T Func<T>();
 
class ManOrBoy
{
    static void Main()
    {
        Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
    }
 
    static Func<int> C(int i)
    {
        return delegate { return i; };
    }
 
    static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
    {
        Func<int> b = null;
        b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
        return k <= 0 ? x4() + x5() : b();
    }
}



Java: import java.util.function.DoubleSupplier;

public class ManOrBoy {
    
    static double A(int k, DoubleSupplier x1, DoubleSupplier x2,
                 DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) {
        
        DoubleSupplier B = new DoubleSupplier() {
            int m = k;
            public double getAsDouble() {
                return A(--m, this, x1, x2, x3, x4);
            }
        };
                
        return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble();
    }
    
    public static void main(String[] args) {
        System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0));
    }
}
Task: Short-circuit evaluation



C#: using System;

class Program
{
    static bool a(bool value)
    {
        Console.WriteLine("a");
        return value;
    }

    static bool b(bool value)
    {
        Console.WriteLine("b");
        return value;
    }

    static void Main()
    {
        foreach (var i in new[] { false, true })
        {
            foreach (var j in new[] { false, true })
            {
                Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
                Console.WriteLine();
                Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
                Console.WriteLine();
            }
        }
    }
}



Java: module test
    {
    @Inject Console console;

    static Boolean show(String name, Boolean value)
        {
        console.print($"{name}()={value}");
        return value;
        }

    void run()
        {
        val a = show("a", _);
        val b = show("b", _);

        for (Boolean v1 : False..True)
            {
            for (Boolean v2 : False..True)
                {
                console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}");
                console.print();
                console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}");
                console.print();
                }
            }
        }
    }
Task: Find limit of recursion



C#: using System;
class RecursionLimit
{
  static void Main(string[] args)
  {
    Recur(0);
  }
 
  private static void Recur(int i) 
  {
    Console.WriteLine(i);
    Recur(i + 1);
  }
}



Java: public class RecursionTest {
	
    private static void recurse(int i) {
        try {
	    recurse(i+1);
	} catch (StackOverflowError e) {
	    System.out.print("Recursion depth on this system is " + i + ".");
	}
    }
	
    public static void main(String[] args) {
        recurse(0);
    }
}
Task: Perfect numbers



C#: static void Main(string[] args)
{
	Console.WriteLine("Perfect numbers from 1 to 33550337:");

	for (int x = 0; x < 33550337; x++)
	{
		if (IsPerfect(x))
			Console.WriteLine(x + " is perfect.");
	}

	Console.ReadLine();
}

static bool IsPerfect(int num) 
{
	int sum = 0;
	for (int i = 1; i < num; i++)
	{
		if (num % i == 0)
			sum += i;
	}

	return sum == num ;
}



Java: public static boolean perf(int n){
	int sum= 0;
	for(int i= 1;i < n;i++){
		if(n % i == 0){
			sum+= i;
		}
	}
	return sum == n;
}
Task: Arbitrary-precision integers (included)



C#: using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;

static class Program {
    static void Main() {
        BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
        string result = n.ToString();

        Debug.Assert(result.Length == 183231);
        Debug.Assert(result.StartsWith("62060698786608744707"));
        Debug.Assert(result.EndsWith("92256259918212890625"));

        Console.WriteLine("n = 5^4^3^2");
        Console.WriteLine("n = {0}...{1}", 
            result.Substring(0, 20),
            result.Substring(result.Length - 20, 20)
            );

        Console.WriteLine("n digits = {0}", result.Length);
    }
}



Java: import java.math.BigInteger;

class IntegerPower {
    public static void main(String[] args) {
        BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact());
        String str = power.toString();
        int len = str.length();
        System.out.printf("5**4**3**2 = %s...%s and has %d digits%n",
                str.substring(0, 20), str.substring(len - 20), len);
    }
}
Task: Least common multiple



C#: Using System;
class Program
{
    static int gcd(int m, int n)
    {
        return n == 0 ? Math.Abs(m) : gcd(n, n % m);
    }
    static int lcm(int m, int n)
    {
        return Math.Abs(m * n) / gcd(m, n);
    }
    static void Main()
    {
        Console.WriteLine("lcm(12,18)=" + lcm(12,18));
    }
}



Java: import java.util.Scanner;

public class LCM{
   public static void main(String[] args){
      Scanner aScanner = new Scanner(System.in);
   
      
      System.out.print("Enter the value of m:");
      int m = aScanner.nextInt();
      System.out.print("Enter the value of n:");
      int n = aScanner.nextInt();
      int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);
      
      if (lcm == 0) {
         int mm = m, nn = n;
         while (mm != nn) {
             while (mm < nn) { mm += m; }
             while (nn < mm) { nn += n; }
         }  
         lcm = mm;
      }
      System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
   }
}
Task: Loops_Break



C#: class Program
{
    static void Main(string[] args)
    {
        Random random = new Random();
        while (true)
        {
            int a = random.Next(20);
            Console.WriteLine(a);
            if (a == 10)
                break;
            int b = random.Next(20)
            Console.WriteLine(b);
        }
           
        Console.ReadLine();
    }       
}



Java: import java.util.Random;

Random rand = new Random();
while(true){
    int a = rand.nextInt(20);
    System.out.println(a);
    if(a == 10) break;
    int b = rand.nextInt(20);
    System.out.println(b);
}
Task: Water collected between towers



C#: class Program
{
    static void Main(string[] args)
    {
        int[][] wta = {
            new int[] {1, 5, 3, 7, 2},   new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
            new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
            new int[] { 5, 5, 5, 5 },    new int[] { 5, 6, 7, 8 },
            new int[] { 8, 7, 7, 6 },    new int[] { 6, 7, 10, 7, 6 }};
        string blk, lf = "\n", tb = "██", wr = "≈≈", mt = "  ";
        for (int i = 0; i < wta.Length; i++)
        {
            int bpf; blk = ""; do
            {
                string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
                {
                    if (wta[i][j] > 0)
                    {    floor += tb; wta[i][j] -= 1; bpf += 1; }
                    else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
                }
                if (bpf > 0) blk = floor + lf + blk;
            } while (bpf > 0);
            while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
            while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
            if (args.Length > 0) System.Console.Write("\n{0}", blk);
            System.Console.WriteLine("Block {0} retains {1,2} water units.",
                i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
        }
    }
}



Java: public class WaterBetweenTowers {
    public static void main(String[] args) {
        int i = 1;
        int[][] tba = new int[][]{
            new int[]{1, 5, 3, 7, 2},
            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
            new int[]{5, 5, 5, 5},
            new int[]{5, 6, 7, 8},
            new int[]{8, 7, 7, 6},
            new int[]{6, 7, 10, 7, 6}
        };

        for (int[] tea : tba) {
            int rht, wu = 0, bof;
            do {
                for (rht = tea.length - 1; rht >= 0; rht--) {
                    if (tea[rht] > 0) {
                        break;
                    }
                }

                if (rht < 0) {
                    break;
                }

                bof = 0;
                for (int col = 0; col <= rht; col++) {
                    if (tea[col] > 0) {
                        tea[col]--;
                        bof += 1;
                    } else if (bof > 0) {
                        wu++;
                    }
                }
                if (bof < 2) {
                    break;
                }
            } while (true);

            System.out.printf("Block %d", i++);
            if (wu == 0) {
                System.out.print(" does not hold any");
            } else {
                System.out.printf(" holds %d", wu);
            }
            System.out.println(" water units.");
        }
    }
}
Task: Middle three digits



C#: using System;

namespace RosettaCode
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
            Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
        }
    }
}



Java: public class MiddleThreeDigits {

    public static void main(String[] args) {
        final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001,
            -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};

        final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE,
            Integer.MAX_VALUE};

        for (long n : passing)
            System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));

        for (int n : failing)
            System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
    }

    public static <T> String middleThreeDigits(T n) {
        String s = String.valueOf(n);
        if (s.charAt(0) == '-')
            s = s.substring(1);
        int len = s.length();
        if (len < 3 || len % 2 == 0)
            return "Need odd and >= 3 digits";
        int mid = len / 2;
        return s.substring(mid - 1, mid + 2);
    }
}
Task: Stern-Brocot sequence



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

static class Program {
    static List<int> l = new List<int>() { 1, 1 };

    static int gcd(int a, int b) {
        return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }

    static void Main(string[] args) {
        int max = 1000; int take = 15; int i = 1;
        int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };
        do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }
        while (l.Count < max || l[l.Count - 2] != selection.Last());
        Console.Write("The first {0} items In the Stern-Brocot sequence: ", take);
        Console.WriteLine("{0}\n", string.Join(", ", l.Take(take)));
        Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:");
        foreach (int ii in selection) {
            int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); }
        Console.WriteLine(); bool good = true;
        for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }
        Console.WriteLine("The greatest common divisor of all the two consecutive items of the" + 
                          " series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
    }
}



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

public class SternBrocot {
	static LinkedList<Integer> sequence = new LinkedList<Integer>(){{
		add(1); add(1);
	}};
	
	private static void genSeq(int n){
		for(int conIdx = 1; sequence.size() < n; conIdx++){
			int consider = sequence.get(conIdx);
			int pre = sequence.get(conIdx - 1);
			sequence.add(consider + pre);
			sequence.add(consider);
		}
		
	}
	
	public static void main(String[] args){
		genSeq(1200);
		System.out.println("The first 15 elements are: " + sequence.subList(0, 15));
		for(int i = 1; i <= 10; i++){
			System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1));
		}
		
		System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1));
		
		boolean failure = false;
		for(int i = 0; i < 999; i++){
			failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);
		}
		System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
	}
}
Task: Documentation



C#: 


public static class XMLSystem
{
    static XMLSystem()
    {
        
    }

    
    
    
    
    
    public static XmlDocument GetXML(string name) 
    {
        return null;
    }
}



Java: 
public class Doc{
   
   private String field;

   
   public int method(long num) throws BadException{
      
   }
}
Task: FASTA format



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

class Program
{
    public class FastaEntry
    {
        public string Name { get; set; }
        public StringBuilder Sequence { get; set; }
    }

    static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)
    {
        FastaEntry f = null;
        string line;
        while ((line = fastaFile.ReadLine()) != null)
        {
            
            if (line.StartsWith(";"))
                continue;

            if (line.StartsWith(">"))
            {
                if (f != null)
                    yield return f;
                f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };
            }
            else if (f != null)
                f.Sequence.Append(line);
        }
        yield return f;
    }

    static void Main(string[] args)
    {
        try
        {
            using (var fastaFile = new StreamReader("fasta.txt"))
            {
                foreach (FastaEntry f in ParseFasta(fastaFile))
                    Console.WriteLine("{0}: {1}", f.Name, f.Sequence);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e);
        }
        Console.ReadLine();
    }
}



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

public class ReadFastaFile {

    public static void main(String[] args) throws FileNotFoundException {

        boolean first = true;

        try (Scanner sc = new Scanner(new File("test.fasta"))) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine().trim();
                if (line.charAt(0) == '>') {
                    if (first)
                        first = false;
                    else
                        System.out.println();
                    System.out.printf("%s: ", line.substring(1));
                } else {
                    System.out.print(line);
                }
            }
        }
        System.out.println();
    }
}
Task: Find palindromic numbers in both binary and ternary bases



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

public class FindPalindromicNumbers
{
    static void Main(string[] args)
    {
        var query =
            PalindromicTernaries()
            .Where(IsPalindromicBinary)
            .Take(6);
        foreach (var x in query) {
            Console.WriteLine("Decimal: " + x);
            Console.WriteLine("Ternary: " + ToTernary(x));
            Console.WriteLine("Binary: " + Convert.ToString(x, 2));
            Console.WriteLine();
        }
    }

    public static IEnumerable<long> PalindromicTernaries() {
        yield return 0;
        yield return 1;
        yield return 13;
        yield return 23;

        var f = new List<long> {0};
        long fMiddle = 9;
        while (true) {
            for (long edge = 1; edge < 3; edge++) {
                int i;
                do {
                    
                    long result = fMiddle;
                    long fLeft = fMiddle * 3;
                    long fRight = fMiddle / 3;
                    for (int j = f.Count - 1; j >= 0; j--) {
                        result += (fLeft + fRight) * f[j];
                        fLeft *= 3;
                        fRight /= 3;
                    }
                    result += (fLeft + fRight) * edge;
                    yield return result;

                    
                    for (i = f.Count - 1; i >= 0; i--) {
                        if (f[i] == 2) {
                            f[i] = 0;
                        } else {
                            f[i]++;
                            break;
                        }
                    }
                } while (i >= 0);
            }
            f.Add(0);
            fMiddle *= 3;
        }
    }

    public static bool IsPalindromicBinary(long number) {
        long n = number;
        long reverse = 0;
        while (n != 0) {
            reverse <<= 1;
            if ((n & 1) == 1) reverse++;
            n >>= 1;
        }
        return reverse == number;
    }

    public static string ToTernary(long n)
    {
        if (n == 0) return "0";
        string result = "";
        while (n > 0) {        {
            result = (n % 3) + result;
            n /= 3;
        }
        return result;
    }

}



Java: public class Pali23 {
	public static boolean isPali(String x){
		return x.equals(new StringBuilder(x).reverse().toString());
	}
	
	public static void main(String[] args){
		
		for(long i = 0, count = 0; count < 6;i++){
			if((i & 1) == 0 && (i != 0)) continue; 
			
			
			if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
				System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
				count++;
			}
		}
	}
}
Task: Literals_String



C#: string path = @"C:\Windows\System32";
string multiline = @"Line 1.
Line 2.
Line 3.";



Java:   char a = 'a';  
  String b = "abc";  
  char doubleQuote = '"';  
  char singleQuote = '\'';  
  String singleQuotes = "''";  
  String doubleQuotes = "\"\"";