WeixiangYan/CodeTransOcean huggingface dataset:
Task: Solve a Hopido puzzle





Java: import java.util.*;

public class Hopido {

    final static String[] board = {
        ".00.00.",
        "0000000",
        "0000000",
        ".00000.",
        "..000..",
        "...0..."};

    final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
    {2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
    static int[][] grid;
    static int totalToFill;

    public static void main(String[] args) {
        int nRows = board.length + 6;
        int nCols = board[0].length() + 6;

        grid = new int[nRows][nCols];

        for (int r = 0; r < nRows; r++) {
            Arrays.fill(grid[r], -1);
            for (int c = 3; c < nCols - 3; c++)
                if (r >= 3 && r < nRows - 3) {
                    if (board[r - 3].charAt(c - 3) == '0') {
                        grid[r][c] = 0;
                        totalToFill++;
                    }
                }
        }

        int pos = -1, r, c;
        do {
            do {
                pos++;
                r = pos / nCols;
                c = pos % nCols;
            } while (grid[r][c] == -1);

            grid[r][c] = 1;
            if (solve(r, c, 2))
                break;
            grid[r][c] = 0;

        } while (pos < nRows * nCols);

        printResult();
    }

    static boolean solve(int r, int c, int count) {
        if (count > totalToFill)
            return true;

        List<int[]> nbrs = neighbors(r, c);

        if (nbrs.isEmpty() && count != totalToFill)
            return false;

        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);

        for (int[] nb : nbrs) {
            r = nb[0];
            c = nb[1];
            grid[r][c] = count;
            if (solve(r, c, count + 1))
                return true;
            grid[r][c] = 0;
        }

        return false;
    }

    static List<int[]> neighbors(int r, int c) {
        List<int[]> nbrs = new ArrayList<>();

        for (int[] m : moves) {
            int x = m[0];
            int y = m[1];
            if (grid[r + y][c + x] == 0) {
                int num = countNeighbors(r + y, c + x) - 1;
                nbrs.add(new int[]{r + y, c + x, num});
            }
        }
        return nbrs;
    }

    static int countNeighbors(int r, int c) {
        int num = 0;
        for (int[] m : moves)
            if (grid[r + m[1]][c + m[0]] == 0)
                num++;
        return num;
    }

    static void printResult() {
        for (int[] row : grid) {
            for (int i : row) {
                if (i == -1)
                    System.out.printf("%2s ", ' ');
                else
                    System.out.printf("%2d ", i);
            }
            System.out.println();
        }
    }
}
Task: Solve a Numbrix puzzle





Java: import java.util.*;

public class Numbrix {

    final static String[] board = {
        "00,00,00,00,00,00,00,00,00",
        "00,00,46,45,00,55,74,00,00",
        "00,38,00,00,43,00,00,78,00",
        "00,35,00,00,00,00,00,71,00",
        "00,00,33,00,00,00,59,00,00",
        "00,17,00,00,00,00,00,67,00",
        "00,18,00,00,11,00,00,64,00",
        "00,00,24,21,00,01,02,00,00",
        "00,00,00,00,00,00,00,00,00"};

    final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

    static int[][] grid;
    static int[] clues;
    static int totalToFill;

    public static void main(String[] args) {
        int nRows = board.length + 2;
        int nCols = board[0].split(",").length + 2;
        int startRow = 0, startCol = 0;

        grid = new int[nRows][nCols];
        totalToFill = (nRows - 2) * (nCols - 2);
        List<Integer> lst = new ArrayList<>();

        for (int r = 0; r < nRows; r++) {
            Arrays.fill(grid[r], -1);

            if (r >= 1 && r < nRows - 1) {

                String[] row = board[r - 1].split(",");

                for (int c = 1; c < nCols - 1; c++) {
                    int val = Integer.parseInt(row[c - 1]);
                    if (val > 0)
                        lst.add(val);
                    if (val == 1) {
                        startRow = r;
                        startCol = c;
                    }
                    grid[r][c] = val;
                }
            }
        }

        clues = lst.stream().sorted().mapToInt(i -> i).toArray();

        if (solve(startRow, startCol, 1, 0))
            printResult();
    }

    static boolean solve(int r, int c, int count, int nextClue) {
        if (count > totalToFill)
            return true;

        if (grid[r][c] != 0 && grid[r][c] != count)
            return false;

        if (grid[r][c] == 0 && nextClue < clues.length)
            if (clues[nextClue] == count)
                return false;

        int back = grid[r][c];
        if (back == count)
            nextClue++;

        grid[r][c] = count;
        for (int[] move : moves)
            if (solve(r + move[1], c + move[0], count + 1, nextClue))
                return true;

        grid[r][c] = back;
        return false;
    }

    static void printResult() {
        for (int[] row : grid) {
            for (int i : row) {
                if (i == -1)
                    continue;
                System.out.printf("%2d ", i);
            }
            System.out.println();
        }
    }
}
Task: Sierpinski curve





Java: import java.io.*;

public class SierpinskiCurve {
    public static void main(final String[] args) {
        try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
            SierpinskiCurve s = new SierpinskiCurve(writer);
            s.currentAngle = 45;
            s.currentX = 5;
            s.currentY = 10;
            s.lineLength = 7;
            s.begin(545);
            s.execute(rewrite(5));
            s.end();
        } catch (final Exception ex) {
            ex.printStackTrace();
        }
    }

    private SierpinskiCurve(final Writer writer) {
        this.writer = writer;
    }

    private void begin(final int size) throws IOException {
        write("<svg xmlns='http:
        write("<rect width='100%%' height='100%%' fill='white'/>\n");
        write("<path stroke-width='1' stroke='black' fill='none' d='");
    }

    private void end() throws IOException {
        write("'/>\n</svg>\n");
    }

    private void execute(final String s) throws IOException {
        write("M%g,%g\n", currentX, currentY);
        for (int i = 0, n = s.length(); i < n; ++i) {
            switch (s.charAt(i)) {
                case 'F':
                case 'G':
                    line(lineLength);
                    break;
                case '+':
                    turn(ANGLE);
                    break;
                case '-':
                    turn(-ANGLE);
                    break;
            }
        }
    }

    private void line(final double length) throws IOException {
        final double theta = (Math.PI * currentAngle) / 180.0;
        currentX += length * Math.cos(theta);
        currentY -= length * Math.sin(theta);
        write("L%g,%g\n", currentX, currentY);
    }

    private void turn(final int angle) {
        currentAngle = (currentAngle + angle) % 360;
    }

    private void write(final String format, final Object... args) throws IOException {
        writer.write(String.format(format, args));
    }

    private static String rewrite(final int order) {
        String s = AXIOM;
        for (int i = 0; i < order; ++i) {
            final StringBuilder sb = new StringBuilder();
            for (int j = 0, n = s.length(); j < n; ++j) {
                final char ch = s.charAt(j);
                if (ch == 'X')
                    sb.append(PRODUCTION);
                else
                    sb.append(ch);
            }
            s = sb.toString();
        }
        return s;
    }

    private final Writer writer;
    private double lineLength;
    private double currentX;
    private double currentY;
    private int currentAngle;

    private static final String AXIOM = "F--XF--F--XF";
    private static final String PRODUCTION = "XF+G+XF--F--XF+G+X";
    private static final int ANGLE = 45;
}
Task: Make a backup file





Java: import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
 
public class Backup {
	public static void saveWithBackup(String filename, String... data) 
        throws IOException {
		
		Path file = Paths.get(filename).toRealPath();
		File backFile = new File(filename + ".backup");
		if(!backFile.exists()) {
			
			backFile.createNewFile();
		}
		Path back = Paths.get(filename + ".backup").toRealPath();
		Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
		try(PrintWriter out = new PrintWriter(file.toFile())){
			for(int i = 0; i < data.length; i++) {
				out.print(data[i]);
				if(i < data.length - 1) {
					out.println();
				}
			}
		}
	}

        public static void main(String[] args) {
		try {
			saveWithBackup("original.txt", "fourth", "fifth", "sixth");
		} catch (IOException e) {
			System.err.println(e);
		}
	} 
}
Task: Rosetta Code_Fix code tags





Java: import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class FixCodeTags 
{
	public static void main(String[] args)
	{
		String sourcefile=args[0];
		String convertedfile=args[1];
		convert(sourcefile,convertedfile);
	}
		static String[] languages = {"abap", "actionscript", "actionscript3",
			"ada", "apache", "applescript", "apt_sources", "asm", "asp",
			"autoit", "avisynth", "bar", "bash", "basic4gl", "bf",
			"blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg",
			"cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css",
			"d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email",
			"foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml",
			"gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict",
			"idl", "ini", "inno", "intercal", "io", "java", "java5",
			"javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
			"lolcode", "lotusformulas", "lotusscript", "lscript", "lua",
			"m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml",
			"mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas",
			"oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief",
			"pic16", "pixelbender", "plsql", "povray", "powershell",
			"progress", "prolog", "providex", "python", "qbasic", "rails",
			"reg", "robots", "ruby", "sas", "scala", "scheme", "scilab",
			"sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
			"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet",
			"verilog", "vhdl", "vim", "visualfoxpro", "visualprolog",
			"whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"};
	static void convert(String sourcefile,String convertedfile)
	{
		try
		{
			BufferedReader br=new BufferedReader(new FileReader(sourcefile));
			
			StringBuffer sb=new StringBuffer("");
			String line;
			while((line=br.readLine())!=null)
			{
				for(int i=0;i<languages.length;i++)
				{
					String lang=languages[i];
					line=line.replaceAll("<"+lang+">", "<lang "+lang+">");
					line=line.replaceAll("</"+lang+">", "</"+"lang>");
					line=line.replaceAll("<code "+lang+">", "<lang "+lang+">");
					line=line.replaceAll("</code>", "</"+"lang>");
				}
				sb.append(line);
			}
			br.close();
			
			FileWriter fw=new FileWriter(new File(convertedfile));
			
			fw.write(sb.toString());
			fw.close();
		}
		catch (Exception e)
		{
			System.out.println("Something went horribly wrong: "+e.getMessage());
		}
	}
}
Task: Snake and ladder





Java: import java.util.Map;
import java.util.Random;

public class Game {
    private static final Map<Integer, Integer> snl = Map.ofEntries(
        Map.entry(4, 14),
        Map.entry(9, 31),
        Map.entry(17, 7),
        Map.entry(20, 38),
        Map.entry(28, 84),
        Map.entry(40, 59),
        Map.entry(51, 67),
        Map.entry(54, 34),
        Map.entry(62, 19),
        Map.entry(63, 81),
        Map.entry(64, 60),
        Map.entry(71, 91),
        Map.entry(87, 24),
        Map.entry(93, 73),
        Map.entry(95, 75),
        Map.entry(99, 78)
    );
    private static final boolean sixesThrowAgain = true;
    private static Random rand = new Random();

    private static int turn(int player, int square) {
        int square2 = square;
        while (true) {
            int roll = rand.nextInt(6) + 1;
            System.out.printf("Player %d, on square %d, rolls a %d", player, square2, roll);
            if (square2 + roll > 100) {
                System.out.println(" but cannot move.");
            } else {
                square2 += roll;
                System.out.printf(" and moves to square %d\n", square2);
                if (square2 == 100) return 100;
                Integer next = snl.getOrDefault(square2, square2);
                if (square2 < next) {
                    System.out.printf("Yay! Landed on a ladder. Climb up to %d.\n", next);
                    if (next == 100) return 100;
                    square2 = next;
                } else if (square2 > next) {
                    System.out.printf("Oops! Landed on a snake. Slither down to %d.\n", next);
                    square2 = next;
                }
            }
            if (roll < 6 || !sixesThrowAgain) return square2;
            System.out.println("Rolled a 6 so roll again.");
        }
    }

    public 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) {
                    System.out.printf("Player %d wins!\n", i + 1);
                    return;
                }
                players[i] = ns;
                System.out.println();
            }
        }
    }
}
Task: Naming conventions





Java: 

module shop.acme.com
    {
    
    const Point(Int x, Int y);
    enum Color {Red, Green, Blue}
    interface Callback
        {
        
        Boolean active;
        void onEvent(String event);
        void onError(Exception e);
        }

    
    String DefaultLogin = "guest";
    Int    MAX_QUANTITY = 100;

    
    interface Bag<Element>
            extends Iterable<Element>
        {
        void add(Element e);
        }
    }
Task: Farey sequence





Java: import java.util.TreeSet;

public class Farey{
	private static class Frac implements Comparable<Frac>{
		int num;
		int den;
		
		public Frac(int num, int den){
			this.num = num;
			this.den = den;
		}

		@Override
		public String toString(){
			return num + "/" + den;
		}

		@Override
		public int compareTo(Frac o){
			return Double.compare((double)num / den, (double)o.num / o.den);
		}
	}
	
	public static TreeSet<Frac> genFarey(int i){
		TreeSet<Frac> farey = new TreeSet<Frac>();
		for(int den = 1; den <= i; den++){
			for(int num = 0; num <= den; num++){
				farey.add(new Frac(num, den));
			}
		}
		return farey;
	}
	
	public static void main(String[] args){
		for(int i = 1; i <= 11; i++){
			System.out.println("F" + i + ": " + genFarey(i));
		}
		
		for(int i = 100; i <= 1000; i += 100){
			System.out.println("F" + i + ": " + genFarey(i).size() + " members");
		}
	}
}
Task: Aliquot sequence classifications





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

public class AliquotSequenceClassifications {

    private static Long properDivsSum(long n) {
        return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
    }

    static boolean aliquot(long n, int maxLen, long maxTerm) {
        List<Long> s = new ArrayList<>(maxLen);
        s.add(n);
        long newN = n;

        while (s.size() <= maxLen && newN < maxTerm) {

            newN = properDivsSum(s.get(s.size() - 1));

            if (s.contains(newN)) {

                if (s.get(0) == newN) {

                    switch (s.size()) {
                        case 1:
                            return report("Perfect", s);
                        case 2:
                            return report("Amicable", s);
                        default:
                            return report("Sociable of length " + s.size(), s);
                    }

                } else if (s.get(s.size() - 1) == newN) {
                    return report("Aspiring", s);

                } else
                    return report("Cyclic back to " + newN, s);

            } else {
                s.add(newN);
                if (newN == 0)
                    return report("Terminating", s);
            }
        }

        return report("Non-terminating", s);
    }

    static boolean report(String msg, List<Long> result) {
        System.out.println(msg + ": " + result);
        return false;
    }

    public static void main(String[] args) {
        long[] arr = {
                11, 12, 28, 496, 220, 1184, 12496, 1264460,
                790, 909, 562, 1064, 1488};

        LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));
        System.out.println();
        Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
    }
}
Task: Implicit type conversion





Java: public class ImplicitTypeConversion{
   public static void main(String...args){
      System.out.println( "Primitive conversions" );
      byte  by = -1;
      short sh = by;
      int   in = sh;
      long  lo = in;
      System.out.println( "byte value    -1         to 3 integral types:  " + lo );

      float  fl = 0.1f;
      double db = fl;
      System.out.println( "float value   0.1        to double:            " + db );

      int    in2 = -1;
      float  fl2 = in2;
      double db2 = fl2;
      System.out.println( "int value     -1         to float and double:  " + db2 );

      int    in3 = Integer.MAX_VALUE;
      float  fl3 = in3;
      double db3 = fl3;
      System.out.println( "int value     " + Integer.MAX_VALUE + " to float and double:  " + db3 );

      char   ch  = 'a';
      int    in4 = ch;
      double db4 = in4;
      System.out.println( "char value    '" + ch + "'        to int and double:    " + db4 );

      System.out.println();
      System.out.println( "Boxing and unboxing" );
      Integer in5 = -1;
      int     in6 = in5;
      System.out.println( "int  value    -1         to Integer and int:   " + in6 );

      Double db5 = 0.1;
      double db6 = db5;
      System.out.println( "double value  0.1        to Double and double: " + db6 );
   }
}
Task: Mersenne primes





Java: import java.math.BigInteger;

public class MersennePrimes {
    private static final int MAX = 20;

    private static final BigInteger ONE = BigInteger.ONE;
    private static final BigInteger TWO = BigInteger.valueOf(2);

    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) {
        int count = 0;
        int p = 2;
        while (true) {
            BigInteger m = TWO.shiftLeft(p - 1).subtract(ONE);
            if (m.isProbablePrime(10)) {
                System.out.printf("2 ^ %d - 1\n", p);
                if (++count == MAX) break;
            }
            
            do {
                p = (p > 2) ? p + 2 : 3;
            } while (!isPrime(p));
        }
    }
}
Task: Sexy primes





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

public class SexyPrimes {

    public static void main(String[] args) {
        sieve();
        int pairs = 0;
        List<String> pairList = new ArrayList<>();
        int triples = 0;
        List<String> tripleList = new ArrayList<>();
        int quadruplets = 0;
        List<String> quadrupletList = new ArrayList<>();
        int unsexyCount = 1;  
        List<String> unsexyList = new ArrayList<>();
        for ( int i = 3 ; i < MAX ; i++ ) {
            if ( i-6 >= 3 && primes[i-6] && primes[i] ) {
                pairs++;
                pairList.add((i-6) + " " + i);
                if ( pairList.size() > 5 ) {
                    pairList.remove(0);
                }
            }
            else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {
                unsexyCount++;
                unsexyList.add("" + i);
                if ( unsexyList.size() > 10 ) {
                    unsexyList.remove(0);
                }
            }
            if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {
                triples++;
                tripleList.add((i-12) + " " + (i-6) + " " + i);
                if ( tripleList.size() > 5 ) {
                    tripleList.remove(0);
                }
            }
            if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {
                quadruplets++;
                quadrupletList.add((i-18) + " " + (i-12) + " " + (i-6) + " " + i);
                if ( quadrupletList.size() > 5 ) {
                    quadrupletList.remove(0);
                }
            }
        }
        System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, pairs);
        System.out.printf("The last 5 sexy pairs:%n  %s%n%n", pairList.toString().replaceAll(", ", "], ["));
        System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, triples);
        System.out.printf("The last 5 sexy triples:%n  %s%n%n", tripleList.toString().replaceAll(", ", "], ["));
        System.out.printf("Count of sexy quadruplets less than %,d = %,d%n", MAX, quadruplets);
        System.out.printf("The last 5 sexy quadruplets:%n  %s%n%n", quadrupletList.toString().replaceAll(", ", "], ["));
        System.out.printf("Count of unsexy primes less than %,d = %,d%n", MAX, unsexyCount);
        System.out.printf("The last 10 unsexy primes:%n  %s%n%n", unsexyList.toString().replaceAll(", ", "], ["));
    }

    private static int MAX = 1_000_035;
    private static boolean[] primes = new boolean[MAX];

    private static final void sieve() {
        
        for ( int i = 2 ; i < MAX ; i++ ) {
            primes[i] = true;            
        }
        for ( int i = 2 ; i < MAX ; i++ ) {
            if ( primes[i] ) {
                for ( int j = 2*i ; j < MAX ; j += i ) {
                    primes[j] = false;
                }
            }
        }
    }

}
Task: Taxicab numbers





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

class CubeSum implements Comparable<CubeSum> {
	public long x, y, value;

	public CubeSum(long x, long y) {
		this.x = x;
		this.y = y;
		this.value = x*x*x + y*y*y;
	}

	public String toString() {
		return String.format("%4d^3 + %4d^3", x, y);
	}

	public int compareTo(CubeSum that) {
		return value < that.value ? -1 : value > that.value ? 1 : 0;
	}
}

class SumIterator implements Iterator<CubeSum> {
	PriorityQueue<CubeSum> pq = new PriorityQueue<CubeSum>();
	long n = 0;

	public boolean hasNext() { return true; }
	public CubeSum next() {
		while (pq.size() == 0 || pq.peek().value >= n*n*n)
			pq.add(new CubeSum(++n, 1));

		CubeSum s = pq.remove();
		if (s.x > s.y + 1) pq.add(new CubeSum(s.x, s.y+1));

		return s;
	}
}

class TaxiIterator implements Iterator<List<CubeSum>> {
	Iterator<CubeSum> sumIterator = new SumIterator();
	CubeSum last = sumIterator.next();

	public boolean hasNext() { return true; }
	public List<CubeSum> next() {
		CubeSum s;
		List<CubeSum> train = new ArrayList<CubeSum>();

		while ((s = sumIterator.next()).value != last.value)
			last = s;

		train.add(last);

		do { train.add(s); } while ((s = sumIterator.next()).value == last.value);
		last = s;

		return train;
	}
}
	
public class Taxi {
	public static final void main(String[] args) {
		Iterator<List<CubeSum>> taxi = new TaxiIterator();

		for (int i = 1; i <= 2006; i++) {
			List<CubeSum> t = taxi.next();
			if (i > 25 && i < 2000) continue;

			System.out.printf("%4d: %10d", i, t.get(0).value);
			for (CubeSum s: t)
				System.out.print(" = " + s);
			System.out.println();
		}
	}
}