WeixiangYan/CodeTransOcean huggingface dataset:
Task: First power of 2 that has leading decimal digits of 12








VB: Module Module1

    Function Func(ByVal l As Integer, ByVal n As Integer) As Long
        Dim res As Long = 0, f As Long = 1
        Dim lf As Double = Math.Log10(2)
        Dim i As Integer = l

        While i > 10
            f *= 10
            i /= 10
        End While

        While n > 0
            res += 1

            If CInt((f * Math.Pow(10, res * lf Mod 1))) = l Then
                n -= 1
            End If
        End While

        Return res
    End Function

    Sub Main()
        Dim values = {Tuple.Create(12, 1), Tuple.Create(12, 2), Tuple.Create(123, 45), Tuple.Create(123, 12345), Tuple.Create(123, 678910), Tuple.Create(99, 1)}
        For Each pair In values
            Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", pair.Item1, pair.Item2, Func(pair.Item1, pair.Item2))
        Next
    End Sub

End Module
Task: Sattolo cycle



C#: private static readonly Random Rand = new Random();

void sattoloCycle<T>(IList<T> items) {
    for (var i = items.Count; i-- > 1;) {
        int j = Rand.Next(i);
        var tmp = items[i];
        items[i] = items[j];
        items[j] = tmp;
    }
}
Task: Twin primes



C#: using System;

class Program {

    static uint[] res = new uint[10];
    static uint ri = 1, p = 10, count = 0;

    static void TabulateTwinPrimes(uint bound) {
        if (bound < 5) return; count++;
        uint cl = (bound - 1) >> 1, i = 1, j,
             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;
        var comp = new bool[cl]; bool lp;
        for (j = 3; j < cl; j += 3) comp[j] = true;
        while (i < limit) {
            if (lp = !comp[i]) {
                uint pr = (i << 1) + 3;
                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
                    comp[j] = true;
            }
            if (!comp[++i]) {
                uint pr = (i << 1) + 3;
                if (lp) {
                    if (pr > p) {
                        res[ri++] = count;
                        p *= 10;
                    }
                    count++;
                    i++;
                }
                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
                    comp[j] = true; 
            }
        }
        cl--;
        while (i < cl) {
            lp = !comp[i++];
            if (!comp[i] && lp) {
                if ((i++ << 1) + 3 > p) {
                    res[ri++] = count;
                    p *= 10;
                }
                count++;
            }
        }
        res[ri] = count;
    }

    static void Main(string[] args) {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        string fmt = "{0,9:n0} twin primes below {1,-13:n0}";
        TabulateTwinPrimes(1_000_000_000);
        sw.Stop();
        p = 1;
        for (var j = 1; j <= ri; j++)
            Console.WriteLine(fmt, res[j], p *= 10);
        Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
    }
}
Task: Brazilian numbers



C#: using System;
class Program {
 
  static bool sameDigits(int n, int b) {
    int f = n % b;
    while ((n /= b) > 0) if (n % b != f) return false;
    return true;
  }
 
  static bool isBrazilian(int n) {
    if (n < 7) return false;
    if (n % 2 == 0) return true;
    for (int b = 2; b < n - 1; b++) if (sameDigits(n, b)) return true;
    return false;
  }
 
  static bool isPrime(int n) {
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    int d = 5;
    while (d * d <= n) {
      if (n % d == 0) return false; d += 2;
      if (n % d == 0) return false; d += 4;
    }
    return true;
  }
 
  static void Main(string[] args) {
    foreach (string kind in ",odd ,prime ".Split(',')) {
      bool quiet = false; int BigLim = 99999, limit = 20;
      Console.WriteLine("First {0} {1}Brazilian numbers:", limit, kind);
      int c = 0, n = 7;
      while (c < BigLim) {
        if (isBrazilian(n)) {
          if (!quiet) Console.Write("{0:n0} ", n);
          if (++c == limit) { Console.Write("\n\n"); quiet = true; }
        }
        if (quiet && kind != "") continue;
        switch (kind) {
          case "": n++; break;
          case "odd ": n += 2; break;
          case "prime ":
            while (true) {
              n += 2;
              if (isPrime(n)) break;
            } break;
        }
      }
      if (kind == "") Console.WriteLine("The {0:n0}th Brazilian number is: {1:n0}\n", BigLim + 1, n);
    }
  }
}
Task: Recaman's sequence



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

namespace RecamanSequence {
    class Program {
        static void Main(string[] args) {
            List<int> a = new List<int>() { 0 };
            HashSet<int> used = new HashSet<int>() { 0 };
            HashSet<int> used1000 = new HashSet<int>() { 0 };
            bool foundDup = false;
            int n = 1;
            while (n <= 15 || !foundDup || used1000.Count < 1001) {
                int next = a[n - 1] - n;
                if (next < 1 || used.Contains(next)) {
                    next += 2 * n;
                }
                bool alreadyUsed = used.Contains(next);
                a.Add(next);
                if (!alreadyUsed) {
                    used.Add(next);
                    if (0 <= next && next <= 1000) {
                        used1000.Add(next);
                    }
                }
                if (n == 14) {
                    Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
                }
                if (!foundDup && alreadyUsed) {
                    Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
                    foundDup = true;
                }
                if (used1000.Count == 1001) {
                    Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
                }
                n++;
            }
        }
    }
}
Task: Y combinator



C#: using System;

static class YCombinator<T, TResult>
{
    
    private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);

    public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
        f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}

static class Program
{
    static void Main()
    {
        var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
        var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));

        Console.WriteLine(fac(10));
        Console.WriteLine(fib(10));
    }
}
Task: Casting out nines



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

namespace CastingOutNines {
    public static class Helper {
        public static string AsString<T>(this IEnumerable<T> e) {
            var it = e.GetEnumerator();

            StringBuilder builder = new StringBuilder();
            builder.Append("[");

            if (it.MoveNext()) {
                builder.Append(it.Current);
            }
            while (it.MoveNext()) {
                builder.Append(", ");
                builder.Append(it.Current);
            }

            builder.Append("]");
            return builder.ToString();
        }
    }

    class Program {
        static List<int> CastOut(int @base, int start, int end) {
            int[] ran = Enumerable
                .Range(0, @base - 1)
                .Where(a => a % (@base - 1) == (a * a) % (@base - 1))
                .ToArray();
            int x = start / (@base - 1);

            List<int> result = new List<int>();
            while (true) {
                foreach (int n in ran) {
                    int k = (@base - 1) * x + n;
                    if (k < start) {
                        continue;
                    }
                    if (k > end) {
                        return result;
                    }
                    result.Add(k);
                }
                x++;
            }
        }

        static void Main() {
            Console.WriteLine(CastOut(16, 1, 255).AsString());
            Console.WriteLine(CastOut(10, 1, 99).AsString());
            Console.WriteLine(CastOut(17, 1, 288).AsString());
        }
    }
}
Task: Lah numbers



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

namespace LahNumbers {
    class Program {
        static BigInteger Factorial(BigInteger n) {
            if (n == 0) return 1;
            BigInteger res = 1;
            while (n > 0) {
                res *= n--;
            }
            return res;
        }

        static BigInteger Lah(BigInteger n, BigInteger k) {
            if (k == 1) return Factorial(n);
            if (k == n) return 1;
            if (k > n) return 0;
            if (k < 1 || n < 1) return 0;
            return (Factorial(n) * Factorial(n - 1)) / (Factorial(k) * Factorial(k - 1)) / Factorial(n - k);
        }

        static void Main() {
            Console.WriteLine("Unsigned Lah numbers: L(n, k):");
            Console.Write("n/k ");
            foreach (var i in Enumerable.Range(0, 13)) {
                Console.Write("{0,10} ", i);
            }
            Console.WriteLine();
            foreach (var row in Enumerable.Range(0, 13)) {
                Console.Write("{0,-3}", row);
                foreach (var i in Enumerable.Range(0, row + 1)) {
                    var l = Lah(row, i);
                    Console.Write("{0,11}", l);
                }
                Console.WriteLine();
            }
            Console.WriteLine("\nMaximum value from the L(100, *) row:");
            var maxVal = Enumerable.Range(0, 100).Select(a => Lah(100, a)).Max();
            Console.WriteLine(maxVal);
        }
    }
}
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))); }
}
Task: Deepcopy



C#: using System;

namespace prog
{
	class MainClass
	{
		class MyClass : ICloneable
		{
			public MyClass() { f = new int[3]{2,3,5}; c = '1'; }
			
			public object Clone()
			{				
				MyClass cpy = (MyClass) this.MemberwiseClone();
				cpy.f = (int[]) this.f.Clone();			
				return cpy;
			}
			
			public char c;
			public int[] f;
		}
		
		public static void Main( string[] args )
		{
			MyClass c1 = new MyClass();
			MyClass c2 = (MyClass) c1.Clone();
		}
	}
}
Task: Frobenius numbers



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

class Program {

    static bool ispr(int x) { int lim = (int)Sqrt((double)x);
        if (x < 2) return false; if ((x % 3) == 0) return x == 0; bool odd = false;
        for (int d = 5; d <= lim; d += (odd = !odd) ? 2 : 4) {
        if (x % d == 0) return false; } return true; }

    static void Main() {
        int c = 0, d = 0, f, lim = 1000000, l2 = lim / 100; var Frob = PG.Primes((int)Sqrt(lim) + 1).ToArray();
        for (int n = 0, m = 1; m < Frob.Length; n = m++) {
            if ((f = Frob[n] * Frob[m] - Frob[n] - Frob[m]) < l2) d++;
            Write("{0,7:n0}{2} {1}", f , ++c % 10 == 0 ? "\n" : "", ispr(f) ? " " : "*"); }
        Write("\n\nCalculated {0} Frobenius numbers of consecutive primes under {1:n0}, " +
            "of which {2} were under {3:n0}", c, lim, d, l2); } }

class PG { public static IEnumerable<int> Primes(int lim) { 
    var flags = new bool[lim + 1]; int j = 3; yield return 2; 
    for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
      if (!flags[j]) { yield return j;
        for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
    for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
Task: Integer roots



C#: using System;
using System.Numerics;

namespace IntegerRoots {
    class Program {
        static BigInteger IRoot(BigInteger @base, int n) {
            if (@base < 0 || n <= 0) {
                throw new ArgumentException();
            }

            int n1 = n - 1;
            BigInteger n2 = n;
            BigInteger n3 = n1;
            BigInteger c = 1;
            BigInteger d = (n3 + @base) / n2;
            BigInteger e = ((n3 * d) + (@base / BigInteger.Pow(d, n1))) / n2;
            while (c != d && c != e) {
                c = d;
                d = e;
                e = (n3 * e + @base / BigInteger.Pow(e, n1)) / n2;
            }
            if (d < e) {
                return d;
            }
            return e;
        }

        static void Main(string[] args) {
            Console.WriteLine("3rd integer root of 8 = {0}", IRoot(8, 3));
            Console.WriteLine("3rd integer root of 9 = {0}", IRoot(9, 3));

            BigInteger b = BigInteger.Pow(100, 2000) * 2;
            Console.WriteLine("First 2001 digits of the sqaure root of 2: {0}", IRoot(b, 2));
        }
    }
}
Task: Random Latin squares



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

namespace RandomLatinSquares {
    using Matrix = List<List<int>>;

    
    static class Helper {
        private static readonly Random rng = new Random();

        public static void Shuffle<T>(this IList<T> list) {
            int n = list.Count;
            while (n > 1) {
                n--;
                int k = rng.Next(n + 1);
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    }

    class Program {
        static void PrintSquare(Matrix latin) {
            foreach (var row in latin) {
                Console.Write('[');

                var it = row.GetEnumerator();
                if (it.MoveNext()) {
                    Console.Write(it.Current);
                }
                while (it.MoveNext()) {
                    Console.Write(", ");
                    Console.Write(it.Current);
                }

                Console.WriteLine(']');
            }
            Console.WriteLine();
        }

        static void LatinSquare(int n) {
            if (n <= 0) {
                Console.WriteLine("[]");
                return;
            }

            var latin = new Matrix();
            for (int i = 0; i < n; i++) {
                List<int> temp = new List<int>();
                for (int j = 0; j < n; j++) {
                    temp.Add(j);
                }
                latin.Add(temp);
            }
            
            latin[0].Shuffle();

            
            for (int i = 1; i < n - 1; i++) {
                bool shuffled = false;

                while (!shuffled) {
                    latin[i].Shuffle();
                    for (int k = 0; k < i; k++) {
                        for (int j = 0; j < n; j++) {
                            if (latin[k][j] == latin[i][j]) {
                                goto shuffling;
                            }
                        }
                    }
                    shuffled = true;

                shuffling: { }
                }
            }

            
            for (int j = 0; j < n; j++) {
                List<bool> used = new List<bool>();
                for (int i = 0; i < n; i++) {
                    used.Add(false);
                }

                for (int i = 0; i < n-1; i++) {
                    used[latin[i][j]] = true;
                }
                for (int k = 0; k < n; k++) {
                    if (!used[k]) {
                        latin[n - 1][j] = k;
                        break;
                    }
                }
            }

            PrintSquare(latin);
        }

        static void Main() {
            LatinSquare(5);
            LatinSquare(5);
            LatinSquare(10); 
        }
    }
}
Task: Kolakoski sequence



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

namespace KolakoskiSequence {
    class Crutch {
        public readonly int len;
        public int[] s;
        public int i;

        public Crutch(int len) {
            this.len = len;
            s = new int[len];
            i = 0;
        }

        public void Repeat(int count) {
            for (int j = 0; j < count; j++) {
                if (++i == len) return;
                s[i] = s[i - 1];
            }
        }
    }

    static class Extension {
        public static int NextInCycle(this int[] self, int index) {
            return self[index % self.Length];
        }

        public static int[] Kolakoski(this int[] self, int len) {
            Crutch c = new Crutch(len);

            int k = 0;
            while (c.i < len) {
                c.s[c.i] = self.NextInCycle(k);
                if (c.s[k] > 1) {
                    c.Repeat(c.s[k] - 1);
                }
                if (++c.i == len) return c.s;
                k++;
            }
            return c.s;
        }

        public static bool PossibleKolakoski(this int[] self) {
            int[] rle = new int[self.Length];
            int prev = self[0];
            int count = 1;
            int pos = 0;
            for (int i = 1; i < self.Length; i++) {
                if (self[i] == prev) {
                    count++;
                }
                else {
                    rle[pos++] = count;
                    count = 1;
                    prev = self[i];
                }
            }
            
            for (int i = 0; i < pos; i++) {
                if (rle[i] != self[i]) {
                    return false;
                }
            }
            return true;
        }

        public static string AsString(this int[] self) {
            StringBuilder sb = new StringBuilder("[");
            int count = 0;
            foreach (var item in self) {
                if (count > 0) {
                    sb.Append(", ");
                }
                sb.Append(item);
                count++;
            }
            return sb.Append("]").ToString();
        }
    }

    class Program {
        static void Main(string[] args) {
            int[][] ias = {
                new int[]{1, 2},
                new int[]{2, 1},
                new int[]{1, 3, 1, 2},
                new int[]{1, 3, 2, 1}
            };
            int[] lens = { 20, 20, 30, 30 };

            for (int i = 0; i < ias.Length; i++) {
                int len = lens[i];
                int[] kol = ias[i].Kolakoski(len);

                Console.WriteLine("First {0} members of the sequence by {1}: ", len, ias[i].AsString());
                Console.WriteLine(kol.AsString());
                Console.WriteLine("Possible Kolakoski sequence? {0}", kol.PossibleKolakoski());
                Console.WriteLine();
            }
        }
    }
}
Task: Smarandache-Wellin primes

C: #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <gmp.h>

bool *sieve(int limit) {
    int i, p;
    limit++;
    
    bool *c = calloc(limit, sizeof(bool)); 
    c[0] = true;
    c[1] = true;
    for (i = 4; i < limit; i += 2) c[i] = true;
    p = 3; 
    while (true) {
        int p2 = p * p;
        if (p2 >= limit) break;
        for (i = p2; i < limit; i += 2 * p) c[i] = true;
        while (true) {
            p += 2;
            if (!c[p]) break;
        }
    }
    return c;
}

const char *ord(int count) {
    return (count == 1) ? "st" :
           (count == 2) ? "nd" :
           (count == 3) ? "rd" : "th";
}   

int main() {
    bool *c = sieve(12000);
    char sw[6000] = "";
    char tmp[20];
    int count = 0, p = 1, ix = 0, i;
    mpz_t n;
    mpz_init(n);
    printf("The known Smarandache-Wellin primes are:\n");
    while (count < 8) {
        while (c[++p]);
        sprintf(tmp, "%d", p);
        strcat(sw, tmp);
        mpz_set_str(n, sw, 10);
        if (mpz_probab_prime_p(n, 15) > 0) {
            count++;
            size_t le = strlen(sw);
            char sws[44];
            if (le < 5) {
                strcpy(sws, sw);
            } else {
                strncpy(sws, sw, 20);
                strcpy(sws + 20, "...");
                strncpy(sws + 23, sw + le - 20, 21);
            }
            printf("%2d%s: index %4d  digits %4ld  last prime %5d -> %s\n", count, ord(count), ix+1, le, p, sws);
        }
        ix++;
    }

    printf("\nThe first 20 Derived Smarandache-Wellin primes are:\n");
    int freqs[10] = {0};
    count = 0;
    p = 1;
    ix = 0;
    while (count < 20) {
        while (c[++p]);
        sprintf(tmp, "%d", p);
        for (i = 0; i < strlen(tmp); ++i) freqs[tmp[i]-48]++;
        char dsw[40] = "";
        for (i = 0; i < 10; ++i) {
            sprintf(tmp, "%d", freqs[i]);
            strcat(dsw, tmp);
        }
        int idx = -1;
        for (i = 0; i < strlen(dsw); ++i) {
            if (dsw[i] != '0') {
                idx = i;
                break;
            }
        }
        mpz_set_str(n, dsw + idx, 10);
        if (mpz_probab_prime_p(n, 15) > 0) {
            count++;                                                      
            printf("%2d%s: index %4d  prime %s\n", count, ord(count), ix+1, dsw + idx);
        }
        ix++; 
    }
    free(c);
    return 0;
}
Task: Active Directory_Search for a user






PHP: <?php

$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);

$bind = ldap_bind($l, 'me@example.com', 'password');

$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('displayName', 'company');

$search = ldap_search($l, $base, $criteria, $attributes);
$entries = ldap_get_entries($l, $search);

var_dump($entries);
Task: Numbers with same digit set in base 10 and base 16







Python: col = 0
for i in range(100000):
    if set(str(i)) == set(hex(i)[2:]):
        col += 1
        print("{:7}".format(i), end='\n'[:col % 10 == 0])
print()
Task: Four sides of square







Python: size = 9
for row in range(size):
    for col in range(size):
        if row == 0 or row == size-1 or col == 0 or col == size-1:
            print("1", end=" ")
        else:
            print("0", end=" ")
    print()
Task: Fixed length records







Python: infile = open('infile.dat', 'rb')
outfile = open('outfile.dat', 'wb')

while True:
    onerecord = infile.read(80)
    if len(onerecord) < 80:
        break
    onerecordreversed = bytes(reversed(onerecord))
    outfile.write(onerecordreversed)

infile.close()
outfile.close()