WeixiangYan/CodeTransOcean huggingface dataset:
Task: Magic squares of doubly even order



C#: using System;

namespace MagicSquareDoublyEven
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 8;
            var result = MagicSquareDoublyEven(n);
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                    Console.Write("{0,2} ", result[i, j]);
                Console.WriteLine();
            }
            Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2);
            Console.ReadLine();
        }

        private static int[,] MagicSquareDoublyEven(int n)
        {
            if (n < 4 || n % 4 != 0)
                throw new ArgumentException("base must be a positive "
                        + "multiple of 4");

            
            int bits = 0b1001_0110_0110_1001;
            int size = n * n;
            int mult = n / 4;  

            int[,] result = new int[n, n];

            for (int r = 0, i = 0; r < n; r++)
            {
                for (int c = 0; c < n; c++, i++)
                {
                    int bitPos = c / mult + (r / mult) * 4;
                    result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
                }
            }
            return result;
        }
    }
}
Task: Pythagorean quadruples



C#: using System;

namespace PythagoreanQuadruples {
    class Program {
        const int MAX = 2200;
        const int MAX2 = MAX * MAX * 2;

        static void Main(string[] args) {
            bool[] found = new bool[MAX + 1]; 
            bool[] a2b2 = new bool[MAX2 + 1]; 
            int s = 3;

            for(int a = 1; a <= MAX; a++) {
                int a2 = a * a;
                for (int b=a; b<=MAX; b++) {
                    a2b2[a2 + b * b] = true;
                }
            }

            for (int c = 1; c <= MAX; c++) {
                int s1 = s;
                s += 2;
                int s2 = s;
                for (int d = c + 1; d <= MAX; d++) {
                    if (a2b2[s1]) found[d] = true;
                    s1 += s2;
                    s2 += 2;
                }
            }

            Console.WriteLine("The values of d <= {0} which can't be represented:", MAX);
            for (int d = 1; d < MAX; d++) {
                if (!found[d]) Console.Write("{0}  ", d);
            }
            Console.WriteLine();
        }
    }
}
Task: Sum and product puzzle



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

public class Program
{
    public static void Main()
    {
        const int maxSum = 100;
        var pairs = (
            from X in 2.To(maxSum / 2 - 1)
            from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)
            select new { X, Y, S = X + Y, P = X * Y }
            ).ToHashSet();

        Console.WriteLine(pairs.Count);
        
        var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();
        
        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));
        Console.WriteLine(pairs.Count);
        
        pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));
        Console.WriteLine(pairs.Count);
        
        pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));
        Console.WriteLine(pairs.Count);
        
        foreach (var pair in pairs) Console.WriteLine(pair);
    }
}

public static class Extensions
{
    public static IEnumerable<int> To(this int start, int end) {
        for (int i = start; i <= end; i++) yield return i;
    }
    
    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}
Task: Reflection_List methods



C#: using System;
using System.Reflection;

public class Rosetta
{
    public static void Main()
    {
        
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
            | BindingFlags.Public | BindingFlags.NonPublic
            | BindingFlags.DeclaredOnly;

        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))
            Console.WriteLine(method);
    }
    
    class TestForMethodReflection
    {
        public void MyPublicMethod() {}
        private void MyPrivateMethod() {}
        
        public static void MyPublicStaticMethod() {}
        private static void MyPrivateStaticMethod() {}
    }
    
}
Task: Arithmetic-geometric mean_Calculate Pi



C#: using System;
using System.Numerics;

class AgmPie
{
    static BigInteger IntSqRoot(BigInteger valu, BigInteger guess)
    {
        BigInteger term; do {
            term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break;
            guess += term; guess >>= 1;
        } while (true); return guess;
    }

    static BigInteger ISR(BigInteger term, BigInteger guess)
    {
        BigInteger valu = term * guess; do {
            if (BigInteger.Abs(term - guess) <= 1) break;
            guess += term; guess >>= 1; term = valu / guess;
        } while (true); return guess;
    }

    static BigInteger CalcAGM(BigInteger lam, BigInteger gm, ref BigInteger z,
                              BigInteger ep)
    {
        BigInteger am, zi; ulong n = 1; do {
            am = (lam + gm) >> 1; gm = ISR(lam, gm);
            BigInteger v = am - lam; if ((zi = v * v * n) < ep) break;
            z -= zi; n <<= 1; lam = am;
        } while (true); return am;
    }

    static BigInteger BIP(int exp, ulong man = 1) 
    {
        BigInteger rv = BigInteger.Pow(10, exp); return man == 1 ? rv : man * rv;
    }

    static void Main(string[] args)
    {
        int d = 25000;
        if (args.Length > 0)
        {
            int.TryParse(args[0], out d);
            if (d < 1 || d > 999999) d = 25000;
        }
        DateTime st = DateTime.Now;
        BigInteger am = BIP(d),
          gm = IntSqRoot(BIP(d + d - 1, 5),
                             BIP(d - 15, (ulong)(Math.Sqrt(0.5) * 1e+15))),
          z = BIP(d + d - 2, 25),
          agm = CalcAGM(am, gm, ref z, BIP(d + 1)),
          pi = agm * agm * BIP(d - 2) / z;
        Console.WriteLine("Computation time: {0:0.0000} seconds ",
                             (DateTime.Now - st).TotalMilliseconds / 1000);
        string s = pi.ToString();
        Console.WriteLine("{0}.{1}", s[0], s.Substring(1));
        if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
    }
}
Task: Numerical integration_Gauss-Legendre Quadrature



C#: using System;


                    
public class Program {

    public static double[][] legeCoef(int N) {
        
        double[][] lcoef = new double[N+1][];
        for (int i=0; i < lcoef.Length; ++i) 
            lcoef[i] = new double[N+1];


        lcoef[0][0] = lcoef[1][1] = 1;
        for (int n = 2; n <= N; n++) {
            lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
            for (int i = 1; i <= n; i++) 
                lcoef[n][i] = ((2*n - 1) * lcoef[n-1][i-1] 
                               - (n-1) * lcoef[n-2][i] ) / n;
        }
        return lcoef;
    }


    static double legeEval(double[][] lcoef, int N, double x) {
        double s = lcoef[N][N];
        for (int i = N; i > 0; --i)
            s = s * x + lcoef[N][i-1];
        return s;
    }

    static double legeDiff(double[][] lcoef, int N, double x) {
        return N * (x * legeEval(lcoef, N, x) - legeEval(lcoef, N-1, x)) / (x*x - 1);
    }

    static void legeRoots(double[][] lcoef, int N, out double[] lroots,  out double[] weight) {
        lroots = new double[N];
        weight = new double[N];

        double x, x1;
        for (int i = 1; i <= N; i++) {
            x = Math.Cos(Math.PI * (i - 0.25) / (N + 0.5));
            do { 
                x1 = x;
                x -= legeEval(lcoef, N, x) / legeDiff(lcoef, N, x);
            } 
            while (x != x1);
            lroots[i-1] = x;

            x1 = legeDiff(lcoef, N, x);
            weight[i-1] = 2 / ((1 - x*x) * x1*x1);
        }
    }
    
    

    static double legeInte(Func<Double, Double> f, int N, double[] weights, double[] lroots, double a, double b) {
        double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0;
        for (int i = 0; i < N; i++)
            sum += weights[i] * f.Invoke(c1 * lroots[i] + c2);
        return c1 * sum;
    }
    
    
    public static string Combine(double[] arrayD) {
        return string.Join(", ", arrayD);	
    }

    public static void Main() {
        int N = 5;
        
        var lcoeff = legeCoef(N);
        
        double[] roots;
        double[] weights;
        legeRoots(lcoeff, N, out roots, out weights);
        
        var integrateResult = legeInte(x=>Math.Exp(x), N, weights, roots, -3, 3);
        
        Console.WriteLine("Roots:   " + Combine(roots));
        Console.WriteLine("Weights: " + Combine(weights)+ "\n" );
        Console.WriteLine("integral: " + integrateResult );
        Console.WriteLine("actual:   " + (Math.Exp(3)-Math.Exp(-3)) );
    }


}
Task: World Cup group stage



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
using static System.Linq.Enumerable;

namespace WorldCupGroupStage
{
    public static class WorldCupGroupStage
    {
        static int[][] _histogram;

        static WorldCupGroupStage()
        {
            int[] scoring = new[] { 0, 1, 3 };

            _histogram = Repeat<Func<int[]>>(()=>new int[10], 4).Select(f=>f()).ToArray();

            var teamCombos = Range(0, 4).Combinations(2).Select(t2=>t2.ToArray()).ToList();

            foreach (var results in Range(0, 3).CartesianProduct(6))
            {
                var points = new int[4]; 

                foreach (var (result, teams) in results.Zip(teamCombos, (r, t) => (r, t)))
                {
                    points[teams[0]] += scoring[result];
                    points[teams[1]] += scoring[2 - result];
                }

                foreach(var (p,i) in points.OrderByDescending(a => a).Select((p,i)=>(p,i)))
                    _histogram[i][p]++;
            }
        }
      
       
       
       static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> seqs) => 
            seqs.Aggregate(Empty<T>().ToSingleton(), (acc, sq) => acc.SelectMany(a => sq.Select(s => a.Append(s))));
        
       static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> seq, int repeat = 1) => 
            Repeat(seq, repeat).CartesianProduct();

       static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) => 
            seq.Aggregate(Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b))));

       static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) => 
            seq.Combinations().Where(s => s.Count() == numItems);

        private static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }

        static new string ToString()
        {
            var sb = new StringBuilder();

            var range = String.Concat(Range(0, 10).Select(i => $"{i,-3} "));
            sb.AppendLine($"Points      : {range}");

            var u = String.Concat(Repeat("─", 40+13));
            sb.AppendLine($"{u}");

            var places = new[] { "First", "Second", "Third", "Fourth" };
            foreach (var row in _histogram.Select((r, i) => (r, i)))
            {
                sb.Append($"{places[row.i],-6} place: ");
                foreach (var standing in row.r)
                    sb.Append($"{standing,-3} ");
                sb.Append("\n");
            }

            return sb.ToString();
        }

        static void Main(string[] args)
        {
            Write(ToString());
            Read();
        }
    }
}
Task: Ramer-Douglas-Peucker line simplification



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

namespace LineSimplification {
    using Point = Tuple<double, double>;

    class Program {
        static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) {
            double dx = lineEnd.Item1 - lineStart.Item1;
            double dy = lineEnd.Item2 - lineStart.Item2;

            
            double mag = Math.Sqrt(dx * dx + dy * dy);
            if (mag > 0.0) {
                dx /= mag;
                dy /= mag;
            }
            double pvx = pt.Item1 - lineStart.Item1;
            double pvy = pt.Item2 - lineStart.Item2;

            
            double pvdot = dx * pvx + dy * pvy;

            
            double ax = pvx - pvdot * dx;
            double ay = pvy - pvdot * dy;

            return Math.Sqrt(ax * ax + ay * ay);
        }

        static void RamerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> output) {
            if (pointList.Count < 2) {
                throw new ArgumentOutOfRangeException("Not enough points to simplify");
            }

            
            double dmax = 0.0;
            int index = 0;
            int end = pointList.Count - 1;
            for (int i = 1; i < end; ++i) {
                double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]);
                if (d > dmax) {
                    index = i;
                    dmax = d;
                }
            }

            
            if (dmax > epsilon) {
                List<Point> recResults1 = new List<Point>();
                List<Point> recResults2 = new List<Point>();
                List<Point> firstLine = pointList.Take(index + 1).ToList();
                List<Point> lastLine = pointList.Skip(index).ToList();
                RamerDouglasPeucker(firstLine, epsilon, recResults1);
                RamerDouglasPeucker(lastLine, epsilon, recResults2);

                
                output.AddRange(recResults1.Take(recResults1.Count - 1));
                output.AddRange(recResults2);
                if (output.Count < 2) throw new Exception("Problem assembling output");
            }
            else {
                
                output.Clear();
                output.Add(pointList[0]);
                output.Add(pointList[pointList.Count - 1]);
            }
        }

        static void Main(string[] args) {
            List<Point> pointList = new List<Point>() {
                new Point(0.0,0.0),
                new Point(1.0,0.1),
                new Point(2.0,-0.1),
                new Point(3.0,5.0),
                new Point(4.0,6.0),
                new Point(5.0,7.0),
                new Point(6.0,8.1),
                new Point(7.0,9.0),
                new Point(8.0,9.0),
                new Point(9.0,9.0),
            };
            List<Point> pointListOut = new List<Point>();
            RamerDouglasPeucker(pointList, 1.0, pointListOut);
            Console.WriteLine("Points remaining after simplification:");
            pointListOut.ForEach(p => Console.WriteLine(p));
        }
    }
}
Task: Burrows–Wheeler transform



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

namespace BurrowsWheeler {
    class Program {
        const char STX = (char)0x02;
        const char ETX = (char)0x03;

        private static void Rotate(ref char[] a) {
            char t = a.Last();
            for (int i = a.Length - 1; i > 0; --i) {
                a[i] = a[i - 1];
            }
            a[0] = t;
        }

        
        private static int Compare(string s1, string s2) {
            for (int i = 0; i < s1.Length && i < s2.Length; ++i) {
                if (s1[i] < s2[i]) {
                    return -1;
                }
                if (s2[i] < s1[i]) {
                    return 1;
                }
            }
            if (s1.Length < s2.Length) {
                return -1;
            }
            if (s2.Length < s1.Length) {
                return 1;
            }
            return 0;
        }

        static string Bwt(string s) {
            if (s.Any(a => a == STX || a == ETX)) {
                throw new ArgumentException("Input can't contain STX or ETX");
            }
            char[] ss = (STX + s + ETX).ToCharArray();
            List<string> table = new List<string>();
            for (int i = 0; i < ss.Length; ++i) {
                table.Add(new string(ss));
                Rotate(ref ss);
            }
            table.Sort(Compare);
            return new string(table.Select(a => a.Last()).ToArray());
        }

        static string Ibwt(string r) {
            int len = r.Length;
            List<string> table = new List<string>(new string[len]);
            for (int i = 0; i < len; ++i) {
                for (int j = 0; j < len; ++j) {
                    table[j] = r[j] + table[j];
                }
                table.Sort(Compare);
            }
            foreach (string row in table) {
                if (row.Last() == ETX) {
                    return row.Substring(1, len - 2);
                }
            }
            return "";
        }

        static string MakePrintable(string s) {
            return s.Replace(STX, '^').Replace(ETX, '|');
        }

        static void Main() {
            string[] tests = new string[] {
                "banana",
                "appellee",
                "dogwood",
                "TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
                "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
                "\u0002ABC\u0003"
            };

            foreach (string test in tests) {
                Console.WriteLine(MakePrintable(test));
                Console.Write(" --> ");

                string t = "";
                try {
                    t = Bwt(test);
                    Console.WriteLine(MakePrintable(t));
                } catch (Exception e) {
                    Console.WriteLine("ERROR: {0}", e.Message);
                }

                string r = Ibwt(t);
                Console.WriteLine(" --> {0}", r);
                Console.WriteLine();
            }
        }
    }
}
Task: Statistics_Normal distribution



C#: using System;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Statistics;

class Program
{
    static void RunNormal(int sampleSize)
    {
        double[] X = new double[sampleSize];
        var norm = new Normal(new Random());
        norm.Samples(X);

        const int numBuckets = 10;
        var histogram = new Histogram(X, numBuckets);
        Console.WriteLine("Sample size: {0:N0}", sampleSize);
        for (int i = 0; i < numBuckets; i++)
        {
            string bar = new String('#', (int)(histogram[i].Count * 360 / sampleSize));
            Console.WriteLine(" {0:0.00} : {1}", histogram[i].LowerBound, bar);
        }
        var statistics = new DescriptiveStatistics(X);
        Console.WriteLine("  Mean: " + statistics.Mean);
        Console.WriteLine("StdDev: " + statistics.StandardDeviation);
        Console.WriteLine();
    }
    static void Main(string[] args)
    {
        RunNormal(100);
        RunNormal(1000);
        RunNormal(10000);
    }
}
Task: Readline interface



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

namespace ReadlineInterface {
    class Program {
        static LinkedList<string> histArr = new LinkedList<string>();

        static void AppendHistory([CallerMemberName] string name = "unknown") {
            histArr.AddLast(name);
        }

        static void Hist() {
            if (histArr.Count == 0) {
                Console.WriteLine("No history");
            }
            else {
                foreach (string cmd in histArr) {
                    Console.WriteLine(" - {0}", cmd);
                }
            }
            AppendHistory();
        }

        static void Hello() {
            Console.WriteLine("Hello World!");
            AppendHistory();
        }

        static void Help() {
            Console.WriteLine("Available commands:");
            Console.WriteLine("  hello");
            Console.WriteLine("  hist");
            Console.WriteLine("  exit");
            Console.WriteLine("  help");
            AppendHistory();
        }

        static void Main(string[] args) {
            Dictionary<string, Action> cmdDict = new Dictionary<string, Action>();
            cmdDict.Add("help", Help);
            cmdDict.Add("hist", Hist);
            cmdDict.Add("hello", Hello);

            Console.WriteLine("Enter a command, type help for a listing.");
            while (true) {
                Console.Write(">");
                string line = Console.ReadLine();
                if (line=="exit") {
                    break;
                }

                Action action;
                if (cmdDict.TryGetValue(line, out action)) {
                    action.Invoke();
                } else {
                    Help();
                }
            }
        }
    }
}
Task: Addition chains



C#: using System;

namespace AdditionChains {
    class Program {
        static int[] Prepend(int n, int[] seq) {
            int[] result = new int[seq.Length + 1];
            Array.Copy(seq, 0, result, 1, seq.Length);
            result[0] = n;
            return result;
        }

        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {
            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);
            if (seq[0] == n) return new Tuple<int, int>(pos, 1);
            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);
            return new Tuple<int, int>(min_len, 0);
        }

        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {
            if (i > pos) return new Tuple<int, int>(min_len, 0);

            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);
            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);

            if (res2.Item1 < res1.Item1) return res2;
            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);

            throw new Exception("TryPerm exception");
        }

        static Tuple<int, int> InitTryPerm(int x) {
            return TryPerm(0, 0, new int[] { 1 }, x, 12);
        }

        static void FindBrauer(int num) {
            Tuple<int, int> res = InitTryPerm(num);
            Console.WriteLine();
            Console.WriteLine("N = {0}", num);
            Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1);
            Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2);
        }

        static void Main(string[] args) {
            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };
            Array.ForEach(nums, n => FindBrauer(n));
        }
    }
}