WeixiangYan/CodeTransOcean huggingface dataset:
Task: First-class functions



C#: using System;

class Program
{
    static void Main(string[] args)
    {
        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));

        var functionTuples = new[]
        {
            (forward: Math.Sin, backward: Math.Asin),
            (forward: Math.Cos, backward: Math.Acos),
            (forward: cube,     backward: croot)
        };

        foreach (var ft in functionTuples)
        {
            Console.WriteLine(ft.backward(ft.forward(0.5)));
        }
    }
}



Java: import java.util.ArrayList;

public class FirstClass{
	
	public interface Function<A,B>{
		B apply(A x);
	}
	
	public static <A,B,C> Function<A, C> compose(
			final Function<B, C> f, final Function<A, B> g) {
		return new Function<A, C>() {
			@Override public C apply(A x) {
				return f.apply(g.apply(x));
			}
		};
	}
	 
	public static void main(String[] args){
		ArrayList<Function<Double, Double>> functions =
			new ArrayList<Function<Double,Double>>();
		
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.cos(x);
					}
				});
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.tan(x);
					}
				});
		functions.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return x * x;
					}
				});
		
		ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
		
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.acos(x);
					}
				});
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.atan(x);
					}
				});
		inverse.add(
				new Function<Double, Double>(){
					@Override public Double apply(Double x){
						return Math.sqrt(x);
					}
				});
		System.out.println("Compositions:");
		for(int i = 0; i < functions.size(); i++){
			System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
		}
		System.out.println("Hard-coded compositions:");
		System.out.println(Math.cos(Math.acos(0.5)));
		System.out.println(Math.tan(Math.atan(0.5)));
		System.out.println(Math.pow(Math.sqrt(0.5), 2));
	}
}
Task: Proper divisors



C#: namespace RosettaCode.ProperDivisors
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal static class Program
    {
        private static IEnumerable<int> ProperDivisors(int number)
        {
            return
                Enumerable.Range(1, number / 2)
                    .Where(divisor => number % divisor == 0);
        }

        private static void Main()
        {
            foreach (var number in Enumerable.Range(1, 10))
            {
                Console.WriteLine("{0}: {{{1}}}", number,
                    string.Join(", ", ProperDivisors(number)));
            }

            var record = Enumerable.Range(1, 20000).Select(number => new
            {
                Number = number,
                Count = ProperDivisors(number).Count()
            }).OrderByDescending(currentRecord => currentRecord.Count).First();
            Console.WriteLine("{0}: {1}", record.Number, record.Count);
        }
    }
}



Java: import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Proper{
    public static List<Integer> properDivs(int n){
        List<Integer> divs = new LinkedList<Integer>();
        if(n == 1) return divs;
        divs.add(1);
        for(int x = 2; x < n; x++){
            if(n % x == 0) divs.add(x);
        }
        
        Collections.sort(divs);
        
        return divs;
    }
    
    public static void main(String[] args){
        for(int x = 1; x <= 10; x++){
            System.out.println(x + ": " + properDivs(x));
        }
        
        int x = 0, count = 0;
        for(int n = 1; n <= 20000; n++){
            if(properDivs(n).size() > count){
                x = n;
                count = properDivs(n).size();
            }
        }
        System.out.println(x + ": " + count);
    }
}
Task: XML_Output



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

class Program
{
    static string CreateXML(Dictionary<string, string> characterRemarks)
    {
        var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key)));
        var xml = new XElement("CharacterRemarks", remarks);
        return xml.ToString();
    }

    static void Main(string[] args)
    {
        var characterRemarks = new Dictionary<string, string>
        {
            { "April", "Bubbly: I'm > Tam and <= Emily" },
            { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" },
            { "Emily", "Short & shrift" }
        };

        string xml = CreateXML(characterRemarks);
        Console.WriteLine(xml);
    }
}



Java: import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlCreation {

  private static final String[] names = {"April", "Tam O'Shanter", "Emily"};
  private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily",
    "Burns: \"When chapman billies leave the street ...\"",
      "Short & shrift"};
  
  public static void main(String[] args) {
    try {
      
      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      
      
      final Element root = doc.createElement("CharacterRemarks");
      doc.appendChild(root);
      
      
      for(int i = 0; i < names.length; i++) {
        final Element character = doc.createElement("Character");
        root.appendChild(character);
        character.setAttribute("name", names[i]);
        character.appendChild(doc.createTextNode(remarks[i]));
      }
      
      
      
      final Source source = new DOMSource(doc);
      
      
      final StringWriter buffer = new StringWriter();
      
      
      final Result result = new StreamResult(buffer);
      
      
      final Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty("indent", "yes");
      transformer.transform(source, result);
      
      
      
      System.out.println(buffer.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
}
Task: Regular expressions



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

class Program {
    static void Main(string[] args) {
        string str = "I am a string";

        if (new Regex("string$").IsMatch(str)) {
            Console.WriteLine("Ends with string.");
        }

        str = new Regex(" a ").Replace(str, " another ");
        Console.WriteLine(str);
    }
}



Java: String str = "I am a string";
if (str.matches(".*string")) { 
  System.out.println("ends with 'string'");
}
Task: Hash from two arrays



C#: static class Program
{
    static void Main()
    {
        System.Collections.Hashtable h = new System.Collections.Hashtable();

        string[] keys = { "foo", "bar", "val" };
        string[] values = { "little", "miss", "muffet" };

        System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");

        for (int i = 0; i < keys.Length; i++)
        {
            h.Add(keys[i], values[i]);
        }
    }
}



Java: import java.util.HashMap;
public static void main(String[] args){
	String[] keys= {"a", "b", "c"};
	int[] vals= {1, 2, 3};
	HashMap<String, Integer> hash= new HashMap<String, Integer>();

	for(int i= 0; i < keys.length; i++){
	   hash.put(keys[i], vals[i]);
	}
}
Task: Sorting algorithms_Heapsort



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

public class HeapSortClass
{
    public static void HeapSort<T>(T[] array)
    {
        HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);
    }

    public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)
    {
        HeapSort<T>(array, offset, length, comparer.Compare);
    }

    public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)
    {
        
        for (int i = 0; i < length; i++)
        {
            int index = i;
            T item = array[offset + i]; 

            
            while (index > 0 &&
                comparison(array[offset + (index - 1) / 2], item) < 0)
            {
                int top = (index - 1) / 2;
                array[offset + index] = array[offset + top];
                index = top;
            }
            array[offset + index] = item;
        }

        for (int i = length - 1; i > 0; i--)
        {
            
            T last = array[offset + i];
            array[offset + i] = array[offset];

            int index = 0;
            
            while (index * 2 + 1 < i)
            {
                int left = index * 2 + 1, right = left + 1;

                if (right < i && comparison(array[offset + left], array[offset + right]) < 0)
                {
                    if (comparison(last, array[offset + right]) > 0) break;

                    array[offset + index] = array[offset + right];
                    index = right;
                }
                else
                {
                    if (comparison(last, array[offset + left]) > 0) break;

                    array[offset + index] = array[offset + left];
                    index = left;
                }
            }
            array[offset + index] = last;
        }
    }

    static void Main()
    {
        
        byte[] r = {5, 4, 1, 2};
        HeapSort(r);

        string[] s = { "-", "D", "a", "33" };
        HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);
    }
}



Java: public static void heapSort(int[] a){
	int count = a.length;

	
	heapify(a, count);

	int end = count - 1;
	while(end > 0){
		
		
		int tmp = a[end];
		a[end] = a[0];
		a[0] = tmp;
		
		siftDown(a, 0, end - 1);
		
		
		end--;
	}
}

public static void heapify(int[] a, int count){
	
	int start = (count - 2) / 2; 

	while(start >= 0){
		
		
		
		siftDown(a, start, count - 1);
		start--;
	}
	
}

public static void siftDown(int[] a, int start, int end){
	
	int root = start;

	while((root * 2 + 1) <= end){      
		int child = root * 2 + 1;           
		
		if(child + 1 <= end && a[child] < a[child + 1])
			child = child + 1;           
		if(a[root] < a[child]){     
			int tmp = a[root];
			a[root] = a[child];
			a[child] = tmp;
			root = child;                
		}else
			return;
	}
}
Task: Playing cards



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

public struct Card
{
    public Card(string rank, string suit) : this()
    {
        Rank = rank;
        Suit = suit;
    }

    public string Rank { get; }
    public string Suit { get; }

    public override string ToString() => $"{Rank} of {Suit}";
}

public class Deck : IEnumerable<Card>
{
    static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
    static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
    readonly List<Card> cards;
 
    public Deck() {
        cards = (from suit in suits
                from rank in ranks
                select new Card(rank, suit)).ToList();
    }

    public int Count => cards.Count;

    public void Shuffle() {
        
        var random = new Random();
        for (int i = 0; i < cards.Count; i++) {
            int r = random.Next(i, cards.Count);
            var temp = cards[i];
            cards[i] = cards[r];
            cards[r] = temp;
        }
    }

    public Card Deal() {
        int last = cards.Count - 1;
        Card card = cards[last];
        
        
        cards.RemoveAt(last);
        return card;
    }

    public IEnumerator<Card> GetEnumerator() {
        
        
        for (int i = cards.Count - 1; i >= 0; i--)
            yield return cards[i];
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}



Java: public enum Pip { Two, Three, Four, Five, Six, Seven, 
    Eight, Nine, Ten, Jack, Queen, King, Ace }
Task: Arrays



C#:  int[] numbers = new int[10];



Java: Int[] literalArray = [1,2,3];
Int[] fixedLengthArray = new Int[10];
Int[] variableArray = new Int[];

assert literalArray.size == 3; 
Int n = literalArray[2];       
fixedLengthArray[4] = 12345;   

fixedLengthArray += 6789;  
variableArray    += 6789;
Task: Sierpinski carpet



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

class Program
{
    static List<string> NextCarpet(List<string> carpet)
    {
        return carpet.Select(x => x + x + x)
                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))
                     .Concat(carpet.Select(x => x + x + x)).ToList();
    }

    static List<string> SierpinskiCarpet(int n)
    {
        return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet));
    }

    static void Main(string[] args)
    {
        foreach (string s in SierpinskiCarpet(3))
            Console.WriteLine(s);
    }
}



Java: public static boolean inCarpet(long x, long y) {
    while (x!=0 && y!=0) {
        if (x % 3 == 1 && y % 3 == 1)
            return false;
        x /= 3;
        y /= 3;
    }
    return true;
}
 
public static void carpet(final int n) {
    final double power = Math.pow(3,n);
    for(long i = 0; i < power; i++) {
        for(long j = 0; j < power; j++) {
            System.out.print(inCarpet(i, j) ? "*" : " ");
        }
        System.out.println();
    }
}
Task: Sorting algorithms_Bogosort



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

namespace RosettaCode.BogoSort
{
    public static class BogoSorter
    {
        public static void Sort<T>(List<T> list) where T:IComparable
        {
            while (!list.isSorted())
            {
                list.Shuffle();
            }
        }

        private static bool isSorted<T>(this IList<T> list) where T:IComparable
        {
            if(list.Count<=1)
                return true;
            for (int i = 1 ; i < list.Count; i++)
                if(list[i].CompareTo(list[i-1])<0) return false;
            return true;
        }

        private static void Shuffle<T>(this IList<T> list)
        {
            Random rand = new Random();
            for (int i = 0; i < list.Count; i++)
            {
                int swapIndex = rand.Next(list.Count);
                T temp = list[swapIndex];
                list[swapIndex] = list[i];
                list[i] = temp;
            }
        }
    }

    class TestProgram
    {
        static void Main()
        {
            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
            BogoSorter.Sort(testList);
            foreach (int i in testList) Console.Write(i + " ");
        }

    }
}



Java: public class BogoSort 
{
	public static void main(String[] args)
	{
		
		int[] arr={4,5,6,0,7,8,9,1,2,3};
		
		BogoSort now=new BogoSort();
		System.out.print("Unsorted: ");
		now.display1D(arr);
		
		now.bogo(arr);
		
		System.out.print("Sorted: ");
		now.display1D(arr);
	}
	void bogo(int[] arr)
	{
		
		int shuffle=1;
		for(;!isSorted(arr);shuffle++)
			shuffle(arr);
		
		System.out.println("This took "+shuffle+" shuffles.");
	}
	void shuffle(int[] arr)
	{
		
		int i=arr.length-1;
		while(i>0)
			swap(arr,i--,(int)(Math.random()*i));
	}
	void swap(int[] arr,int i,int j)
	{
		int temp=arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
	}
	boolean isSorted(int[] arr)
	{

		for(int i=1;i<arr.length;i++)
			if(arr[i]<arr[i-1])
				return false;
		return true;
	}
	void display1D(int[] arr)
	{
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}

}
Task: Euler method



C#: using System;

namespace prog
{
	class MainClass
	{
		const float T0 = 100f;
		const float TR = 20f;
		const float k = 0.07f;
		readonly static float[] delta_t = {2.0f,5.0f,10.0f};
		const int n = 100;
		
		public delegate float func(float t);
		static float NewtonCooling(float t)
		{
			return -k * (t-TR);			
		}
		
		public static void Main (string[] args)
		{
			func f = new func(NewtonCooling); 
			for(int i=0; i<delta_t.Length; i++)
			{
				Console.WriteLine("delta_t = " + delta_t[i]);
				Euler(f,T0,n,delta_t[i]);
			}
		}
				
		public static void Euler(func f, float y, int n, float h)
		{
			for(float x=0; x<=n; x+=h)
			{
				Console.WriteLine("\t" + x + "\t" + y);
				y += h * f(y);	
			}
		}
	}
}



Java: public class Euler {
  private static void euler (Callable f, double y0, int a, int b, int h) {
    int t = a;
    double y = y0;
    while (t < b) {
      System.out.println ("" + t + " " + y);
      t += h;
      y += h * f.compute (t, y);
    }
    System.out.println ("DONE");
  }

  public static void main (String[] args) {
    Callable cooling = new Cooling ();
    int[] steps = {2, 5, 10};
    for (int stepSize : steps) {
      System.out.println ("Step size: " + stepSize);
      euler (cooling, 100.0, 0, 100, stepSize);
    }
  }
}


interface Callable {
  public double compute (int time, double t);
}


class Cooling implements Callable {
  public double compute (int time, double t) {
    return -0.07 * (t - 20);
  }
}
Task: Sequence of non-squares



C#: using System;
using System.Diagnostics;

namespace sons
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i < 23; i++)            
                Console.WriteLine(nonsqr(i));            

            for (int i = 1; i < 1000000; i++)
            {
                double j = Math.Sqrt(nonsqr(i));
                Debug.Assert(j != Math.Floor(j),"Square");
            }            
        }

        static int nonsqr(int i)
        {
            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));
        }
    }
}



Java: public class SeqNonSquares {
    public static int nonsqr(int n) {
        return n + (int)Math.round(Math.sqrt(n));
    }
    
    public static void main(String[] args) {
        
        for (int i = 1; i < 23; i++)
            System.out.print(nonsqr(i) + " ");
        System.out.println();
        
        
        for (int i = 1; i < 1000000; i++) {
            double j = Math.sqrt(nonsqr(i));
            assert j != Math.floor(j);
        }
    }
}
Task: Substring



C#: using System;
namespace SubString
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "0123456789";
            const int n = 3;
            const int m = 2;
            const char c = '3';
            const string z = "345";

            
            Console.WriteLine(s.Substring(n, m));
            
            Console.WriteLine(s.Substring(n, s.Length - n));
            
            Console.WriteLine(s.Substring(0, s.Length - 1));
            
            Console.WriteLine(s.Substring(s.IndexOf(c), m));
            
            Console.WriteLine(s.Substring(s.IndexOf(z), m));
        }
    }
}



Java: public static String Substring(String str, int n, int m){
    return str.substring(n, n+m);
}
public static String Substring(String str, int n){
    return str.substring(n);
}
public static String Substring(String str){
    return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, int m){
    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);
}
public static String Substring(String str, String sub, int m){
    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}
Task: JortSort



C#: using System;

class Program
{
  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>
  {
    
    T[] originalArray = (T[]) array.Clone();
    Array.Sort(array);

    
    for (var i = 0; i < originalArray.Length; i++)
    {
      if (!Equals(originalArray[i], array[i]))
      {
        return false;
      }
    }

    return true;
  }
}



Java: public class JortSort {
    public static void main(String[] args) {
        System.out.println(jortSort(new int[]{1, 2, 3}));
    }

    static boolean jortSort(int[] arr) {
        return true;
    }
}
Task: Leap year



C#: using System;

class Program
{
    static void Main()
    {
        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })
        {
            Console.WriteLine("{0} is {1}a leap year.",
                              year,
                              DateTime.IsLeapYear(year) ? string.Empty : "not ");
        }
    }
}



Java: import java.util.GregorianCalendar;
import java.text.MessageFormat;

public class Leapyear{
        public static void main(String[] argv){
                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
                GregorianCalendar cal = new GregorianCalendar();
                for(int year : yrs){
                        System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.",
                                                                 year, cal.isLeapYear(year), isLeapYear(year)));
                }

        }
        public static boolean isLeapYear(int year){
                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);
        }
}
Task: Sort numbers lexicographically



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

public class Program
{
    public static void Main() {
        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}");
    }

    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
}



Java: import java.util.List;
import java.util.stream.*;

public class LexicographicalNumbers {

    static List<Integer> lexOrder(int n) {
        int first = 1, last = n;
        if (n < 1) {
            first = n;
            last = 1;
        }
        return IntStream.rangeClosed(first, last)
                        .mapToObj(Integer::toString)
                        .sorted()
                        .map(Integer::valueOf)
                        .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        System.out.println("In lexicographical order:\n");
        int[] ints = {0, 5, 13, 21, -22};
        for (int n : ints) {
           System.out.printf("%3d: %s\n", n, lexOrder(n));
        }
    }
}