WeixiangYan/CodeTransOcean huggingface dataset:
Task: Letter frequency



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

class Program
{
    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
    {
        var dictionary = new SortedDictionary<TItem, int>();
        foreach (var item in items)
        {
            if (dictionary.ContainsKey(item))
            {
                dictionary[item]++;
            }
            else
            {
                dictionary[item] = 1;
            }
        }
        return dictionary;
    }

    static void Main(string[] arguments)
    {
        var file = arguments.FirstOrDefault();
        if (File.Exists(file))
        {
            var text = File.ReadAllText(file);
            foreach (var entry in GetFrequencies(text))
            {
                Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            }
        }
    }
}



Java: import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class LetterFreq {
	public static int[] countLetters(String filename) throws IOException{
		int[] freqs = new int[26];
		BufferedReader in = new BufferedReader(new FileReader(filename));
		String line;
		while((line = in.readLine()) != null){
			line = line.toUpperCase();
			for(char ch:line.toCharArray()){
				if(Character.isLetter(ch)){
					freqs[ch - 'A']++;
				}
			}
		}
		in.close();
		return freqs;
	}
	
	public static void main(String[] args) throws IOException{
		System.out.println(Arrays.toString(countLetters("filename.txt")));
	}
}
Task: Increment a numerical string



C#: string s = "12345";
s = (int.Parse(s) + 1).ToString();






using System.Numerics;
string bis = "123456789012345678999999999";
bis = (BigInteger.Parse(bis) + 1).ToString();





Java: String s = "12345";
IntLiteral lit1 = new IntLiteral(s);
IntLiteral lit2 = 6789;
++lit1; 
++lit2;
Task: Strip a set of characters from a string



C#: using System;

public static string RemoveCharactersFromString(string testString, string removeChars)
{
    char[] charAry = removeChars.ToCharArray();
    string returnString = testString;
    foreach (char c in charAry)
    {
        while (returnString.IndexOf(c) > -1)
        {
            returnString = returnString.Remove(returnString.IndexOf(c), 1);
        }
    }
    return returnString;
}



Java: class StripChars {
    public static String stripChars(String inString, String toStrip) {
        return inString.replaceAll("[" + toStrip + "]", "");
    }

    public static void main(String[] args) {
        String sentence = "She was a soul stripper. She took my heart!";
        String chars = "aei";
        System.out.println("sentence: " + sentence);
        System.out.println("to strip: " + chars);
        System.out.println("stripped: " + stripChars(sentence, chars));
    }
}
Task: Averages_Arithmetic mean



C#: using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Console.WriteLine(new[] { 1, 2, 3 }.Average());
    }
}



Java: public static double avg(double... arr) {
    double sum = 0.0;
    for (double x : arr) {
        sum += x;
    }
    return sum / arr.length;
}
Task: Entropy



C#: using System;
using System.Collections.Generic;
namespace Entropy
{
	class Program
	{
		public static double logtwo(double num)
		{
			return Math.Log(num)/Math.Log(2);
		}
		public static void Main(string[] args)
		{
		label1:
			string input = Console.ReadLine();
			double infoC=0;
			Dictionary<char,double> table = new Dictionary<char, double>();

			
			foreach (char c in input)
			{
				if (table.ContainsKey(c))
					table[c]++;
				    else
				    	table.Add(c,1);
	
			}
			double freq;
			foreach (KeyValuePair<char,double> letter in table)
			{
				freq=letter.Value/input.Length;
				infoC+=freq*logtwo(freq);
			}
			infoC*=-1;
			Console.WriteLine("The Entropy of {0} is {1}",input,infoC);
			goto label1;
		
		}
	}
}



Java: import java.lang.Math;
import java.util.Map;
import java.util.HashMap;

public class REntropy {

  @SuppressWarnings("boxing")
  public static double getShannonEntropy(String s) {
    int n = 0;
    Map<Character, Integer> occ = new HashMap<>();

    for (int c_ = 0; c_ < s.length(); ++c_) {
      char cx = s.charAt(c_);
      if (occ.containsKey(cx)) {
        occ.put(cx, occ.get(cx) + 1);
      } else {
        occ.put(cx, 1);
      }
      ++n;
    }

    double e = 0.0;
    for (Map.Entry<Character, Integer> entry : occ.entrySet()) {
      char cx = entry.getKey();
      double p = (double) entry.getValue() / n;
      e += p * log2(p);
    }
    return -e;
  }

  private static double log2(double a) {
    return Math.log(a) / Math.log(2);
  }
  public static void main(String[] args) {
    String[] sstr = {
      "1223334444",
      "1223334444555555555", 
      "122333", 
      "1227774444",
      "aaBBcccDDDD",
      "1234567890abcdefghijklmnopqrstuvwxyz",
      "Rosetta Code",
    };

    for (String ss : sstr) {
      double entropy = REntropy.getShannonEntropy(ss);
      System.out.printf("Shannon entropy of %40s: %.12f%n", "\"" + ss + "\"", entropy);
    }
    return;
  }
}
Task: Tokenize a string with escaping



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

public class TokenizeAStringWithEscaping
{
    public static void Main() {
        string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
            Console.WriteLine(": " + token); 
        }
    }
}

public static class Extensions
{
    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
        if (input == null) yield break;
        var buffer = new StringBuilder();
        bool escaping = false;
        foreach (char c in input) {
            if (escaping) {
                buffer.Append(c);
                escaping = false;
            } else if (c == escape) {
                escaping = true;
            } else if (c == separator) {
                yield return buffer.Flush();
            } else {
                buffer.Append(c);
            }
        }
        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
    }
    
    public static string Flush(this StringBuilder stringBuilder) {
        string result = stringBuilder.ToString();
        stringBuilder.Clear();
        return result;
    }
}



Java: import java.util.*;

public class TokenizeStringWithEscaping {

    public static void main(String[] args) {
        String sample = "one^|uno||three^^^^|four^^^|^cuatro|";
        char separator = '|';
        char escape = '^';

        System.out.println(sample);
        try {
            System.out.println(tokenizeString(sample, separator, escape));
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static List<String> tokenizeString(String s, char sep, char escape)
            throws Exception {
        List<String> tokens = new ArrayList<>();
        StringBuilder sb = new StringBuilder();

        boolean inEscape = false;
        for (char c : s.toCharArray()) {
            if (inEscape) {
                inEscape = false;
            } else if (c == escape) {
                inEscape = true;
                continue;
            } else if (c == sep) {
                tokens.add(sb.toString());
                sb.setLength(0);
                continue;
            }
            sb.append(c);
        }
        if (inEscape)
            throw new Exception("Invalid terminal escape");

        tokens.add(sb.toString());

        return tokens;
    }
}
Task: Hello world_Text



C#: Using System;
namespace HelloWorld {
  class Program
  {
    static void Main()
    {
      Console.Writeln("Hello World!");
    }
  }
}



Java: module HelloWorld
    {
    void run()
        {
        @Inject Console console;
        console.print("Hello World!");
        }
    }
Task: Forward difference



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

class Program
{
    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)
    {
        switch (order)
        {
            case 0u:
                return sequence;
            case 1u:
                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);
            default:
                return ForwardDifference(ForwardDifference(sequence), order - 1u);
        }
    }

    static void Main()
    {
        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };
        do
        {
            Console.WriteLine(string.Join(", ", sequence));
        } while ((sequence = ForwardDifference(sequence)).Any());
    }
}



Java: import java.util.Arrays;
public class FD {
    public static void main(String args[]) {
        double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
        System.out.println(Arrays.toString(dif(a, 1)));
        System.out.println(Arrays.toString(dif(a, 2)));
        System.out.println(Arrays.toString(dif(a, 9)));
        System.out.println(Arrays.toString(dif(a, 10)));      
        System.out.println(Arrays.toString(dif(a, 11)));
        System.out.println(Arrays.toString(dif(a, -1)));
        System.out.println(Arrays.toString(dif(a, 0)));
    }

    public static double[] dif(double[] a, int n) {
        if (n < 0)
            return null; 

        for (int i = 0; i < n && a.length > 0; i++) {
            double[] b = new double[a.length - 1];
            for (int j = 0; j < b.length; j++){
                b[j] = a[j+1] - a[j];
            }
            a = b; 
        }
        return a;
    }
}
Task: Primality by trial division



C#: static bool isPrime(int n)
        {
            if (n <= 1) return false;
            for (int i = 2; i * i <= n; i++)            
                if (n % i == 0) return false;            
            return true;
        }



Java: public static boolean prime(long a){
   if(a == 2){
      return true;
   }else if(a <= 1 || a % 2 == 0){
      return false;
   }
   long max = (long)Math.sqrt(a);
   for(long n= 3; n <= max; n+= 2){
      if(a % n == 0){ return false; }
   }
   return true;
}
Task: Evaluate binomial coefficients



C#: using System;

namespace BinomialCoefficients
{
    class Program
    {
        static void Main(string[] args)
        {
            ulong n = 1000000, k = 3;
            ulong result = biCoefficient(n, k);
            Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result);
            Console.ReadLine();
        }

        static int fact(int n)
        {
            if (n == 0) return 1;
            else return n * fact(n - 1);
        }

        static ulong biCoefficient(ulong n, ulong k)
        {
            if (k > n - k)
            {
                k = n - k;
            }

            ulong c = 1;
            for (uint i = 0; i < k; i++)
            {
                c = c * (n - i);
                c = c / (i + 1);
            }
            return c;
        }
    }
}



Java: public class Binomial {

    
    private static long binomialInt(int n, int k) {
        if (k > n - k)
            k = n - k;

        long binom = 1;
        for (int i = 1; i <= k; i++)
            binom = binom * (n + 1 - i) / i;
        return binom;
    }

    
    private static Object binomialIntReliable(int n, int k) {
        if (k > n - k)
            k = n - k;

        long binom = 1;
        for (int i = 1; i <= k; i++) {
            try {
                binom = Math.multiplyExact(binom, n + 1 - i) / i;
            } catch (ArithmeticException e) {
                return "overflow";
            }
        }
        return binom;
    }

    
    
    private static double binomialFloat(int n, int k) {
        if (k > n - k)
            k = n - k;

        double binom = 1.0;
        for (int i = 1; i <= k; i++)
            binom = binom * (n + 1 - i) / i;
        return binom;
    }

    
    private static BigInteger binomialBigInt(int n, int k) {
        if (k > n - k)
            k = n - k;

        BigInteger binom = BigInteger.ONE;
        for (int i = 1; i <= k; i++) {
            binom = binom.multiply(BigInteger.valueOf(n + 1 - i));
            binom = binom.divide(BigInteger.valueOf(i));
        }
        return binom;
    }

    private static void demo(int n, int k) {
        List<Object> data = Arrays.asList(
                n,
                k,
                binomialInt(n, k),
                binomialIntReliable(n, k),
                binomialFloat(n, k),
                binomialBigInt(n, k));

        System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t")));
    }

    public static void main(String[] args) {
        demo(5, 3);
        demo(1000, 300);
    }
}
Task: Collections



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

int[] intArray = new int[]{ 1, 2, 3, 4, 5 };

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


string[] stringArr = new string[5];
stringArr[0] = "string";



Java: List arrayList = new ArrayList();
arrayList.add(new Integer(0));

arrayList.add(0); 



List<Integer> myarrlist = new ArrayList<Integer>();


int sum;
for(int i = 0; i < 10; i++) {
    myarrlist.add(i);
}
Task: Singly-linked list_Traversal



C#: var current = [head of list to traverse]
while(current != null)
{
    

    current = current.Next;
}



Java: LinkedList<Type> list = new LinkedList<Type>();

for(Type i: list){
  
  System.out.println(i);
}
Task: Bitmap_Write a PPM file



C#: using System;
using System.IO;
class PPMWriter
{
    public static void WriteBitmapToPPM(string file, Bitmap bitmap)
        {
            
            var writer = new StreamWriter(file);
            writer.WriteLine("P6");
            writer.WriteLine($"{bitmap.Width}  {bitmap.Height}");
            writer.WriteLine("255");
            writer.Close();
            
            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));
            for (int x = 0; x < bitmap.Height; x++)
                for (int y = 0; y < bitmap.Width; y++)
                {
                    Color color = bitmap.GetPixel(y, x);
                    writerB.Write(color.R);
                    writerB.Write(color.G);
                    writerB.Write(color.B);
                }
            writerB.Close();
        }
}



Java: import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class PPMWriter {

    public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {
        file.delete();

        try (var os = new FileOutputStream(file, true);
             var bw = new BufferedOutputStream(os)) {
            var header = String.format("P6\n%d %d\n255\n",
                    bitmap.getWidth(), bitmap.getHeight());

            bw.write(header.getBytes(StandardCharsets.US_ASCII));

            for (var y = 0; y < bitmap.getHeight(); y++) {
                for (var x = 0; x < bitmap.getWidth(); x++) {
                    var pixel = bitmap.getPixel(x, y);
                    bw.write(pixel.getRed());
                    bw.write(pixel.getGreen());
                    bw.write(pixel.getBlue());
                }
            }
        }
    }
}
Task: Delete a file



C#: using System;
using System.IO;

namespace DeleteFile {
  class Program {
    static void Main() {
      File.Delete("input.txt");
      Directory.Delete("docs");
      File.Delete("/input.txt");
      Directory.Delete("/docs");
    }
  }
}



Java: import java.io.File;

public class FileDeleteTest {
    public static boolean deleteFile(String filename) {
        boolean exists = new File(filename).delete();
        return exists;
    }
    
    public static void test(String type, String filename) {
        System.out.println("The following " + type + " called " + filename + 
            (deleteFile(filename) ? " was deleted." : " could not be deleted.")
        );
    }

    public static void main(String args[]) {
        test("file", "input.txt");
        test("file", File.seperator + "input.txt");
        test("directory", "docs");
        test("directory", File.seperator + "docs" + File.seperator);
    }
}
Task: Average loop length



C#: public class AverageLoopLength {
	private static int N = 100000;
	
	private static double analytical(int n) {
		double[] factorial = new double[n + 1];
		double[] powers = new double[n + 1];
		powers[0] = 1.0;
		factorial[0] = 1.0;
		for (int i = 1; i <= n; i++) {
			factorial[i] = factorial[i - 1] * i;
			powers[i] = powers[i - 1] * n;
		}
		double sum = 0;
		
		for (int i = 1; i <= n; i++) {
			sum += factorial[n] / factorial[n - i] / powers[i];
		}
		return sum;
	}

	private static double average(int n) {
		Random rnd = new Random();
		double sum = 0.0;
		for (int a = 0; a < N; a++) {
			int[] random = new int[n];
			for (int i = 0; i < n; i++) {
				random[i] = rnd.Next(n);
			}
			var seen = new HashSet<double>(n);
			int current = 0;
			int length = 0;
			while (seen.Add(current)) {
				length++;
				current = random[current];
			}
			sum += length;
		}
		return sum / N;
	}
	
	public static void Main(string[] args) {
	Console.WriteLine(" N    average    analytical    (error)");
	Console.WriteLine("===  =========  ============  =========");
		for (int i = 1; i <= 20; i++) {
			var average = AverageLoopLength.average(i);
			var analytical = AverageLoopLength.analytical(i);
			Console.WriteLine("{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
		}
	}
}



Java: import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class AverageLoopLength {

    private static final int N = 100000;

    
    private static double analytical(int n) {
        double[] factorial = new double[n + 1];
        double[] powers = new double[n + 1];
        powers[0] = 1.0;
        factorial[0] = 1.0;
        for (int i = 1; i <= n; i++) {
            factorial[i] = factorial[i - 1] * i;
            powers[i] = powers[i - 1] * n;
        }
        double sum = 0;
        
        for (int i = 1; i <= n; i++) {
            sum += factorial[n] / factorial[n - i] / powers[i];
        }
        return sum;
    }

    private static double average(int n) {
        Random rnd = new Random();
        double sum = 0.0;
        for (int a = 0; a < N; a++) {
            int[] random = new int[n];
            for (int i = 0; i < n; i++) {
                random[i] = rnd.nextInt(n);
            }
            Set<Integer> seen = new HashSet<>(n);
            int current = 0;
            int length = 0;
            while (seen.add(current)) {
                length++;
                current = random[current];
            }
            sum += length;
        }
        return sum / N;
    }

    public static void main(String[] args) {
        System.out.println(" N    average    analytical    (error)");
        System.out.println("===  =========  ============  =========");
        for (int i = 1; i <= 20; i++) {
            double avg = average(i);
            double ana = analytical(i);
            System.out.println(String.format("%3d  %9.4f  %12.4f  (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
        }
    }
}
Task: String interpolation (included)



C#: class Program
{
    static void Main()
    {
        string extra = "little";
        string formatted = $"Mary had a {extra} lamb.";
        System.Console.WriteLine(formatted);
    }
}



Java: String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little); 
System.out.println(replaced);

System.out.printf("Mary had a %s lamb.", little);

String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);
Task: Partition function P



C#: using System;

class Program {

    const long Lm = (long)1e18;
    const string Fm = "D18";

    
    struct LI { public long lo, ml, mh, hi, tp; }

    static void inc(ref LI d, LI s) { 
        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
        d.tp += s.tp;
    }
 
    static void dec(ref LI d, LI s) { 
        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
        d.tp -= s.tp;
    }

    static LI set(long s) { LI d;
      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }

  static string fmt(LI x) { 
    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
    return x.lo.ToString();
  }

  static LI partcount(int n) {
    var P = new LI[n + 1]; P[0] = set(1);
    for (int i = 1; i <= n; i++) {
      int k = 0, d = -2, j = i;
      LI x = set(0);
      while (true) {
        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;
        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;
      }
      P[i] = x;
    }
    return P[n];
  }

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew ();
    var res = partcount(6666); sw.Stop();
    Console.Write("{0}  {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
  }
}



Java: import java.math.BigInteger;

public class PartitionFunction {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        BigInteger result = partitions(6666);
        long end = System.currentTimeMillis();
        System.out.println("P(6666) = " + result);
        System.out.printf("elapsed time: %d milliseconds\n", end - start);
    }

    private static BigInteger partitions(int n) {
        BigInteger[] p = new BigInteger[n + 1];
        p[0] = BigInteger.ONE;
        for (int i = 1; i <= n; ++i) {
            p[i] = BigInteger.ZERO;
            for (int k = 1; ; ++k) {
                int j = (k * (3 * k - 1))/2;
                if (j > i)
                    break;
                if ((k & 1) != 0)
                    p[i] = p[i].add(p[i - j]);
                else
                    p[i] = p[i].subtract(p[i - j]);
                j += k;
                if (j > i)
                    break;
                if ((k & 1) != 0)
                    p[i] = p[i].add(p[i - j]);
                else
                    p[i] = p[i].subtract(p[i - j]);
            }
        }
        return p[n];
    }
}
Task: Numbers with prime digits whose sum is 13



C#: using System;
using static System.Console; 
using LI = System.Collections.Generic.SortedSet<int>;

class Program {

  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
    if (lft == 0) res.Add(vlu);
    else if (lft > 0) foreach (int itm in set)
      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
    return res; }

  static void Main(string[] args) { WriteLine(string.Join(" ",
      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}



Java: public class PrimeDigits {
    private static boolean primeDigitsSum13(int n) {
        int sum = 0;
        while (n > 0) {
            int r = n % 10;
            if (r != 2 && r != 3 && r != 5 && r != 7) {
                return false;
            }
            n /= 10;
            sum += r;
        }
        return sum == 13;
    }

    public static void main(String[] args) {
        
        int c = 0;
        for (int i = 1; i < 1_000_000; i++) {
            if (primeDigitsSum13(i)) {
                System.out.printf("%6d ", i);
                if (c++ == 10) {
                    c = 0;
                    System.out.println();
                }
            }
        }
        System.out.println();
    }
}