WeixiangYan/CodeTransOcean huggingface dataset:
Task: Stirling numbers of the second kind


C++: #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>

using integer = mpz_class;

class stirling2 {
public:
    integer get(int n, int k);
private:
    std::map<std::pair<int, int>, integer> cache_;
};

integer stirling2::get(int n, int k) {
    if (k == n)
        return 1;
    if (k == 0 || k > n)
        return 0;
    auto p = std::make_pair(n, k);
    auto i = cache_.find(p);
    if (i != cache_.end())
        return i->second;
    integer s = k * get(n - 1, k) + get(n - 1, k - 1);
    cache_.emplace(p, s);
    return s;
}

void print_stirling_numbers(stirling2& s2, int n) {
    std::cout << "Stirling numbers of the second kind:\nn/k";
    for (int j = 0; j <= n; ++j) {
        std::cout << std::setw(j == 0 ? 2 : 8) << j;
    }
    std::cout << '\n';
    for (int i = 0; i <= n; ++i) {
        std::cout << std::setw(2) << i << ' ';
        for (int j = 0; j <= i; ++j)
            std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);
        std::cout << '\n';
    }
}

int main() {
    stirling2 s2;
    print_stirling_numbers(s2, 12);
    std::cout << "Maximum value of S2(n,k) where n == 100:\n";
    integer max = 0;
    for (int k = 0; k <= 100; ++k)
        max = std::max(max, s2.get(100, k));
    std::cout << max << '\n';
    return 0;
}
Task: Stirling numbers of the first kind


C++: #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>

using integer = mpz_class;

class unsigned_stirling1 {
public:
    integer get(int n, int k);
private:
    std::map<std::pair<int, int>, integer> cache_;
};

integer unsigned_stirling1::get(int n, int k) {
    if (k == 0)
        return n == 0 ? 1 : 0;
    if (k > n)
        return 0;
    auto p = std::make_pair(n, k);
    auto i = cache_.find(p);
    if (i != cache_.end())
        return i->second;
    integer s = get(n - 1, k - 1) + (n - 1) * get(n - 1, k);
    cache_.emplace(p, s);
    return s;
}

void print_stirling_numbers(unsigned_stirling1& s1, int n) {
    std::cout << "Unsigned Stirling numbers of the first kind:\nn/k";
    for (int j = 0; j <= n; ++j) {
        std::cout << std::setw(j == 0 ? 2 : 10) << j;
    }
    std::cout << '\n';
    for (int i = 0; i <= n; ++i) {
        std::cout << std::setw(2) << i << ' ';
        for (int j = 0; j <= i; ++j)
            std::cout << std::setw(j == 0 ? 2 : 10) << s1.get(i, j);
        std::cout << '\n';
    }
}

int main() {
    unsigned_stirling1 s1;
    print_stirling_numbers(s1, 12);
    std::cout << "Maximum value of S1(n,k) where n == 100:\n";
    integer max = 0;
    for (int k = 0; k <= 100; ++k)
        max = std::max(max, s1.get(100, k));
    std::cout << max << '\n';
    return 0;
}
Task: Special factorials


C++: #include <cmath>
#include <cstdint>
#include <iostream>
#include <functional>


uint64_t factorial(int n) {
    uint64_t result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}


int inverse_factorial(uint64_t f) {
    int p = 1;
    int i = 1;

    if (f == 1) {
        return 0;
    }

    while (p < f) {
        p *= i;
        i++;
    }

    if (p == f) {
        return i - 1;
    }
    return -1;
}


uint64_t super_factorial(int n) {
    uint64_t result = 1;
    for (int i = 1; i <= n; i++) {
        result *= factorial(i);
    }
    return result;
}


uint64_t hyper_factorial(int n) {
    uint64_t result = 1;
    for (int i = 1; i <= n; i++) {
        result *= (uint64_t)powl(i, i);
    }
    return result;
}


uint64_t alternating_factorial(int n) {
    uint64_t result = 0;
    for (int i = 1; i <= n; i++) {
        if ((n - i) % 2 == 0) {
            result += factorial(i);
        } else {
            result -= factorial(i);
        }
    }
    return result;
}


uint64_t exponential_factorial(int n) {
    uint64_t result = 0;
    for (int i = 1; i <= n; i++) {
        result = (uint64_t)powl(i, (long double)result);
    }
    return result;
}

void test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {
    std::cout << "First " << count << ' ' << name << '\n';
    for (int i = 0; i < count; i++) {
        std::cout << func(i) << ' ';
    }
    std::cout << '\n';
}

void test_inverse(uint64_t f) {
    int n = inverse_factorial(f);
    if (n < 0) {
        std::cout << "rf(" << f << ") = No Solution\n";
    } else {
        std::cout << "rf(" << f << ") = " << n << '\n';
    }
}

int main() {
    
    test_factorial(9, super_factorial, "super factorials");
    std::cout << '\n';

    
    test_factorial(8, hyper_factorial, "hyper factorials");
    std::cout << '\n';

    test_factorial(10, alternating_factorial, "alternating factorials");
    std::cout << '\n';

    test_factorial(5, exponential_factorial, "exponential factorials");
    std::cout << '\n';

    test_inverse(1);
    test_inverse(2);
    test_inverse(6);
    test_inverse(24);
    test_inverse(120);
    test_inverse(720);
    test_inverse(5040);
    test_inverse(40320);
    test_inverse(362880);
    test_inverse(3628800);
    test_inverse(119);

    return 0;
}
Task: Tropical algebra overloading


C++: #include <iostream>
#include <optional>

using namespace std;

class TropicalAlgebra
{
    
    optional<double> m_value;
    
public:
    friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);
    friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;
    
    
    TropicalAlgebra() = default;

    
    explicit TropicalAlgebra(double value) noexcept
        : m_value{value} {}

    
    
    TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept
    {
        if(!m_value)
        {
            
            *this = rhs;
        }
        else if (!rhs.m_value)
        {
            
        }
        else
        {
            
            *m_value = max(*rhs.m_value, *m_value);
        }

        return *this;
    }
    
    
    TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept
    {
        if(!m_value)
        {
            
            
        }
        else if (!rhs.m_value)
        {
            
            *this = rhs;
        }
        else
        {
            *m_value += *rhs.m_value;
        }

        return *this;
    }
};


inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
    
    lhs += rhs;
    return lhs;
}


inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra&  rhs) noexcept
{
    lhs *= rhs;
    return lhs;
}


inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept
{
    auto result = base;
    for(unsigned int i = 1; i < exponent; i++)
    {
        
        result *= base;
    }
    return result;
}


ostream& operator<<(ostream& os, const TropicalAlgebra& pt)
{
    if(!pt.m_value) cout << "-Inf\n";
    else cout << *pt.m_value << "\n";
    return os;
}

int main(void) {
    const TropicalAlgebra a(-2);
    const TropicalAlgebra b(-1);
    const TropicalAlgebra c(-0.5);
    const TropicalAlgebra d(-0.001);
    const TropicalAlgebra e(0);
    const TropicalAlgebra h(1.5);
    const TropicalAlgebra i(2);
    const TropicalAlgebra j(5);
    const TropicalAlgebra k(7);
    const TropicalAlgebra l(8);
    const TropicalAlgebra m; 
    
    cout << "2 * -2 == " << i * a;
    cout << "-0.001 + -Inf == " << d + m;
    cout << "0 * -Inf == " << e * m;
    cout << "1.5 + -1 == " << h + b;
    cout << "-0.5 * 0 == " << c * e;
    cout << "pow(5, 7) == " << pow(j, 7);
    cout << "5 * (8 + 7)) == " << j * (l + k);
    cout << "5 * 8 + 5 * 7 == " << j * l + j * k;
}
Task: Special characters





Java: & | ^ ~ 
>> << 
>>> 
+ - * / = %
Task: Odd words





Java: import java.io.*;
import java.util.*;

public class OddWords {
    public static void main(String[] args) {
        try {
            Set<String> dictionary = new TreeSet<>();
            final int minLength = 5;
            String fileName = "unixdict.txt";
            if (args.length != 0)
                fileName = args[0];
            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.length() >= minLength)
                        dictionary.add(line);
                }
            }
            StringBuilder word1 = new StringBuilder();
            StringBuilder word2 = new StringBuilder();
            List<StringPair> evenWords = new ArrayList<>();
            List<StringPair> oddWords = new ArrayList<>();
            for (String word : dictionary) {
                int length = word.length();
                if (length < minLength + 2 * (minLength/2))
                    continue;
                word1.setLength(0);
                word2.setLength(0);
                for (int i = 0; i < length; ++i) {
                    if ((i & 1) == 0)
                        word1.append(word.charAt(i));
                    else
                        word2.append(word.charAt(i));
                }
                String oddWord = word1.toString();
                String evenWord = word2.toString();
                if (dictionary.contains(oddWord))
                    oddWords.add(new StringPair(word, oddWord));
                if (dictionary.contains(evenWord))
                    evenWords.add(new StringPair(word, evenWord));
            }
            System.out.println("Odd words:");
            printWords(oddWords);
            System.out.println("\nEven words:");
            printWords(evenWords);
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }

    private static void printWords(List<StringPair> strings) {
        int n = 1;
        for (StringPair pair : strings) {
            System.out.printf("%2d: %-14s%s\n", n++,
                                    pair.string1, pair.string2);
        }
    }

    private static class StringPair {
        private String string1;
        private String string2;
        private StringPair(String s1, String s2) {
            string1 = s1;
            string2 = s2;
        }
    }
}
Task: Loops_Infinite





Java: while (true) {
   System.out.println("SPAM");
}
Task: Assertions in design by contract





Java: (...)
int feedForward(double[] inputs) {
    assert inputs.length == weights.length : "weights and input length mismatch";

    double sum = 0;
    for (int i = 0; i < weights.length; i++) {
        sum += inputs[i] * weights[i];
    }
    return activate(sum);
}
(...)
Task: History variables





Java: public class HistoryVariable
{
    private Object value;

    public HistoryVariable(Object v)
    {
        value = v;
    }

    public void update(Object v)
    {
        value = v;
    }

    public Object undo()
    {
        return value;
    }

    @Override
    public String toString()
    {
        return value.toString();
    }

    public void dispose()
    {
    }
}
Task: Function definition





Java: module MultiplyExample
    {
    static <Value extends Number> Value multiply(Value n1, Value n2)
        {
        return n1 * n2;
        }

    void run()
        {
        (Int i1, Int i2) = (7, 3);
        Int i3 = multiply(i1, i2);
        (Double d1, Double d2) = (2.7182818, 3.1415);
        Double d3 = multiply(d1, d2);
        @Inject Console console;
        console.print($"{i1}*{i2}={i3}, {d1}*{d2}={d3}");
        }
    }
Task: Successive prime differences





Java: import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SuccessivePrimeDifferences {
    private static Integer[] sieve(int limit) {
        List<Integer> primes = new ArrayList<>();
        primes.add(2);
        boolean[] c = new boolean[limit + 1];
        
        int p = 3;
        while (true) {
            int p2 = p * p;
            if (p2 > limit) {
                break;
            }
            for (int i = p2; i <= limit; i += 2 * p) {
                c[i] = true;
            }
            do {
                p += 2;
            } while (c[p]);
        }
        for (int i = 3; i <= limit; i += 2) {
            if (!c[i]) {
                primes.add(i);
            }
        }

        return primes.toArray(new Integer[0]);
    }

    private static List<List<Integer>> successivePrimes(Integer[] primes, Integer[] diffs) {
        List<List<Integer>> results = new ArrayList<>();
        int dl = diffs.length;
        outer:
        for (int i = 0; i < primes.length - dl; i++) {
            Integer[] group = new Integer[dl + 1];
            group[0] = primes[i];
            for (int j = i; j < i + dl; ++j) {
                if (primes[j + 1] - primes[j] != diffs[j - i]) {
                    continue outer;
                }
                group[j - i + 1] = primes[j + 1];
            }
            results.add(Arrays.asList(group));
        }
        return results;
    }

    public static void main(String[] args) {
        Integer[] primes = sieve(999999);
        Integer[][] diffsList = {{2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2}};
        System.out.println("For primes less than 1,000,000:-\n");
        for (Integer[] diffs : diffsList) {
            System.out.printf("  For differences of %s ->\n", Arrays.toString(diffs));
            List<List<Integer>> sp = successivePrimes(primes, diffs);
            if (sp.isEmpty()) {
                System.out.println("    No groups found");
                continue;
            }
            System.out.printf("    First group   = %s\n", Arrays.toString(sp.get(0).toArray(new Integer[0])));
            System.out.printf("    Last group    = %s\n", Arrays.toString(sp.get(sp.size() - 1).toArray(new Integer[0])));
            System.out.printf("    Number found  = %d\n", sp.size());
            System.out.println();
        }
    }
}
Task: 10001th prime





Java: public class NthPrime {
    public static void main(String[] args) {
        System.out.printf("The 10,001st prime is %,d.\n", nthPrime(10001));
    }

    private static int nthPrime(int n) {
        assert n > 0;
        PrimeGenerator primeGen = new PrimeGenerator(10000, 100000);
        int prime = primeGen.nextPrime();
        while (--n > 0)
            prime = primeGen.nextPrime();
        return prime;
    }
}
Task: Next special primes





Java: class SpecialPrimes {
    private static boolean 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;
    }

    public static void main(String[] args) {
        System.out.println("Special primes under 1,050:");
        System.out.println("Prime1 Prime2 Gap");
        int lastSpecial = 3;
        int lastGap = 1;
        System.out.printf("%6d %6d %3d\n", 2, 3, lastGap);
        for (int i = 5; i < 1050; i += 2) {
            if (isPrime(i) && (i-lastSpecial) > lastGap) {
                lastGap = i - lastSpecial;
                System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
                lastSpecial = i;
            }
        }
    }
}
Task: Modulinos





Java: public class ScriptedMain {
	public static int meaningOfLife() {
		return 42;
	}

	public static void main(String[] args) {
		System.out.println("Main: The meaning of life is " + meaningOfLife());
	}
}
Task: Active Directory_Connect





Java: import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;

public class LdapConnectionDemo {

    public static void main(String[] args) throws LdapException, IOException {
        try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
            connection.bind();
            connection.unBind();
        }
    }
}
Task: Write to Windows event log





Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class WriteToWindowsEventLog {
    public static void main(String[] args) throws IOException, InterruptedException {
        String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
        if (!osName.startsWith("WINDOWS")) {
            System.err.println("Not windows");
            return;
        }

        Process process = Runtime.getRuntime().exec("EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \"Rosetta Code Example\"");
        process.waitFor(10, TimeUnit.SECONDS);
        int exitValue = process.exitValue();
        System.out.printf("Process exited with value %d\n", exitValue);
        if (exitValue != 0) {
            InputStream errorStream = process.getErrorStream();
            String result = new BufferedReader(new InputStreamReader(errorStream))
                .lines()
                .collect(Collectors.joining("\n"));
            System.err.println(result);
        }
    }
}
Task: Getting the number of decimal places





Java: public static int findNumOfDec(double x){
    String str = String.valueOf(x);
    if(str.endsWith(".0")) return 0;
    else return (str.substring(str.indexOf('.')).length() - 1);
}
Task: Pythagorean quadruples





Java: import java.util.ArrayList;
import java.util.List;

public class PythagoreanQuadruples {

    public static void main(String[] args) {
        long d = 2200;
        System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
    }

    
    private static List<Long> getPythagoreanQuadruples(long max) {
        List<Long> list = new ArrayList<>();
        long n = -1;
        long m = -1;
        while ( true ) {
            long nTest = (long) Math.pow(2, n+1);
            long mTest = (long) (5L * Math.pow(2, m+1));
            long test = 0;
            if ( nTest > mTest ) {
                test = mTest;
                m++;
            }
            else {
                test = nTest;
                n++;
            }
            if ( test < max ) {
                list.add(test);
            }
            else {
                break;
            }
        }
        return list;
    }

}
Task: Superpermutation minimisation





Java: import static java.util.stream.IntStream.rangeClosed;

public class Test {
    final static int nMax = 12;

    static char[] superperm;
    static int pos;
    static int[] count = new int[nMax];

    static int factSum(int n) {
        return rangeClosed(1, n)
                .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum();
    }

    static boolean r(int n) {
        if (n == 0)
            return false;

        char c = superperm[pos - n];
        if (--count[n] == 0) {
            count[n] = n;
            if (!r(n - 1))
                return false;
        }
        superperm[pos++] = c;
        return true;
    }

    static void superPerm(int n) {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        pos = n;
        superperm = new char[factSum(n)];

        for (int i = 0; i < n + 1; i++)
            count[i] = i;
        for (int i = 1; i < n + 1; i++)
            superperm[i - 1] = chars.charAt(i);

        while (r(n)) {
        }
    }

    public static void main(String[] args) {
        for (int n = 0; n < nMax; n++) {
            superPerm(n);
            System.out.printf("superPerm(%2d) len = %d", n, superperm.length);
            System.out.println();
        }
    }
}
Task: Long primes





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

public class LongPrimes
{
    private static void sieve(int limit, List<Integer> primes)
    {
        boolean[] c = new boolean[limit];
        for (int i = 0; i < limit; i++)
            c[i] = false;
        
        int p = 3, n = 0;
        int p2 = p * p;
        while (p2 <= limit)
        {
            for (int i = p2; i <= limit; i += 2 * p)
                c[i] = true;
            do
                p += 2;
            while (c[p]);
            p2 = p * p;
        }
        for (int i = 3; i <= limit; i += 2)
            if (!c[i])
                primes.add(i);
    }

    
    private static int findPeriod(int n)
    {
        int r = 1, period = 0;
        for (int i = 1; i < n; i++)
            r = (10 * r) % n;
        int rr = r;
        do
        {
            r = (10 * r) % n;
            ++period;
        }
        while (r != rr);
        return period;
    }
    
    public static void main(String[] args)
    {
        int[] numbers = new int[]{500, 1000, 2000, 4000, 8000, 16000, 32000, 64000};
        int[] totals = new int[numbers.length]; 
        List<Integer> primes = new LinkedList<Integer>();
        List<Integer> longPrimes = new LinkedList<Integer>();
        sieve(64000, primes);
        for (int prime : primes)
            if (findPeriod(prime) == prime - 1)
                longPrimes.add(prime);
        int count = 0, index = 0;
        for (int longPrime : longPrimes)
        {
            if (longPrime > numbers[index])
                totals[index++] = count;
            ++count;
        }
        totals[numbers.length - 1] = count;
        System.out.println("The long primes up to " + numbers[0] + " are:");
        System.out.println(longPrimes.subList(0, totals[0]));
        System.out.println();
        System.out.println("The number of long primes up to:");
        for (int i = 0; i <= 7; i++)
            System.out.printf("  %5d is %d\n", numbers[i], totals[i]);
    }
}
Task: Active Directory_Search for a user





Java: import java.io.IOException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;

public class LdapSearchDemo {

    public static void main(String[] args) throws IOException, LdapException, CursorException {
        new LdapSearchDemo().demonstrateSearch();
    }

    private void demonstrateSearch() throws IOException, LdapException, CursorException {
        try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) {
            conn.bind("uid=admin,ou=system", "********");
            search(conn, "*mil*");
            conn.unBind();
        }
    }

    private void search(LdapConnection connection, String uid) throws LdapException, CursorException {
        String baseDn = "ou=users,o=mojo";
        String filter = "(&(objectClass=person)(&(uid=" + uid + ")))";
        SearchScope scope = SearchScope.SUBTREE;
        String[] attributes = {"dn", "cn", "sn", "uid"};
        int ksearch = 0;

        EntryCursor cursor = connection.search(baseDn, filter, scope, attributes);
        while (cursor.next()) {
            ksearch++;
            Entry entry = cursor.get();
            System.out.printf("Search entry %d = %s%n", ksearch, entry);
        }
    }
}