WeixiangYan/CodeTransOcean huggingface dataset:
Task: Ramsey's theorem





Java: import java.util.Arrays;
import java.util.stream.IntStream;

public class RamseysTheorem {

    static char[][] createMatrix() {
        String r = "-" + Integer.toBinaryString(53643);
        int len = r.length();
        return IntStream.range(0, len)
                .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i))
                .map(String::toCharArray)
                .toArray(char[][]::new);
    }

    
    static String ramseyCheck(char[][] mat) {
        int len = mat.length;
        char[] connectivity = "------".toCharArray();

        for (int a = 0; a < len; a++) {
            for (int b = 0; b < len; b++) {
                if (a == b)
                    continue;
                connectivity[0] = mat[a][b];
                for (int c = 0; c < len; c++) {
                    if (a == c || b == c)
                        continue;
                    connectivity[1] = mat[a][c];
                    connectivity[2] = mat[b][c];
                    for (int d = 0; d < len; d++) {
                        if (a == d || b == d || c == d)
                            continue;
                        connectivity[3] = mat[a][d];
                        connectivity[4] = mat[b][d];
                        connectivity[5] = mat[c][d];

                        
                        
                        String conn = new String(connectivity);
                        if (conn.indexOf('0') == -1)
                            return String.format("Fail, found wholly connected: "
                                    + "%d %d %d %d", a, b, c, d);
                        else if (conn.indexOf('1') == -1)
                            return String.format("Fail, found wholly unconnected: "
                                    + "%d %d %d %d", a, b, c, d);
                    }
                }
            }
        }
        return "Satisfies Ramsey condition.";
    }

    public static void main(String[] a) {
        char[][] mat = createMatrix();
        for (char[] s : mat)
            System.out.println(Arrays.toString(s));
        System.out.println(ramseyCheck(mat));
    }
}
Task: Type detection





Java: public class TypeDetection {
    private static void showType(Object a) {
        if (a instanceof Integer) {
            System.out.printf("'%s' is an integer\n", a);
        } else if (a instanceof Double) {
            System.out.printf("'%s' is a double\n", a);
        } else if (a instanceof Character) {
            System.out.printf("'%s' is a character\n", a);
        } else {
            System.out.printf("'%s' is some other type\n", a);
        }
    }

    public static void main(String[] args) {
        showType(5);
        showType(7.5);
        showType('d');
        showType(true);
    }
}
Task: Safe primes and unsafe primes





Java: public class SafePrimes {
    public static void main(String... args) {
        
        int SIEVE_SIZE = 10_000_000;
        boolean[] isComposite = new boolean[SIEVE_SIZE];
        
        isComposite[0] = true;
        isComposite[1] = true;
        for (int n = 2; n < SIEVE_SIZE; n++) {
            if (isComposite[n]) {
                continue;
            }
            for (int i = n * 2; i < SIEVE_SIZE; i += n) {
                isComposite[i] = true;
            }
        }
        
        int oldSafePrimeCount = 0;
        int oldUnsafePrimeCount = 0;
        int safePrimeCount = 0;
        int unsafePrimeCount = 0;
        StringBuilder safePrimes = new StringBuilder();
        StringBuilder unsafePrimes = new StringBuilder();
        int safePrimesStrCount = 0;
        int unsafePrimesStrCount = 0;
        for (int n = 2; n < SIEVE_SIZE; n++) {
            if (n == 1_000_000) {
                oldSafePrimeCount = safePrimeCount;
                oldUnsafePrimeCount = unsafePrimeCount;
            }
            if (isComposite[n]) {
                continue;
            }
            boolean isUnsafe = isComposite[(n - 1) >>> 1];
            if (isUnsafe) {
                if (unsafePrimeCount < 40) {
                    if (unsafePrimeCount > 0) {
                        unsafePrimes.append(", ");
                    }
                    unsafePrimes.append(n);
                    unsafePrimesStrCount++;
                }
                unsafePrimeCount++;
            }
            else {
                if (safePrimeCount < 35) {
                    if (safePrimeCount > 0) {
                        safePrimes.append(", ");
                    }
                    safePrimes.append(n);
                    safePrimesStrCount++;
                }
                safePrimeCount++;
            }
        }
        
        System.out.println("First " + safePrimesStrCount + " safe primes: " + safePrimes.toString());
        System.out.println("Number of safe primes below 1,000,000: " + oldSafePrimeCount);
        System.out.println("Number of safe primes below 10,000,000: " + safePrimeCount);
        System.out.println("First " + unsafePrimesStrCount + " unsafe primes: " + unsafePrimes.toString());
        System.out.println("Number of unsafe primes below 1,000,000: " + oldUnsafePrimeCount);
        System.out.println("Number of unsafe primes below 10,000,000: " + unsafePrimeCount);
        
        return;
    }
}
Task: Hash join





Java: import java.util.*;

public class HashJoin {

    public static void main(String[] args) {
        String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
        {"18", "Popeye"}, {"28", "Alan"}};

        String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
        {"Bob", "foo"}};

        hashJoin(table1, 1, table2, 0).stream()
                .forEach(r -> System.out.println(Arrays.deepToString(r)));
    }

    static List<String[][]> hashJoin(String[][] records1, int idx1,
            String[][] records2, int idx2) {

        List<String[][]> result = new ArrayList<>();
        Map<String, List<String[]>> map = new HashMap<>();

        for (String[] record : records1) {
            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
            v.add(record);
            map.put(record[idx1], v);
        }

        for (String[] record : records2) {
            List<String[]> lst = map.get(record[idx2]);
            if (lst != null) {
                lst.stream().forEach(r -> {
                    result.add(new String[][]{r, record});
                });
            }
        }

        return result;
    }
}
Task: Permutations with repetitions





Java: import java.util.function.Predicate;

public class PermutationsWithRepetitions {

    public static void main(String[] args) {
        char[] chars = {'a', 'b', 'c', 'd'};
        
        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
    }

    static void permute(char[] a, int k, Predicate<int[]> decider) {
        int n = a.length;
        if (k < 1 || k > n)
            throw new IllegalArgumentException("Illegal number of positions.");

        int[] indexes = new int[n];
        int total = (int) Math.pow(n, k);

        while (total-- > 0) {
            for (int i = 0; i < n - (n - k); i++)
                System.out.print(a[indexes[i]]);
            System.out.println();

            if (decider.test(indexes))
                break;

            for (int i = 0; i < n; i++) {
                if (indexes[i] >= n - 1) {
                    indexes[i] = 0;
                } else {
                    indexes[i]++;
                    break;
                }
            }
        }
    }
}
Task: Idiomatically determine all the characters that can be used for symbols





Java: import java.util.function.IntPredicate;
import java.util.stream.IntStream;

public class Test {
    public static void main(String[] args) throws Exception {
        print("Java Identifier start:     ", 0, 0x10FFFF, 72,
                Character::isJavaIdentifierStart, "%c");

        print("Java Identifier part:      ", 0, 0x10FFFF, 25,
                Character::isJavaIdentifierPart, "[%d]");

        print("Identifier ignorable:      ", 0, 0x10FFFF, 25,
                Character::isIdentifierIgnorable, "[%d]");

        print("Unicode Identifier start:  ", 0, 0x10FFFF, 72,
                Character::isUnicodeIdentifierStart, "%c");

        print("Unicode Identifier part :  ", 0, 0x10FFFF, 25,
                Character::isUnicodeIdentifierPart, "[%d]");
    }

    static void print(String msg, int start, int end, int limit, 
        IntPredicate p, String fmt) {

        System.out.print(msg);
        IntStream.rangeClosed(start, end)
                .filter(p)
                .limit(limit)
                .forEach(cp -> System.out.printf(fmt, cp));
        System.out.println("...");
    }
}
Task: Selective file copy





Java: import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

class CopysJ {

  public static void main(String[] args) {
    String ddname_IN  = "copys.in.txt";
    String ddname_OUT = "copys.out.txt";
    if (args.length >= 1) { ddname_IN  = args[0].length() > 0 ? args[0] : ddname_IN; }
    if (args.length >= 2) { ddname_OUT = args[1].length() > 0 ? args[1] : ddname_OUT; }

    File dd_IN = new File(ddname_IN);
    File dd_OUT = new File(ddname_OUT);

    try (
      Scanner scanner_IN = new Scanner(dd_IN);
      BufferedWriter writer_OUT = new BufferedWriter(new FileWriter(dd_OUT))
      ) {
      String a;
      String b;
      String c;
      String d;
      String c1;
      String x = "XXXXX";
      String data_IN;
      String data_OUT;
      int ib;

      while (scanner_IN.hasNextLine()) {
        data_IN = scanner_IN.nextLine();
        ib = 0;
        a = data_IN.substring(ib, ib += 5);
        b = data_IN.substring(ib, ib += 5);
        c = data_IN.substring(ib, ib += 4);
        c1=Integer.toHexString(new Byte((c.getBytes())[0]).intValue());
        if (c1.length()<2) { c1="0" + c1; }
        data_OUT = a + c1 + x;
        writer_OUT.write(data_OUT);
        writer_OUT.newLine();
        System.out.println(data_IN);
        System.out.println(data_OUT);
        System.out.println();
      }
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
    return;
  }
}
Task: Audio alarm





Java: import com.sun.javafx.application.PlatformImpl;
import java.io.File;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class AudioAlarm {

    public static void main(String[] args) throws InterruptedException {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number of seconds: ");
        int seconds = Integer.parseInt(input.nextLine());

        System.out.print("Enter a filename (must end with .mp3 or .wav): ");
        String audio = input.nextLine();

        TimeUnit.SECONDS.sleep(seconds);

        Media media = new Media(new File(audio).toURI().toString());
        AtomicBoolean stop = new AtomicBoolean();
        Runnable onEnd = () -> stop.set(true);

        PlatformImpl.startup(() -> {}); 

        MediaPlayer player = new MediaPlayer(media);
        player.setOnEndOfMedia(onEnd);
        player.setOnError(onEnd);
        player.setOnHalted(onEnd);
        player.play();

        while (!stop.get()) {
            Thread.sleep(100);
        }
        System.exit(0); 
    }
}
Task: Terminal control_Preserve screen





Java: public class PreserveScreen
{
    public static void main(String[] args) throws InterruptedException {
        System.out.print("\033[?1049h\033[H");
        System.out.println("Alternate screen buffer\n");
        for (int i = 5; i > 0; i--) {
            String s = (i > 1) ? "s" : "";
            System.out.printf("\rgoing back in %d second%s...", i, s);
            Thread.sleep(1000);
        }
        System.out.print("\033[?1049l");
    }
}
Task: Find largest left truncatable prime in a given base





Java: import java.math.BigInteger;
import java.util.*;

class LeftTruncatablePrime
{
  private static List<BigInteger> getNextLeftTruncatablePrimes(BigInteger n, int radix, int millerRabinCertainty)
  {
    List<BigInteger> probablePrimes = new ArrayList<BigInteger>();
    String baseString = n.equals(BigInteger.ZERO) ? "" : n.toString(radix);
    for (int i = 1; i < radix; i++)
    {
      BigInteger p = new BigInteger(Integer.toString(i, radix) + baseString, radix);
      if (p.isProbablePrime(millerRabinCertainty))
        probablePrimes.add(p);
    }
    return probablePrimes;
  }
  
  public static BigInteger getLargestLeftTruncatablePrime(int radix, int millerRabinCertainty)
  {
    List<BigInteger> lastList = null;
    List<BigInteger> list = getNextLeftTruncatablePrimes(BigInteger.ZERO, radix, millerRabinCertainty);
    while (!list.isEmpty())
    {
      lastList = list;
      list = new ArrayList<BigInteger>();
      for (BigInteger n : lastList)
        list.addAll(getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty));
    }
    if (lastList == null)
      return null;
    Collections.sort(lastList);
    return lastList.get(lastList.size() - 1);
  }
  
  public static void main(String[] args)
  {
    if (args.length != 2) {
      System.err.println("There must be exactly two command line arguments.");
      return;
    }
    int maxRadix;
    try {
      maxRadix = Integer.parseInt(args[0]);
      if (maxRadix < 3) throw new NumberFormatException(); 
    } catch (NumberFormatException e) {
      System.err.println("Radix must be an integer greater than 2.");
      return;
    }
    int millerRabinCertainty;
    try {
      millerRabinCertainty = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
      System.err.println("Miiller-Rabin Certainty must be an integer.");
      return;
    }  
    for (int radix = 3; radix <= maxRadix; radix++)
    {
      BigInteger largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty);
      System.out.print("n=" + radix + ": ");
      if (largest == null)
        System.out.println("No left-truncatable prime");
      else
        System.out.println(largest + " (in base " + radix + "): " + largest.toString(radix));
    }
  }
  
}
Task: Doubly-linked list_Definition





Java: import java.util.LinkedList;

public class DoublyLinkedList {
   
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.addFirst("Add First");
        list.addLast("Add Last 1");
        list.addLast("Add Last 2");
        list.addLast("Add Last 1");
        traverseList(list);
        
        list.removeFirstOccurrence("Add Last 1");
        traverseList(list);
    }
    
    private static void traverseList(LinkedList<String> list) {
        System.out.println("Traverse List:");
        for ( int i = 0 ; i < list.size() ; i++ ) {
            System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
        }
        System.out.println();
    }
    
}
Task: State name puzzle





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

public class StateNamePuzzle {

    static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas",
        "California", "Colorado", "Connecticut", "Delaware", "Florida",
        "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
        "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
        "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
        "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
        "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma",
        "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
        "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
        "Washington", "West Virginia", "Wisconsin", "Wyoming",
        "New Kory", "Wen Kory", "York New", "Kory New", "New Kory",};

    public static void main(String[] args) {
        solve(Arrays.asList(states));
    }

    static void solve(List<String> input) {
        Map<String, String> orig = input.stream().collect(Collectors.toMap(
                s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s));

        input = new ArrayList<>(orig.keySet());

        Map<String, List<String[]>> map = new HashMap<>();
        for (int i = 0; i < input.size() - 1; i++) {
            String pair0 = input.get(i);
            for (int j = i + 1; j < input.size(); j++) {

                String[] pair = {pair0, input.get(j)};
                String s = pair0 + pair[1];
                String key = Arrays.toString(s.chars().sorted().toArray());

                List<String[]> val = map.getOrDefault(key, new ArrayList<>());
                val.add(pair);
                map.put(key, val);
            }
        }

        map.forEach((key, list) -> {
            for (int i = 0; i < list.size() - 1; i++) {
                String[] a = list.get(i);
                for (int j = i + 1; j < list.size(); j++) {
                    String[] b = list.get(j);

                    if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)
                        continue;

                    System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]),
                            orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));
                }
            }
        });
    }
}
Task: Super-d numbers





Java: import java.math.BigInteger;

public class SuperDNumbers {

    public static void main(String[] args) {
        for ( int i = 2 ; i <= 9 ; i++ ) {
            superD(i, 10);
        }
    }
    
    private static final void superD(int d, int max) {
        long start = System.currentTimeMillis();
        String test = "";
        for ( int i = 0 ; i < d ; i++ ) {
            test += (""+d);
        }
        
        int n = 0;
        int i = 0;
        System.out.printf("First %d super-%d numbers: %n", max, d);
        while ( n < max ) {
            i++;
            BigInteger val = BigInteger.valueOf(d).multiply(BigInteger.valueOf(i).pow(d));
            if ( val.toString().contains(test) ) {
                n++;
                System.out.printf("%d ", i);
            }
        }
        long end = System.currentTimeMillis();
        System.out.printf("%nRun time %d ms%n%n", end-start);
        
    }

}
Task: Church numerals





Java: package lvijay;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

public class Church {
    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
    }

    public static ChurchNum zero() {
        return f -> x -> x;
    }

    public static ChurchNum next(ChurchNum n) {
        return f -> x -> f.apply(n.apply(f).apply(x));
    }

    public static ChurchNum plus(ChurchNum a) {
        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
    }

    public static ChurchNum pow(ChurchNum m) {
        return n -> m.apply(n);
    }

    public static ChurchNum mult(ChurchNum a) {
        return b -> f -> x -> b.apply(a.apply(f)).apply(x);
    }

    public static ChurchNum toChurchNum(int n) {
        if (n <= 0) {
            return zero();
        }
        return next(toChurchNum(n - 1));
    }

    public static int toInt(ChurchNum c) {
        AtomicInteger counter = new AtomicInteger(0);
        ChurchNum funCounter = f -> {
            counter.incrementAndGet();
            return f;
        };

        plus(zero()).apply(c).apply(funCounter).apply(x -> x);

        return counter.get();
    }

    public static void main(String[] args) {
        ChurchNum zero  = zero();
        ChurchNum three = next(next(next(zero)));
        ChurchNum four  = next(next(next(next(zero))));

        System.out.println("3+4=" + toInt(plus(three).apply(four))); 
        System.out.println("4+3=" + toInt(plus(four).apply(three))); 

        System.out.println("3*4=" + toInt(mult(three).apply(four))); 
        System.out.println("4*3=" + toInt(mult(four).apply(three))); 

        
        System.out.println("3^4=" + toInt(pow(four).apply(three))); 
        System.out.println("4^3=" + toInt(pow(three).apply(four))); 

        System.out.println("  8=" + toInt(toChurchNum(8))); 
    }
}
Task: Reflection_List methods





Java: import java.lang.reflect.Method;

public class ListMethods {
    public int examplePublicInstanceMethod(char c, double d) {
        return 42;
    }

    private boolean examplePrivateInstanceMethod(String s) {
        return true;
    }
    
    public static void main(String[] args) {
        Class clazz = ListMethods.class;

        System.out.println("All public methods (including inherited):");
        for (Method m : clazz.getMethods()) {
            System.out.println(m);
        }
        System.out.println();
        System.out.println("All declared methods (excluding inherited):");
        for (Method m : clazz.getDeclaredMethods()) {
            System.out.println(m);
        }
    }
}
Task: Special variables





Java: import java.util.Arrays;

public class SpecialVariables {

    public static void main(String[] args) {

        
        
        System.out.println(Arrays.toString(args));

        
        
        System.out.println(SpecialVariables.class);


        

        
        System.out.println(System.getenv());

        
        
        System.out.println(System.getProperties());

        
        
        System.out.println(Runtime.getRuntime().availableProcessors());

    }
}
Task: Canonicalize CIDR





Java: import java.text.MessageFormat;
import java.text.ParseException;

public class CanonicalizeCIDR {
    public static void main(String[] args) {
        for (String test : TESTS) {
            try {
                CIDR cidr = new CIDR(test);
                System.out.printf("%-18s -> %s\n", test, cidr.toString());
            } catch (Exception ex) {
                System.err.printf("Error parsing '%s': %s\n", test, ex.getLocalizedMessage());
            }
        }
    }

    private static class CIDR {
        private CIDR(int address, int maskLength) {
            this.address = address;
            this.maskLength = maskLength;
        }

        private CIDR(String str) throws Exception {
            Object[] args = new MessageFormat(FORMAT).parse(str);
            int address = 0;
            for (int i = 0; i < 4; ++i) {
                int a = ((Number)args[i]).intValue();
                if (a < 0 || a > 255)
                    throw new Exception("Invalid IP address");
                address <<= 8;
                address += a;
            }
            int maskLength = ((Number)args[4]).intValue();
            if (maskLength < 1 || maskLength > 32)
                throw new Exception("Invalid mask length");
            int mask = ~((1 << (32 - maskLength)) - 1);
            this.address = address & mask;
            this.maskLength = maskLength;
        }

        public String toString() {
            int address = this.address;
            int d = address & 0xFF;
            address >>= 8;
            int c = address & 0xFF;
            address >>= 8;
            int b = address & 0xFF;
            address >>= 8;
            int a = address & 0xFF;
            Object[] args = { a, b, c, d, maskLength };
            return new MessageFormat(FORMAT).format(args);
        }

        private int address;
        private int maskLength;
        private static final String FORMAT = "{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}";
    };

    private static final String[] TESTS = {
        "87.70.141.1/22",
        "36.18.154.103/12",
        "62.62.197.11/29",
        "67.137.119.181/4",
        "161.214.74.21/24",
        "184.232.176.184/18"
    };
}