WeixiangYan/CodeTransOcean huggingface dataset:
Task: Chaos game



C#: using System.Diagnostics;
using System.Drawing;

namespace RosettaChaosGame
{
    class Program
    {
        static void Main(string[] args)
        {
            var bm = new Bitmap(600, 600);

            var referencePoints = new Point[] {
                new Point(0, 600),
                new Point(600, 600),
                new Point(300, 81)
            };
            var r = new System.Random();
            var p = new Point(r.Next(600), r.Next(600));
            for (int count = 0; count < 10000; count++)
            {
                bm.SetPixel(p.X, p.Y, Color.Magenta);
                int i = r.Next(3);
                p.X = (p.X + referencePoints[i].X) / 2;
                p.Y = (p.Y + referencePoints[i].Y) / 2;
            }
            const string filename = "Chaos Game.png";
            bm.Save(filename);
            Process.Start(filename);
        }
    }
}
Task: Parsing_Shunting-yard algorithm



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

public class Program
{
    public static void Main() {
        string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
        Console.WriteLine(infix.ToPostfix());
    }
}

public static class ShuntingYard
{
    private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators
        = new (string symbol, int precedence, bool rightAssociative) [] {
            ("^", 4, true),
            ("*", 3, false),
            ("/", 3, false),
            ("+", 2, false),
            ("-", 2, false)
    }.ToDictionary(op => op.symbol);

    public static string ToPostfix(this string infix) {
        string[] tokens = infix.Split(' ');
        var stack = new Stack<string>();
        var output = new List<string>();
        foreach (string token in tokens) {
            if (int.TryParse(token, out _)) {
                output.Add(token);
                Print(token);
            } else if (operators.TryGetValue(token, out var op1)) {
                while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {
                    int c = op1.precedence.CompareTo(op2.precedence);
                    if (c < 0 || !op1.rightAssociative && c <= 0) {
                        output.Add(stack.Pop());
                    } else {
                        break;
                    }
                }
                stack.Push(token);
                Print(token);
            } else if (token == "(") {
                stack.Push(token);
                Print(token);
            } else if (token == ")") {
                string top = "";
                while (stack.Count > 0 && (top = stack.Pop()) != "(") {
                    output.Add(top);
                }
                if (top != "(") throw new ArgumentException("No matching left parenthesis.");
                Print(token);
            }
        }
        while (stack.Count > 0) {
            var top = stack.Pop();
            if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis.");
            output.Add(top);
        }
        Print("pop");
        return string.Join(" ", output);
        
        
        void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}");
        
        void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]");
    }
}
Task: Almkvist-Giullera formula for pi



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

class Program {

  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }

  static string dump(int digs, bool show = false) {
    int gb = 1, dg = ++digs + gb, z;
    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,
       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;
    for (BI n = 0; n < dg; n++) {
      if (n > 0) t3 *= BI.Pow(n, 6);
      te = t1 * t2 / t3;
      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);
      else te /= BI.Pow (10, -z);
      if (show && n < 10)
        WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t);
      su += te; if (te < 10) {
        if (show) WriteLine("\n{0} iterations required for {1} digits " +
        "after the decimal point.\n", n, --digs); break; }
      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;
      t2 += 126 + 532 * (d += 2);
    }
    string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) /
      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));
    return s[0] + "." + s.Substring(1, digs); }

  static void Main(string[] args) {
    WriteLine(dump(70, true)); }
}
Task: First power of 2 that has leading decimal digits of 12



C#: 

using System;

class Program {

    
    static long js(int l, int n) {
        long res = 0, f = 1;
        double lf = Math.Log10(2);
        for (int i = l; i > 10; i /= 10) f *= 10;
        while (n > 0)
            if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--;
        return res;
    }

    
    static long gi(int ld, int n) {
        string Ls = ld.ToString();
        long res = 0, count = 0, f = 1;
        for (int i = 1; i <= 18 - Ls.Length; i++) f *= 10;
        const long ten18 = (long)1e18; long probe = 1;
        do {
            probe <<= 1; res++; if (probe >= ten18)
                do {
                    if (probe >= ten18) probe /= 10;
                    if (probe / f == ld)
                        if (++count >= n) { count--; break; }
                    probe <<= 1; res++;
                } while (true);
            string ps = probe.ToString();
            if (ps.Substring(0, Math.Min(Ls.Length, ps.Length)) == Ls)
                if (++count >= n) break;
        } while (true);
        return res;
    }

    
    static long pa(int ld, int n) {
        double L_float64 = Math.Pow(2, 64);
        ulong Log10_2_64 = (ulong)(L_float64 * Math.Log10(2));
        double Log10Num; ulong LmtUpper, LmtLower, Frac64;
        long res = 0, dgts = 1, cnt;
        for (int i = ld; i >= 10; i /= 10) dgts *= 10;
        Log10Num = Math.Log10((ld + 1.0) / dgts);
        
        if (Log10Num >= 0.5) {
            LmtUpper = (ld + 1.0) / dgts < 10.0 ? (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2) : 0;
            Log10Num = Math.Log10((double)ld / dgts);
            LmtLower = (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2);
        } else {
            LmtUpper = (ulong)(Log10Num * L_float64);
            LmtLower = (ulong)(Math.Log10((double)ld / dgts) * L_float64);
        }
        cnt = 0; Frac64 = 0; if (LmtUpper != 0)
            do {
                res++; Frac64 += Log10_2_64;
                if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper))
                    if (++cnt >= n) break;
            } while (true);
        else 
            do {
                res++; Frac64 += Log10_2_64;
                if (Frac64 >= LmtLower) if (++cnt >= n) break;
            } while (true);
        return res;
    }

    static int[] values = new int[] { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 };

    static void doOne(string name, Func<int, int, long> fun) {
        Console.WriteLine("{0} version:", name);
        var start = DateTime.Now;
        for (int i = 0; i < values.Length; i += 2)
            Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", values[i], values[i + 1], fun(values[i], values[i + 1]));
        Console.WriteLine("Took {0} seconds\n", DateTime.Now - start);
    }

    static void Main() {
        doOne("java simple", js);
        doOne("go integer", gi);
        doOne("pascal alternative", pa);
    }
}
Task: Cipolla's algorithm



C#: using System;
using System.Numerics;

namespace CipollaAlgorithm {
    class Program {
        static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151;

        private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) {
            BigInteger n = BigInteger.Parse(ns);
            BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG;

            
            BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p);

            
            if (ls(n) != 1) {
                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
            }

            
            BigInteger a = 0;
            BigInteger omega2;
            while (true) {
                omega2 = (a * a + p - n) % p;
                if (ls(omega2) == p - 1) {
                    break;
                }
                a += 1;
            }

            
            BigInteger finalOmega = omega2;
            Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) {
                return new Tuple<BigInteger, BigInteger>(
                    (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p,
                    (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p
                );
            }

            
            Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0);
            Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1);
            BigInteger nn = ((p + 1) >> 1) % p;
            while (nn > 0) {
                if ((nn & 1) == 1) {
                    r = mul(r, s);
                }
                s = mul(s, s);
                nn >>= 1;
            }

            
            if (r.Item2 != 0) {
                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
            }

            
            if (r.Item1 * r.Item1 % p != n) {
                return new Tuple<BigInteger, BigInteger, bool>(0, 0, false);
            }

            
            return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true);
        }

        static void Main(string[] args) {
            Console.WriteLine(C("10", "13"));
            Console.WriteLine(C("56", "101"));
            Console.WriteLine(C("8218", "10007"));
            Console.WriteLine(C("8219", "10007"));
            Console.WriteLine(C("331575", "1000003"));
            Console.WriteLine(C("665165880", "1000000007"));
            Console.WriteLine(C("881398088036", "1000000000039"));
            Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""));
        }
    }
}
Task: Partition an integer x into n primes



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

public static class Rosetta
{
    static void Main()
    {
        foreach ((int x, int n) in new [] {
            (99809, 1),
            (18, 2),
            (19, 3),
            (20, 4),
            (2017, 24),
            (22699, 1),
            (22699, 2),
            (22699, 3),
            (22699, 4),
            (40355, 3)
        }) {
            Console.WriteLine(Partition(x, n));
        }
    }

    public static string Partition(int x, int n) {
        if (x < 1 || n < 1) throw new ArgumentOutOfRangeException("Parameters must be positive.");
        string header = $"{x} with {n} {(n == 1 ? "prime" : "primes")}: ";
        int[] primes = SievePrimes(x).ToArray();
        if (primes.Length < n) return header + "not enough primes";
        int[] solution = CombinationsOf(n, primes).FirstOrDefault(c => c.Sum() == x);
        return header + (solution == null ? "not possible" : string.Join("+", solution);
    }

    static IEnumerable<int> SievePrimes(int bound) {
        if (bound < 2) yield break;
        yield return 2;

        BitArray composite = new BitArray((bound - 1) / 2);
        int limit = ((int)(Math.Sqrt(bound)) - 1) / 2;
        for (int i = 0; i < limit; i++) {
            if (composite[i]) continue;
            int prime = 2 * i + 3;
            yield return prime;
            for (int j = (prime * prime - 2) / 2; j < composite.Count; j += prime) composite[j] = true;
        }
        for (int i = limit; i < composite.Count; i++) {
            if (!composite[i]) yield return 2 * i + 3;
        }
    }

    static IEnumerable<int[]> CombinationsOf(int count, int[] input) {
        T[] result = new T[count];
        foreach (int[] indices in Combinations(input.Length, count)) {
            for (int i = 0; i < count; i++) result[i] = input[indices[i]];
            yield return result;
        }
    }

    static IEnumerable<int[]> Combinations(int n, int k) {
        var result = new int[k];
        var stack = new Stack<int>();
        stack.Push(0);
        while (stack.Count > 0) {
            int index = stack.Count - 1;
            int value = stack.Pop();
            while (value < n) {
                result[index++] = value++;
                stack.Push(value);
                if (index == k) {
                    yield return result;
                    break;
                }
            }
        }
    }

}
Task: Bilinear interpolation



C#: using System;
using System.Drawing;

namespace BilinearInterpolation {
    class Program {
        private static float Lerp(float s, float e, float t) {
            return s + (e - s) * t;
        }

        private static float Blerp(float c00, float c10, float c01, float c11, float tx, float ty) {
            return Lerp(Lerp(c00, c10, tx), Lerp(c01, c11, tx), ty);
        }

        private static Image Scale(Bitmap self, float scaleX, float scaleY) {
            int newWidth = (int)(self.Width * scaleX);
            int newHeight = (int)(self.Height * scaleY);
            Bitmap newImage = new Bitmap(newWidth, newHeight, self.PixelFormat);

            for (int x = 0; x < newWidth; x++) {
                for (int y = 0; y < newHeight; y++) {
                    float gx = ((float)x) / newWidth * (self.Width - 1);
                    float gy = ((float)y) / newHeight * (self.Height - 1);
                    int gxi = (int)gx;
                    int gyi = (int)gy;
                    Color c00 = self.GetPixel(gxi, gyi);
                    Color c10 = self.GetPixel(gxi + 1, gyi);
                    Color c01 = self.GetPixel(gxi, gyi + 1);
                    Color c11 = self.GetPixel(gxi + 1, gyi + 1);

                    int red = (int)Blerp(c00.R, c10.R, c01.R, c11.R, gx - gxi, gy - gyi);
                    int green = (int)Blerp(c00.G, c10.G, c01.G, c11.G, gx - gxi, gy - gyi);
                    int blue = (int)Blerp(c00.B, c10.B, c01.B, c11.B, gx - gxi, gy - gyi);
                    Color rgb = Color.FromArgb(red, green, blue);
                    newImage.SetPixel(x, y, rgb);
                }
            }

            return newImage;
        }

        static void Main(string[] args) {
            Image newImage = Image.FromFile("Lenna100.jpg");
            if (newImage is Bitmap oi) {
                Image result = Scale(oi, 1.6f, 1.6f);
                result.Save("Lenna100_larger.jpg");
            } else {
                Console.WriteLine("Could not open the source file.");
            }
        }
    }
}
Task: Vector



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

namespace RosettaVectors
{
    public class Vector
    {
        public double[] store;
        public Vector(IEnumerable<double> init)
        {
            store = init.ToArray();
        }
        public Vector(double x, double y)
        {
            store = new double[] { x, y };
        }
        static public Vector operator+(Vector v1, Vector v2)
        {
            return new Vector(v1.store.Zip(v2.store, (a, b) => a + b));
        }
        static public Vector operator -(Vector v1, Vector v2)
        {
            return new Vector(v1.store.Zip(v2.store, (a, b) => a - b));
        }
        static public Vector operator *(Vector v1, double scalar)
        {
            return new Vector(v1.store.Select(x => x * scalar));
        }
        static public Vector operator /(Vector v1, double scalar)
        {
            return new Vector(v1.store.Select(x => x / scalar));
        }
        public override string ToString()
        {
            return string.Format("[{0}]", string.Join(",", store));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var v1 = new Vector(5, 7);
            var v2 = new Vector(2, 3);
            Console.WriteLine(v1 + v2);
            Console.WriteLine(v1 - v2);
            Console.WriteLine(v1 * 11);
            Console.WriteLine(v1 / 2);
            
            var lostVector = new Vector(new double[] { 4, 8, 15, 16, 23, 42 });
            Console.WriteLine(lostVector * 7);
            Console.ReadLine();
        }
    }
}
Task: Prime conspiracy



C#: using System;

namespace PrimeConspiracy {
    class Program {
        static void Main(string[] args) {
            const int limit = 1_000_000;
            const int sieveLimit = 15_500_000;

            int[,] buckets = new int[10, 10];
            int prevDigit = 2;
            bool[] notPrime = Sieve(sieveLimit);

            for (int n = 3, primeCount = 1; primeCount < limit; n++) {
                if (notPrime[n]) continue;

                int digit = n % 10;
                buckets[prevDigit, digit]++;
                prevDigit = digit;
                primeCount++;
            }

            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    if (buckets[i, j] != 0) {
                        Console.WriteLine("{0} -> {1}  count: {2,5:d}  frequency : {3,6:0.00%}", i, j, buckets[i, j], 1.0 * buckets[i, j] / limit);
                    }
                }
            }
        }

        public static bool[] Sieve(int limit) {
            bool[] composite = new bool[limit];
            composite[0] = composite[1] = true;

            int max = (int)Math.Sqrt(limit);
            for (int n = 2; n <= max; n++) {
                if (!composite[n]) {
                    for (int k = n * n; k < limit; k += n) {
                        composite[k] = true;
                    }
                }
            }

            return composite;
        }
    }
}
Task: Minimum positive multiple in base 10 using only 0 and 1



C#: using System;
using System.Collections.Generic;
using static System.Console;
 
class Program {
 
  static string B10(int n) {
    int[] pow = new int[n + 1], val = new int[29];
    for (int count = 0, ten = 1, x = 1; x <= n; x++) {
      val[x] = ten;
      for (int j = 0, t; j <= n; j++)
        if (pow[j] != 0 && pow[j] != x && pow[t = (j + ten) % n] == 0)
          pow[t] = x;
      if (pow[ten] == 0) pow[ten] = x;
      ten = (10 * ten) % n;
      if (pow[0] != 0) {
        x = n;
        string s = ""; 
        while (x != 0) {
          int p = pow[x % n];
          if (count > p) s += new string('0', count - p);
          count = p - 1;
          s += "1";
          x = (n + x - val[p]) % n;
        }
        if (count > 0) s += new string('0', count);
        return s;
      }
    } 
    return "1";
  }
 
  static void Main(string[] args) {
    string fmt = "{0,4} * {1,24} = {2,-28}\n";
    int[] m = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
      95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
      297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878 };
    string[] r = new string[m.Length]; 
    WriteLine(fmt + new string('-', 62), "n", "multiplier", "B10");
    var sw = System.Diagnostics.Stopwatch.StartNew();
    for (int i = 0; i < m.Length; i++) r[i] = B10(m[i]);
    sw.Stop();
    for (int i = 0; i < m.Length; i++) Write(fmt, m[i], decimal.Parse(r[i]) / m[i], r[i]);
    Write("\nTook {0}ms", sw.Elapsed.TotalMilliseconds);
  }
}
Task: Weird numbers



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WeirdNumbers {
    class Program {
        static List<int> Divisors(int n) {
            List<int> divs = new List<int> { 1 };
            List<int> divs2 = new List<int>();

            for (int i = 2; i * i <= n; i++) {
                if (n % i == 0) {
                    int j = n / i;
                    divs.Add(i);
                    if (i != j) {
                        divs2.Add(j);
                    }
                }
            }

            divs.Reverse();
            divs2.AddRange(divs);
            return divs2;
        }

        static bool Abundant(int n, List<int> divs) {
            return divs.Sum() > n;
        }

        static bool Semiperfect(int n, List<int> divs) {
            if (divs.Count > 0) {
                var h = divs[0];
                var t = divs.Skip(1).ToList();
                if (n < h) {
                    return Semiperfect(n, t);
                } else {
                    return n == h
                        || Semiperfect(n - h, t)
                        || Semiperfect(n, t);
                }
            } else {
                return false;
            }
        }

        static List<bool> Sieve(int limit) {
            
            
            bool[] w = new bool[limit];
            for (int i = 2; i < limit; i += 2) {
                if (w[i]) continue;
                var divs = Divisors(i);
                if (!Abundant(i, divs)) {
                    w[i] = true;
                } else if (Semiperfect(i, divs)) {
                    for (int j = i; j < limit; j += i) {
                        w[j] = true;
                    }
                }
            }
            return w.ToList();
        }

        static void Main() {
            var w = Sieve(17_000);
            int count = 0;
            int max = 25;
            Console.WriteLine("The first 25 weird numbers:");
            for (int n = 2; count < max; n += 2) {
                if (!w[n]) {
                    Console.Write("{0} ", n);
                    count++;
                }
            }
            Console.WriteLine();
        }
    }
}