WeixiangYan/CodeTransOcean huggingface dataset:
Task: Resistance network calculator







Python: from fractions import Fraction

def gauss(m):
	n, p = len(m), len(m[0])
	for i in range(n):
		k = max(range(i, n), key = lambda x: abs(m[x][i]))
		m[i], m[k] = m[k], m[i]
		t = 1 / m[i][i]
		for j in range(i + 1, p): m[i][j] *= t
		for j in range(i + 1, n):
			t = m[j][i]
			for k in range(i + 1, p): m[j][k] -= t * m[i][k]
	for i in range(n - 1, -1, -1):
		for j in range(i): m[j][-1] -= m[j][i] * m[i][-1]
	return [row[-1] for row in m]

def network(n,k0,k1,s):
	m = [[0] * (n+1) for i in range(n)]
	resistors = s.split('|')
	for resistor in resistors:
		a,b,r = resistor.split(' ')
		a,b,r = int(a), int(b), Fraction(1,int(r))
		m[a][a] += r
		m[b][b] += r
		if a > 0: m[a][b] -= r
		if b > 0: m[b][a] -= r
	m[k0][k0] = Fraction(1, 1)
	m[k1][-1] = Fraction(1, 1)
	return gauss(m)[k1]

assert 10             == network(7,0,1,"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8")
assert 3/2            == network(3*3,0,3*3-1,"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1")
assert Fraction(13,7) == network(4*4,0,4*4-1,"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1")
assert 180            == network(4,0,3,"0 1 150|0 2 50|1 3 300|2 3 250")
Task: Resistance calculator







Python: import strutils, strformat

type
  Node = ref object
    kind: char  
    resistance: float
    voltage: float
    a: Node
    b: Node

proc res(node: Node): float =
  if node.kind == '+': return node.a.res + node.b.res
  if node.kind == '*': return 1 / (1 / node.a.res + 1 / node.b.res)
  node.resistance

proc current(node: Node): float = node.voltage / node.res
proc effect (node: Node): float = node.current * node.voltage

proc report(node: Node, level: string = "") =
  echo fmt"{node.res:8.3f} {node.voltage:8.3f} {node.current:8.3f} {node.effect:8.3f}  {level}{node.kind}"
  if node.kind in "+*":
    node.a.report level & "| "
    node.b.report level & "| "

proc setVoltage(node: Node, voltage: float) =
  node.voltage = voltage
  if node.kind == '+':
    let ra = node.a.res
    let rb = node.b.res
    node.a.setVoltage ra / (ra+rb) * voltage
    node.b.setVoltage rb / (ra+rb) * voltage
  if node.kind == '*':
    node.a.setVoltage voltage
    node.b.setVoltage voltage

proc build(tokens: seq[string]): Node =
  var stack: seq[Node]
  for token in tokens:
    stack.add if token == "+": Node(kind: '+', a: stack.pop, b: stack.pop)
              elif token == "*": Node(kind: '*', a: stack.pop, b: stack.pop)
              else: Node(kind: 'r', resistance: parseFloat(token))
  stack.pop

proc calculate(voltage: float, tokens: seq[string]): Node =
  echo ""
  echo "     Ohm     Volt   Ampere     Watt  Network tree"
  let node = build tokens
  node.setVoltage voltage
  node.report
  node
Task: Solve equations with substitution method







Python: 

firstEquation  = [ 3, 1, -1]
secondEquation = [ 2,-3,-19]

def getCrossingPoint(firstEquation, secondEquation):
    x1 = firstEquation[0]
    y1 = firstEquation[1]
    r1 = firstEquation[2]
    x2 = secondEquation[0]
    y2 = secondEquation[1]
    r2 = secondEquation[2]
    temp = []
    temp.append( x1)
    temp.append(-y1)
    temp.append( r1)
    resultY = ((temp[0]*r2) - (x2*temp[2])) / ((x2*temp[1]) + (temp[0]*y2)) 
    resultX = (r1 - (y1*resultY)) / x1 
    print("x = ", resultX)
    print("y = ", resultY)


if __name__ == "__main__":
    getCrossingPoint(firstEquation, secondEquation)
Task: Price list behind API







Python: import random


price_list_size = random.choice(range(99_000, 101_000))
price_list = random.choices(range(100_000), k=price_list_size)

delta_price = 1     


def get_prange_count(startp, endp):
    return len([r for r in price_list if startp <= r <= endp])

def get_max_price():
    return max(price_list)


def get_5k(mn=0, mx=get_max_price(), num=5_000):
    "Binary search for num items between mn and mx, adjusting mx"
    count = get_prange_count(mn, mx)
    delta_mx = (mx - mn) / 2
    while count != num and delta_mx >= delta_price / 2:
        mx += -delta_mx if count > num else +delta_mx
        mx = mx // 1    
        count, delta_mx = get_prange_count(mn, mx), delta_mx / 2
    return mx, count

def get_all_5k(mn=0, mx=get_max_price(), num=5_000):
    "Get all non-overlapping ranges"
    partmax, partcount = get_5k(mn, mx, num)
    result = [(mn, partmax, partcount)]
    while partmax < mx:
        partmin = partmax + delta_price 
        partmax, partcount = get_5k(partmin, mx, num)
        assert partcount > 0, \
            f"price_list from {partmin} with too many of the same price"
        result.append((partmin, partmax, partcount))
    return result

if __name__ == '__main__':
    print(f"Using {price_list_size} random prices from 0 to {get_max_price()}")
    result = get_all_5k()
    print(f"Splits into {len(result)} bins of approx 5000 elements")
    for mn, mx, count in result:
        print(f"  From {mn:8.1f} ... {mx:8.1f} with {count} items.")

    if len(price_list) != sum(count for mn, mx, count in result):
        print("\nWhoops! Some items missing:")
Task: Run as a daemon or service







Python: 
import posix
import os
import sys

pid = posix.fork()
if pid != 0:
    print("Child process detached with pid %s" % pid)
    sys.exit(0)

old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr

sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout

old_stdin.close()
old_stdout.close()
old_stderr.close()

posix.setsid()

import time
t = time.time()
while time.time() < t + 10:
    print("timer running, %s seconds" % str(time.time() - t))
    time.sleep(1)
Task: Vampire number



C#: using System;

namespace RosettaVampireNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j, n;
            ulong x;
            var f = new ulong[16];
            var bigs = new ulong[] { 16758243290880UL, 24959017348650UL, 14593825548650UL, 0 };
            ulong[] tens = new ulong[20];
            tens[0] = 1;
            for (i = 1; i < 20; i++)
                tens[i] = tens[i - 1] * 10;
            
            for (x = 1, n = 0; n < 25; x++)
            {
                if ((j = fangs(x, f, tens)) == 0) continue;
                Console.Write(++n + ": ");
                show_fangs(x, f, j);
            }

            Console.WriteLine();
            for (i = 0; bigs[i] > 0 ; i++)
            {
                if ((j = fangs(bigs[i], f, tens)) > 0)
                    show_fangs(bigs[i], f, j);
                else
                    Console.WriteLine(bigs[i] + " is not vampiric.");
            }
            Console.ReadLine();
        }

        private static void show_fangs(ulong x, ulong[] f, int cnt)
        {
            Console.Write(x); 
            int i;
            for (i = 0; i < cnt; i++)
                Console.Write(" = " + f[i] + " * " + (x / f[i]));
            Console.WriteLine();
        }

        private static int fangs(ulong x, ulong[] f, ulong[] tens)
        {
            int n = 0;
            int nd = ndigits(x);
            if ((nd & 1) > 0) return 0;
            nd /= 2;

            ulong lo, hi;
            lo = Math.Max(tens[nd - 1], (x + tens[nd] - 2) / (tens[nd] - 1));
            hi = Math.Min(x / lo, (ulong) Math.Sqrt(x));

            ulong a, b, t = dtally(x);
            for (a = lo; a <= hi; a++)
            {
                b = x / a;
                if (a * b == x && ((a % 10) > 0 || (b % 10) > 0) && t == dtally(a) + dtally(b))
                    f[n++] = a;
            }

            return n;
        }

        private static ulong dtally(ulong x)
        {
            ulong t = 0;
            while (x > 0)
            {
                t += 1UL << (int)((x % 10) * 6);
                x /= 10;
            }

            return t;
        }

        private static int ndigits(ulong x)
        {
            int n = 0;
            while (x > 0)
            {
                n++;
                x /= 10;
            }
            return n;
        }
    }
}
Task: Nonoblock



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

public static class Nonoblock
{
    public static void Main() {
        Positions(5, 2,1);
        Positions(5);
        Positions(10, 8);
        Positions(15, 2,3,2,3);
        Positions(5, 2,3);
    }

    public static void Positions(int cells, params int[] blocks) {
        if (cells < 0 || blocks == null || blocks.Any(b => b < 1)) throw new ArgumentOutOfRangeException();
        Console.WriteLine($"{cells} cells with [{string.Join(", ", blocks)}]");
        if (blocks.Sum() + blocks.Length - 1 > cells) {
            Console.WriteLine("No solution");
            return;
        }
        var spaces = new int[blocks.Length + 1];
        int total = -1;
        for (int i = 0; i < blocks.Length; i++) {
            total += blocks[i] + 1;
            spaces[i+1] = total;
        }
        spaces[spaces.Length - 1] = cells - 1;
        var sb = new StringBuilder(string.Join(".", blocks.Select(b => new string('#', b))).PadRight(cells, '.'));
        Iterate(sb, spaces, spaces.Length - 1, 0);
        Console.WriteLine();
    }

    private static void Iterate(StringBuilder output, int[] spaces, int index, int offset) {
        Console.WriteLine(output.ToString());
        if (index <= 0) return;
        int count = 0;
        while (output[spaces[index] - offset] != '#') {
            count++;
            output.Remove(spaces[index], 1);
            output.Insert(spaces[index-1], '.');
            spaces[index-1]++;
            Iterate(output, spaces, index - 1, 1);
        }
        if (offset == 0) return;
        spaces[index-1] -= count;
        output.Remove(spaces[index-1], count);
        output.Insert(spaces[index] - count, ".", count);
    }

}
Task: Eban numbers



C#: using System;

namespace EbanNumbers {
    struct Interval {
        public int start, end;
        public bool print;

        public Interval(int start, int end, bool print) {
            this.start = start;
            this.end = end;
            this.print = print;
        }
    }

    class Program {
        static void Main() {
            Interval[] intervals = {
                new Interval(2, 1_000, true),
                new Interval(1_000, 4_000, true),
                new Interval(2, 10_000, false),
                new Interval(2, 100_000, false),
                new Interval(2, 1_000_000, false),
                new Interval(2, 10_000_000, false),
                new Interval(2, 100_000_000, false),
                new Interval(2, 1_000_000_000, false),
            };
            foreach (var intv in intervals) {
                if (intv.start == 2) {
                    Console.WriteLine("eban numbers up to and including {0}:", intv.end);
                } else {
                    Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.end);
                }

                int count = 0;
                for (int i = intv.start; i <= intv.end; i += 2) {
                    int b = i / 1_000_000_000;
                    int r = i % 1_000_000_000;
                    int m = r / 1_000_000;
                    r = i % 1_000_000;
                    int t = r / 1_000;
                    r %= 1_000;
                    if (m >= 30 && m <= 66) m %= 10;
                    if (t >= 30 && t <= 66) t %= 10;
                    if (r >= 30 && r <= 66) r %= 10;
                    if (b == 0 || b == 2 || b == 4 || b == 6) {
                        if (m == 0 || m == 2 || m == 4 || m == 6) {
                            if (t == 0 || t == 2 || t == 4 || t == 6) {
                                if (r == 0 || r == 2 || r == 4 || r == 6) {
                                    if (intv.print) Console.Write("{0} ", i);
                                    count++;
                                }
                            }
                        }
                    }
                }
                if (intv.print) {
                    Console.WriteLine();
                }
                Console.WriteLine("count = {0}\n", count);
            }
        }
    }
}
Task: Sailors, coconuts and a monkey problem



C#: class Test
{
    static bool valid(int n, int nuts)
    {
        for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
        {
            if (nuts % n != 1)
            {
                return false;
            }                
        }
            
        return nuts != 0 && (nuts % n == 0);
    }

    static void Main(string[] args)
    {
        int x = 0;
        for (int n = 2; n < 10; n++)
        {
            while (!valid(n, x))
                x++;
            System.Console.WriteLine(n + ": " + x);
        }
    }
}
Task: Active Directory_Connect



C#: 
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
Task: Knapsack problem_Bounded



C#: using System;  
class program
{
    static void Main()
    {
        knapSack(40);
        var sw = System.Diagnostics.Stopwatch.StartNew();
        Console.Write(knapSack(400) + "\n" + sw.Elapsed);  
        Console.Read();
    }

    static string knapSack(uint w1)
    {
        init(); change();
        uint n = (uint)w.Length; var K = new uint[n + 1, w1 + 1];
        for (uint vi, wi, w0, x, i = 0; i < n; i++)
            for (vi = v[i], wi = w[i], w0 = 1; w0 <= w1; w0++)
            {
                x = K[i, w0];
                if (wi <= w0) x = max(vi + K[i, w0 - wi], x);
                K[i + 1, w0] = x;
            }
        string str = "";
        for (uint v1 = K[n, w1]; v1 > 0; n--)
            if (v1 != K[n - 1, w1])
            {
                v1 -= v[n - 1]; w1 -= w[n - 1]; str += items[n - 1] + "\n";
            }
        return str;
    }

    static uint max(uint a, uint b) { return a > b ? a : b; }

    static byte[] w, v; static string[] items;

    static byte[] p = { 1, 1, 2, 2, 2, 3, 3, 3, 1, 3, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2 };

    static void init()
    {
        w = new byte[] { 9, 13, 153, 50, 15, 68, 27, 39, 23, 52, 11,
                          32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30 };

        v = new byte[] { 150, 35, 200, 60, 60, 45, 60, 40, 30, 10, 70,
                          30, 15, 10, 40, 70, 75, 80, 20, 12, 50, 10 };

        items = new string[] {"map","compass","water","sandwich","glucose","tin",
                              "banana","apple","cheese","beer","suntan cream",
                              "camera","T-shirt","trousers","umbrella",
                              "waterproof trousers","waterproof overclothes",
                              "note-case","sunglasses","towel","socks","book"};
    }

    static void change()
    {
        int n = w.Length, s = 0, i, j, k; byte xi;
        for (i = 0; i < n; i++) s += p[i];
        {
            byte[] x = new byte[s];
            for (k = i = 0; i < n; i++)
                for (xi = w[i], j = p[i]; j > 0; j--) x[k++] = xi;
            w = x;
        }
        {
            byte[] x = new byte[s];
            for (k = i = 0; i < n; i++)
                for (xi = v[i], j = p[i]; j > 0; j--) x[k++] = xi;
            v = x;
        }
        string[] pItems = new string[s]; string itemI;
        for (k = i = 0; i < n; i++)
            for (itemI = items[i], j = p[i]; j > 0; j--) pItems[k++] = itemI;
        items = pItems;
    }
}
Task: I before E except after C



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

namespace IBeforeE {
    class Program {
        static bool IsOppPlausibleWord(string word) {
            if (!word.Contains("c") && word.Contains("ei")) {
                return true;
            }
            if (word.Contains("cie")) {
                return true;
            }
            return false;
        }

        static bool IsPlausibleWord(string word) {
            if (!word.Contains("c") && word.Contains("ie")) {
                return true;
            }
            if (word.Contains("cei")) {
                return true;
            }
            return false;
        }

        static bool IsPlausibleRule(string filename) {
            IEnumerable<string> wordSource = File.ReadLines(filename);
            int trueCount = 0;
            int falseCount = 0;

            foreach (string word in wordSource) {
                if (IsPlausibleWord(word)) {
                    trueCount++;
                }
                else if (IsOppPlausibleWord(word)) {
                    falseCount++;
                }
            }

            Console.WriteLine("Plausible count: {0}", trueCount);
            Console.WriteLine("Implausible count: {0}", falseCount);
            return trueCount > 2 * falseCount;
        }

        static void Main(string[] args) {
            if (IsPlausibleRule("unixdict.txt")) {
                Console.WriteLine("Rule is plausible.");
            }
            else {
                Console.WriteLine("Rule is not plausible.");
            }
        }
    }
}
Task: Respond to an unknown method call



C#: using System;
using System.Dynamic;

class Example : DynamicObject
{
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        result = null;

        Console.WriteLine("This is {0}.", binder.Name);
        return true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        dynamic ex = new Example();

        ex.Foo();
        ex.Bar();
    }
}
Task: Snake and ladder



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

namespace SnakeAndLadder {
    class Program {
        private static Dictionary<int, int> snl = new Dictionary<int, int>() {
            {4, 14},
            {9, 31},
            {17, 7},
            {20, 38},
            {28, 84},
            {40, 59},
            {51, 67},
            {54, 34},
            {62, 19},
            {63, 81},
            {64, 60},
            {71, 91},
            {87, 24},
            {93, 73},
            {95, 75},
            {99, 78},
        };
        private static Random rand = new Random();
        private const bool sixesThrowAgain = true;

        static int Turn(int player, int square) {
            while (true) {
                int roll = rand.Next(1, 6);
                Console.Write("Player {0}, on square {1}, rolls a {2}", player, square, roll);
                if (square + roll > 100) {
                    Console.WriteLine(" but cannot move.");
                } else {
                    square += roll;
                    Console.WriteLine(" and moves to square {0}", square);
                    if (square == 100) return 100;
                    int next = square;
                    if (snl.ContainsKey(square)) {
                        next = snl[square];
                    }
                    if (square < next) {
                        Console.WriteLine("Yay! Landed on a ladder. Climb up to {0}.", next);
                        if (next == 100) return 100;
                        square = next;
                    } else if (square > next) {
                        Console.WriteLine("Oops! Landed on a snake. Slither down to {0}.", next);
                    }
                }
                if (roll < 6 || !sixesThrowAgain) return square;
                Console.WriteLine("Rolled a 6 so roll again.");
            }
        }

        static void Main(string[] args) {
            
            int[] players = { 1, 1, 1 };
            while (true) {
                for (int i = 0; i < players.Length; i++) {
                    int ns = Turn(i + 1, players[i]);
                    if (ns == 100) {
                        Console.WriteLine("Player {0} wins!", i + 1);
                        return;
                    }
                    players[i] = ns;
                    Console.WriteLine();
                }
            }
        }
    }
}
Task: Farey sequence



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

public static class FareySequence
{
    public static void Main() {
        for (int i = 1; i <= 11; i++) {
            Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}")));
        }
        for (int i = 100; i <= 1000; i+=100) {
            Console.WriteLine($"F{i} has {Generate(i).Count()} terms.");
        }
    }

    public static IEnumerable<(int num, int den)> Generate(int i) {
        var comparer = Comparer<(int n, int d)>.Create((a, b) => (a.n * b.d).CompareTo(a.d * b.n));
        var seq = new SortedSet<(int n, int d)>(comparer);
        for (int d = 1; d <= i; d++) {
            for (int n = 0; n <= d; n++) {
                seq.Add((n, d));
            }
        }
        return seq;
    }
}
Task: Implicit type conversion



C#: byte aByte = 2;
short aShort = aByte;
int anInt = aShort;
long aLong = anInt;

float aFloat = 1.2f;
double aDouble = aFloat;

BigInteger b = 5;
Complex c = 2.5;
Task: Taxicab numbers



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

namespace TaxicabNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            IDictionary<long, IList<Tuple<int, int>>> taxicabNumbers = GetTaxicabNumbers(2006);
            PrintTaxicabNumbers(taxicabNumbers);
            Console.ReadKey();
        }

        private static IDictionary<long, IList<Tuple<int, int>>> GetTaxicabNumbers(int length)
        {
            SortedList<long, IList<Tuple<int, int>>> sumsOfTwoCubes = new SortedList<long, IList<Tuple<int, int>>>();

            for (int i = 1; i < int.MaxValue; i++)
            {
                for (int j = 1; j < int.MaxValue; j++)
                {
                    long sum = (long)(Math.Pow((double)i, 3) + Math.Pow((double)j, 3));

                    if (!sumsOfTwoCubes.ContainsKey(sum))
                    {
                        sumsOfTwoCubes.Add(sum, new List<Tuple<int, int>>());
                    }

                    sumsOfTwoCubes[sum].Add(new Tuple<int, int>(i, j));

                    if (j >= i)
                    {
                        break;
                    }
                }

                
                if (sumsOfTwoCubes.Count(t => t.Value.Count >= 2) >= length * 1.1)
                {
                    break;
                }
            }

            IDictionary<long, IList<Tuple<int, int>>> values = (from t in sumsOfTwoCubes where t.Value.Count >= 2 select t)
                .Take(2006)
                .ToDictionary(u => u.Key, u => u.Value);

            return values;
        }

        private static void PrintTaxicabNumbers(IDictionary<long, IList<Tuple<int, int>>> values)
        {
            int i = 1;

            foreach (long taxicabNumber in values.Keys)
            {
                StringBuilder output = new StringBuilder().AppendFormat("{0,10}\t{1,4}", i, taxicabNumber);

                foreach (Tuple<int, int> numbers in values[taxicabNumber])
                {
                    output.AppendFormat("\t= {0}^3 + {1}^3", numbers.Item1, numbers.Item2);
                }

                if (i <= 25 || (i >= 2000 && i <= 2006))
                {
                    Console.WriteLine(output.ToString());
                }

                i++;
            }
        }
    }
}