WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Permutation sort





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

public class PermutationSort 
{
	public static void main(String[] args)
	{
		int[] a={3,2,1,8,9,4,6};
		System.out.println("Unsorted: " + Arrays.toString(a));
		a=pSort(a);
		System.out.println("Sorted: " + Arrays.toString(a));
	}
	public static int[] pSort(int[] a)
	{
		List<int[]> list=new ArrayList<int[]>();
		permute(a,a.length,list);
		for(int[] x : list)
			if(isSorted(x))
				return x;
		return a;
	}
	private static void permute(int[] a, int n, List<int[]> list) 
	{
		if (n == 1) 
		{
			int[] b=new int[a.length];
			System.arraycopy(a, 0, b, 0, a.length);
			list.add(b);
		    return;
		}
		for (int i = 0; i < n; i++) 
		{
		        swap(a, i, n-1);
		        permute(a, n-1, list);
		        swap(a, i, n-1);
		 }
	}
	private static boolean isSorted(int[] a)
	{
		for(int i=1;i<a.length;i++)
			if(a[i-1]>a[i])
				return false;
		return true;
	}
	private static void swap(int[] arr,int i, int j)
	{
		int temp=arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
	}
}
Task: Integer roots





Java: import java.math.BigInteger;

public class IntegerRoots {
    private static BigInteger iRoot(BigInteger base, int n) {
        if (base.compareTo(BigInteger.ZERO) < 0 || n <= 0) {
            throw new IllegalArgumentException();
        }

        int n1 = n - 1;
        BigInteger n2 = BigInteger.valueOf(n);
        BigInteger n3 = BigInteger.valueOf(n1);
        BigInteger c = BigInteger.ONE;
        BigInteger d = n3.add(base).divide(n2);
        BigInteger e = n3.multiply(d).add(base.divide(d.pow(n1))).divide(n2);
        while (!c.equals(d) && !c.equals(e)) {
            c = d;
            d = e;
            e = n3.multiply(e).add(base.divide(e.pow(n1))).divide(n2);
        }
        if (d.compareTo(e) < 0) {
            return d;
        }
        return e;
    }

    public static void main(String[] args) {
        BigInteger b = BigInteger.valueOf(8);
        System.out.print("3rd integer root of 8 = ");
        System.out.println(iRoot(b, 3));

        b = BigInteger.valueOf(9);
        System.out.print("3rd integer root of 9 = ");
        System.out.println(iRoot(b, 3));

        b = BigInteger.valueOf(100).pow(2000).multiply(BigInteger.valueOf(2));
        System.out.print("First 2001 digits of the square root of 2: ");
        System.out.println(iRoot(b, 2));
    }
}
Task: Nice primes





Java: public class NicePrimes {
    private static boolean isPrime(long n) {
        if (n < 2) {
            return false;
        }
        if (n % 2 == 0L) {
            return n == 2L;
        }
        if (n % 3 == 0L) {
            return n == 3L;
        }

        var p = 5L;
        while (p * p <= n) {
            if (n % p == 0L) {
                return false;
            }
            p += 2;
            if (n % p == 0L) {
                return false;
            }
            p += 4;
        }
        return true;
    }

    private static long digitalRoot(long n) {
        if (n == 0) {
            return 0;
        }
        return 1 + (n - 1) % 9;
    }

    public static void main(String[] args) {
        final long from = 500;
        final long to = 1000;
        int count = 0;

        System.out.printf("Nice primes between %d and %d%n", from, to);
        long n = from;
        while (n < to) {
            if (isPrime(digitalRoot(n)) && isPrime(n)) {
                count++;
                System.out.print(n);
                if (count % 10 == 0) {
                    System.out.println();
                } else {
                    System.out.print(' ');
                }
            }

            n++;
        }
        System.out.println();
        System.out.printf("%d nice primes found.%n", count);
    }
}
Task: Find the last Sunday of each month





Java: import java.util.Scanner;

public class LastSunday 
{
	static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"};
	
	public static int[] findLastSunday(int year)
	{
		boolean isLeap = isLeapYear(year);
		
		int[] days={31,isLeap?29:28,31,30,31,30,31,31,30,31,30,31};
		int[] lastDay=new int[12];
		
		for(int m=0;i<12;i++)
		{
			int d;
			for(d=days[m]; getWeekDay(year,m,d)!=0; d--)
				;
			lastDay[m]=d;
		}
		
		return lastDay;
	}
	
	private static boolean isLeapYear(int year)
	{
		if(year%4==0)
		{
			if(year%100!=0)
				return true;
			else if (year%400==0)
				return true;
		}
		return false;
	}
	
	private static int getWeekDay(int y, int m, int d)
	{
		int f=y+d+3*m-1;
		m++;
		
		if(m<3)
			y--;
		else
			f-=(int)(0.4*m+2.3);
		
		f+=(int)(y/4)-(int)((y/100+1)*0.75);
		f%=7;
		
		return f;
	}
	
	private static void display(int year, int[] lastDay)
	{
		System.out.println("\nYEAR: "+year);
		for(int m=0;i<12;i++)
			System.out.println(months[m]+": "+lastDay[m]);
	}
	
	public static void main(String[] args) throws Exception
	{
		System.out.print("Enter year: ");
		Scanner s=new Scanner(System.in);
		
		int y=Integer.parseInt(s.next());
		
		int[] lastDay = findLastSunday(y);
		display(y, lastDay);
		
		s.close();
	}
}
Task: Random Latin squares





Java: import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

public class RandomLatinSquares {
    private static void printSquare(List<List<Integer>> latin) {
        for (List<Integer> row : latin) {
            Iterator<Integer> it = row.iterator();

            System.out.print("[");
            if (it.hasNext()) {
                Integer col = it.next();
                System.out.print(col);
            }
            while (it.hasNext()) {
                Integer col = it.next();
                System.out.print(", ");
                System.out.print(col);
            }
            System.out.println("]");
        }
        System.out.println();
    }

    private static void latinSquare(int n) {
        if (n <= 0) {
            System.out.println("[]");
            return;
        }

        List<List<Integer>> latin = new ArrayList<>(n);
        for (int i = 0; i < n; ++i) {
            List<Integer> inner = new ArrayList<>(n);
            for (int j = 0; j < n; ++j) {
                inner.add(j);
            }
            latin.add(inner);
        }
        
        Collections.shuffle(latin.get(0));

        
        for (int i = 1; i < n - 1; ++i) {
            boolean shuffled = false;
            shuffling:
            while (!shuffled) {
                Collections.shuffle(latin.get(i));
                for (int k = 0; k < i; ++k) {
                    for (int j = 0; j < n; ++j) {
                        if (Objects.equals(latin.get(k).get(j), latin.get(i).get(j))) {
                            continue shuffling;
                        }
                    }
                }
                shuffled = true;
            }
        }

        
        for (int j = 0; j < n; ++j) {
            List<Boolean> used = new ArrayList<>(n);
            for (int i = 0; i < n; ++i) {
                used.add(false);
            }
            for (int i = 0; i < n - 1; ++i) {
                used.set(latin.get(i).get(j), true);
            }
            for (int k = 0; k < n; ++k) {
                if (!used.get(k)) {
                    latin.get(n - 1).set(j, k);
                    break;
                }
            }
        }

        printSquare(latin);
    }

    public static void main(String[] args) {
        latinSquare(5);
        latinSquare(5);
        latinSquare(10);
    }
}
Task: Teacup rim text





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

public class Teacup {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("usage: java Teacup dictionary");
            System.exit(1);
        }
        try {
            findTeacupWords(loadDictionary(args[0]));
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }

    
    private static Set<String> loadDictionary(String fileName) throws IOException {
        Set<String> words = new TreeSet<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String word;
            while ((word = reader.readLine()) != null)
                words.add(word);
            return words;
        }
    }

    private static void findTeacupWords(Set<String> words) {
        List<String> teacupWords = new ArrayList<>();
        Set<String> found = new HashSet<>();
        for (String word : words) {
            int len = word.length();
            if (len < 3 || found.contains(word))
                continue;
            teacupWords.clear();
            teacupWords.add(word);
            char[] chars = word.toCharArray();
            for (int i = 0; i < len - 1; ++i) {
                String rotated = new String(rotate(chars));
                if (rotated.equals(word) || !words.contains(rotated))
                    break;
                teacupWords.add(rotated);
            }
            if (teacupWords.size() == len) {
                found.addAll(teacupWords);
                System.out.print(word);
                for (int i = 1; i < len; ++i)
                    System.out.print(" " + teacupWords.get(i));
                System.out.println();
            }
        }
    }

    private static char[] rotate(char[] ch) {
        char c = ch[0];
        System.arraycopy(ch, 1, ch, 0, ch.length - 1);
        ch[ch.length - 1] = c;
        return ch;
    }
}
Task: Fairshare between two and more





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

public class FairshareBetweenTwoAndMore {

    public static void main(String[] args) {
        for ( int base : Arrays.asList(2, 3, 5, 11) ) {
            System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base));
        }
    }
    
    private static List<Integer> thueMorseSequence(int terms, int base) {
        List<Integer> sequence = new ArrayList<Integer>();
        for ( int i = 0 ; i < terms ; i++ ) {
            int sum = 0;
            int n = i;
            while ( n > 0 ) {
                
                sum += n % base;
                n /= base;
            }
            
            sequence.add(sum % base);
        }
        return sequence;
    }

}
Task: Permutations by swapping





Java: package org.rosettacode.java;

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

public class HeapsAlgorithm {

	public static void main(String[] args) {
		Object[] array = IntStream.range(0, 4)
				.boxed()
				.toArray();
		HeapsAlgorithm algorithm = new HeapsAlgorithm();
		algorithm.recursive(array);
		System.out.println();
		algorithm.loop(array);
	}

	void recursive(Object[] array) {
		recursive(array, array.length, true);
	}

	void recursive(Object[] array, int n, boolean plus) {
		if (n == 1) {
			output(array, plus);
		} else {
			for (int i = 0; i < n; i++) {
				recursive(array, n - 1, i == 0);
				swap(array, n % 2 == 0 ? i : 0, n - 1);
			}
		}
	}

	void output(Object[] array, boolean plus) {
		System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1"));
	}

	void swap(Object[] array, int a, int b) {
		Object o = array[a];
		array[a] = array[b];
		array[b] = o;
	}

	void loop(Object[] array) {
		loop(array, array.length);
	}

	void loop(Object[] array, int n) {
		int[] c = new int[n];
		output(array, true);
		boolean plus = false;
		for (int i = 0; i < n; ) {
			if (c[i] < i) {
				if (i % 2 == 0) {
					swap(array, 0, i);
				} else {
					swap(array, c[i], i);
				}
				output(array, plus);
				plus = !plus;
				c[i]++;
				i = 0;
			} else {
				c[i] = 0;
				i++;
			}
		}
	}
}
Task: RPG attributes generator





Java: import java.util.List;
import java.util.Random;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

public class Rpg {

    private static final Random random = new Random();
 
    public static int genAttribute() {
        return random.ints(1, 6 + 1) 
            .limit(4) 
            .sorted() 
            .limit(3) 
            .sum();   
    }
 
    public static void main(String[] args) {
        while (true) {
            List<Integer> stats =
                Stream.generate(Rpg::genAttribute) 
                    .limit(6) 
                    .collect(toList()); 
            int sum = stats.stream().mapToInt(Integer::intValue).sum();
            long count = stats.stream().filter(v -> v >= 15).count();
            if (count >= 2 && sum >= 75) {
                System.out.printf("The 6 random numbers generated are: %s\n", stats);
                System.out.printf("Their sum is %s and %s of them are >= 15\n", sum, count);
                return;
            }      
        }
    }
}
Task: Kolakoski sequence





Java: import java.util.Arrays;

public class Kolakoski {
    private static class Crutch {
        final int len;
        int[] s;
        int i;

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

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

    private static int nextInCycle(final int[] self, int index) {
        return self[index % self.length];
    }

    private static int[] kolakoski(final int[] self, int len) {
        Crutch c = new Crutch(len);

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

    private static boolean possibleKolakoski(final 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 void main(String[] args) {
        int[][] ias = new int[][]{
            new int[]{1, 2},
            new int[]{2, 1},
            new int[]{1, 3, 1, 2},
            new int[]{1, 3, 2, 1}
        };
        int[] lens = new int[]{20, 20, 30, 30};

        for (int i=0; i<ias.length; i++) {
            int len = lens[i];
            int[] kol = kolakoski(ias[i], len);

            System.out.printf("First %d members of the sequence generated by %s: \n", len, Arrays.toString(ias[i]));
            System.out.printf("%s\n", Arrays.toString(kol));
            System.out.printf("Possible Kolakoski sequence? %s\n\n", possibleKolakoski(kol));
        }
    }
}
Task: Sequence_ smallest number with exactly n divisors





Java: import java.util.Arrays;

public class OEIS_A005179 {

    static int count_divisors(int n) {
        int count = 0;
        for (int i = 1; i * i <= n; ++i) {
            if (n % i == 0) {
                if (i == n / i)
                    count++;
                else
                    count += 2;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        final int max = 15;
        int[] seq = new int[max];
        System.out.printf("The first %d terms of the sequence are:\n", max);
        for (int i = 1, n = 0; n < max; ++i) {
            int k = count_divisors(i);
            if (k <= max && seq[k - 1] == 0) {        
                seq[k- 1] = i;
                n++;
            }
        }
        System.out.println(Arrays.toString(seq));
    }
}
Task: Sparkline in unicode





Java: public class Sparkline 
{
	String bars="▁▂▃▄▅▆▇█";
	public static void main(String[] args)
	{
		Sparkline now=new Sparkline();
		float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
		now.display1D(arr);
		System.out.println(now.getSparkline(arr));
		float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};
		now.display1D(arr1);
		System.out.println(now.getSparkline(arr1));
	}
	public void display1D(float[] arr)
	{
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}
	public String getSparkline(float[] arr)
	{
		float min=Integer.MAX_VALUE;
		float max=Integer.MIN_VALUE;
		for(int i=0;i<arr.length;i++)
		{
			if(arr[i]<min)
				min=arr[i];
			if(arr[i]>max)
				max=arr[i];
		}
		float range=max-min;
		int num=bars.length()-1;
		String line="";
		for(int i=0;i<arr.length;i++)
		{
			
			line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));
		}
		return line;
	}
}
Task: Levenshtein distance_Alignment





Java: public class LevenshteinAlignment {

    public static String[] alignment(String a, String b) {
        a = a.toLowerCase();
        b = b.toLowerCase();
        
        int[][] costs = new int[a.length()+1][b.length()+1];
        for (int j = 0; j <= b.length(); j++)
            costs[0][j] = j;
        for (int i = 1; i <= a.length(); i++) {
            costs[i][0] = i;
            for (int j = 1; j <= b.length(); j++) {
                costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1);
            }
        }

	
	StringBuilder aPathRev = new StringBuilder();
	StringBuilder bPathRev = new StringBuilder();
	for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) {
	    if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) {
		aPathRev.append(a.charAt(--i));
		bPathRev.append(b.charAt(--j));
	    } else if (costs[i][j] == 1 + costs[i-1][j]) {
		aPathRev.append(a.charAt(--i));
		bPathRev.append('-');
	    } else if (costs[i][j] == 1 + costs[i][j-1]) {
		aPathRev.append('-');
		bPathRev.append(b.charAt(--j));
	    }
	}
        return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()};
    }

    public static void main(String[] args) {
	String[] result = alignment("rosettacode", "raisethysword");
	System.out.println(result[0]);
	System.out.println(result[1]);
    }
}
Task: Longest increasing subsequence





Java: import java.util.*;

public class LIS {
    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {
        List<Node<E>> pileTops = new ArrayList<Node<E>>();
        
        for (E x : n) {
	    Node<E> node = new Node<E>();
	    node.value = x;
            int i = Collections.binarySearch(pileTops, node);
            if (i < 0) i = ~i;
	    if (i != 0)
		node.pointer = pileTops.get(i-1);
            if (i != pileTops.size())
                pileTops.set(i, node);
            else
                pileTops.add(node);
        }
	
	List<E> result = new ArrayList<E>();
	for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);
                node != null; node = node.pointer)
	    result.add(node.value);
	Collections.reverse(result);
	return result;
    }

    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {
	public E value;
	public Node<E> pointer;
        public int compareTo(Node<E> y) { return value.compareTo(y.value); }
    }

    public static void main(String[] args) {
	List<Integer> d = Arrays.asList(3,2,6,4,5,1);
	System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);
	System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
    }
}
Task: Words from neighbour ones





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

public class NeighbourWords {
    public static void main(String[] args) {
        try {
            int minLength = 9;
            List<String> words = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.length() >= minLength)
                        words.add(line);
                }
            }
            Collections.sort(words);
            String previousWord = null;
            int count = 0;
            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {
                StringBuilder sb = new StringBuilder(minLength);
                for (int j = 0; j < minLength; ++j)
                    sb.append(words.get(i + j).charAt(j));
                String word = sb.toString();
                if (word.equals(previousWord))
                    continue;
                if (Collections.binarySearch(words, word) >= 0)
                    System.out.printf("%2d. %s\n", ++count, word);
                previousWord = word;
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }
}
Task: Dynamic variable names





Java: public static void main(String... args){
        HashMap<String, Integer> vars = new HashMap<String, Integer>();
        
        
        
        vars.put("Variable name", 3); 
        vars.put("Next variable name", 5);
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        vars.put(str, sc.nextInt()); 
        
        System.out.println(vars.get("Variable name")); 
        System.out.println(vars.get(str));
}
Task: Square root by hand





Java: import java.math.BigInteger;

public class SquareRoot {
    public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);
    public static final BigInteger TWENTY = BigInteger.valueOf(20);

    public static void main(String[] args) {
        var i = BigInteger.TWO;
        var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));
        var k = j;
        var d = j;
        int n = 500;
        int n0 = n;
        do {
            System.out.print(d);
            i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);
            k = TWENTY.multiply(j);
            for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {
                if (k.add(d).multiply(d).compareTo(i) > 0) {
                    d = d.subtract(BigInteger.ONE);
                    break;
                }
            }
            j = j.multiply(BigInteger.TEN).add(d);
            k = k.add(d);
            if (n0 > 0) {
                n--;
            }
        } while (n > 0);
        System.out.println();
    }
}
Task: Order disjoint list items





Java: import java.util.Arrays;
import java.util.BitSet;
import org.apache.commons.lang3.ArrayUtils;

public class OrderDisjointItems {

    public static void main(String[] args) {
        final String[][] MNs = {{"the cat sat on the mat", "mat cat"},
        {"the cat sat on the mat", "cat mat"},
        {"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"},
        {"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}};

        for (String[] a : MNs) {
            String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" "));
            System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r));
        }
    }

    
    static String[] orderDisjointItems(String[] m, String[] n) {
        for (String e : n) {
            int idx = ArrayUtils.indexOf(m, e);
            if (idx != -1)
                m[idx] = null;
        }
        for (int i = 0, j = 0; i < m.length; i++) {
            if (m[i] == null)
                m[i] = n[j++];
        }
        return m;
    }

    
    static String[] orderDisjointItems2(String[] m, String[] n) {
        BitSet bitSet = new BitSet(m.length);
        for (String e : n) {
            int idx = -1;
            do {
                idx = ArrayUtils.indexOf(m, e, idx + 1);
            } while (idx != -1 && bitSet.get(idx));
            if (idx != -1)
                bitSet.set(idx);
        }
        for (int i = 0, j = 0; i < m.length; i++) {
            if (bitSet.get(i))
                m[i] = n[j++];
        }
        return m;
    }
}