WeixiangYan/CodeTransOcean huggingface dataset:
Task: Magic squares of odd order

C: #include <stdio.h>
#include <stdlib.h>
 
int f(int n, int x, int y)
{
	return (x + y*2 + 1)%n;
}
 
int main(int argc, char **argv)
{
	int i, j, n;
 
	
	if(argc!=2) return 1;

	
	n = atoi(argv[1]);
	if (n < 3 || (n%2) == 0) return 2;
 
	for (i = 0; i < n; i++) {
		for (j = 0; j < n; j++)
			printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1);
		putchar('\n');
	}
	printf("\n Magic Constant: %d.\n", (n*n+1)/2*n);
 
	return 0;
}





Java: public class MagicSquare {

    public static void main(String[] args) {
        int n = 5;
        for (int[] row : magicSquareOdd(n)) {
            for (int x : row)
                System.out.format("%2s ", x);
            System.out.println();
        }
        System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
    }

    public static int[][] magicSquareOdd(final int base) {
        if (base % 2 == 0 || base < 3)
            throw new IllegalArgumentException("base must be odd and > 2");

        int[][] grid = new int[base][base];
        int r = 0, number = 0;
        int size = base * base;

        int c = base / 2;
        while (number++ < size) {
            grid[r][c] = number;
            if (r == 0) {
                if (c == base - 1) {
                    r++;
                } else {
                    r = base - 1;
                    c++;
                }
            } else {
                if (c == base - 1) {
                    r--;
                    c = 0;
                } else {
                    if (grid[r - 1][c + 1] == 0) {
                        r--;
                        c++;
                    } else {
                        r++;
                    }
                }
            }
        }
        return grid;
    }
}
Task: Cut a rectangle

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef unsigned char byte;
byte *grid = 0;

int w, h, len;
unsigned long long cnt;

static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
	int i, t;

	if (!y || y == h || !x || x == w) {
		cnt += 2;
		return;
	}

	t = y * (w + 1) + x;
	grid[t]++, grid[len - t]++;

	for (i = 0; i < 4; i++)
		if (!grid[t + next[i]])
			walk(y + dir[i][0], x + dir[i][1]);

	grid[t]--, grid[len - t]--;
}

unsigned long long solve(int hh, int ww, int recur)
{
	int t, cx, cy, x;

	h = hh, w = ww;

	if (h & 1) t = w, w = h, h = t;
	if (h & 1) return 0;
	if (w == 1) return 1;
	if (w == 2) return h;
	if (h == 2) return w;

	cy = h / 2, cx = w / 2;

	len = (h + 1) * (w + 1);
	grid = realloc(grid, len);
	memset(grid, 0, len--);

	next[0] = -1;
	next[1] = -w - 1;
	next[2] = 1;
	next[3] = w + 1;

	if (recur) cnt = 0;
	for (x = cx + 1; x < w; x++) {
		t = cy * (w + 1) + x;
		grid[t] = 1;
		grid[len - t] = 1;
		walk(cy - 1, x);
	}
	cnt++;

	if (h == w)
		cnt *= 2;
	else if (!(w & 1) && recur)
		solve(w, h, 0);

	return cnt;
}

int main()
{
	int y, x;
	for (y = 1; y <= 10; y++)
		for (x = 1; x <= y; x++)
			if (!(x & 1) || !(y & 1))
				printf("%d x %d: %llu\n", y, x, solve(y, x, 1));

	return 0;
}





Java: import java.util.*;

public class CutRectangle {

    private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};

    public static void main(String[] args) {
        cutRectangle(2, 2);
        cutRectangle(4, 3);
    }

    static void cutRectangle(int w, int h) {
        if (w % 2 == 1 && h % 2 == 1)
            return;

        int[][] grid = new int[h][w];
        Stack<Integer> stack = new Stack<>();

        int half = (w * h) / 2;
        long bits = (long) Math.pow(2, half) - 1;

        for (; bits > 0; bits -= 2) {

            for (int i = 0; i < half; i++) {
                int r = i / w;
                int c = i % w;
                grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
                grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
            }

            stack.push(0);
            grid[0][0] = 2;
            int count = 1;
            while (!stack.empty()) {

                int pos = stack.pop();
                int r = pos / w;
                int c = pos % w;

                for (int[] dir : dirs) {

                    int nextR = r + dir[0];
                    int nextC = c + dir[1];

                    if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {

                        if (grid[nextR][nextC] == 1) {
                            stack.push(nextR * w + nextC);
                            grid[nextR][nextC] = 2;
                            count++;
                        }
                    }
                }
            }
            if (count == half) {
                printResult(grid);
            }
        }
    }

    static void printResult(int[][] arr) {
        for (int[] a : arr)
            System.out.println(Arrays.toString(a));
        System.out.println();
    }
}
Task: Order by pair comparisons

C: #include <stdio.h>
#include <string.h>
#include <stdlib.h>

int interactiveCompare(const void *x1, const void *x2)
{
  const char *s1 = *(const char * const *)x1;
  const char *s2 = *(const char * const *)x2;
  static int count = 0;
  printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2);
  int response;
  scanf("%d", &response);
  return response;
}

void printOrder(const char *items[], int len)
{
  printf("{ ");
  for (int i = 0; i < len; ++i) printf("%s ", items[i]);
  printf("}\n");
}

int main(void)
{
  const char *items[] =
    {
      "violet", "red", "green", "indigo", "blue", "yellow", "orange"
    };

  qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);
  printOrder(items, sizeof(items)/sizeof(*items));
  return 0;
}





Java: import java.util.*;

public class SortComp1 {
    public static void main(String[] args) {
        List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
        List<String> sortedItems = new ArrayList<>();
        Comparator<String> interactiveCompare = new Comparator<String>() {
                int count = 0;
                Scanner s = new Scanner(System.in);
                public int compare(String s1, String s2) {
                    System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2);
                    return s.nextInt();
                }
            };
        for (String item : items) {
            System.out.printf("Inserting '%s' into %s\n", item, sortedItems);
            int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);
            
            
            if (spotToInsert < 0) spotToInsert = ~spotToInsert;
            sortedItems.add(spotToInsert, item);
        }
        System.out.println(sortedItems);
    }
}
Task: Benford's law

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>

float *benford_distribution(void)
{
    static float prob[9];
    for (int i = 1; i < 10; i++)
        prob[i - 1] = log10f(1 + 1.0 / i);

    return prob;
}

float *get_actual_distribution(char *fn)
{
    FILE *input = fopen(fn, "r");
    if (!input)
    {
        perror("Can't open file");
        exit(EXIT_FAILURE);
    }

    int tally[9] = { 0 };
    char c;
    int total = 0;
    while ((c = getc(input)) != EOF)
    {
        
        while (c < '1' || c > '9')
            c = getc(input);

        tally[c - '1']++;
        total++;

        
        while ((c = getc(input)) != '\n' && c != EOF)
            ;
    }
    fclose(input);
    
    static float freq[9];
    for (int i = 0; i < 9; i++)
        freq[i] = tally[i] / (float) total;

    return freq;
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        printf("Usage: benford <file>\n");
        return EXIT_FAILURE;
    }

    float *actual = get_actual_distribution(argv[1]);
    float *expected = benford_distribution();  

    puts("digit\tactual\texpected");
    for (int i = 0; i < 9; i++)
        printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]);

    return EXIT_SUCCESS;
}





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

public class BenfordsLaw {

    private static BigInteger[] generateFibonacci(int n) {
        BigInteger[] fib = new BigInteger[n];
        fib[0] = BigInteger.ONE;
        fib[1] = BigInteger.ONE;
        for (int i = 2; i < fib.length; i++) {
            fib[i] = fib[i - 2].add(fib[i - 1]);
        }
        return fib;
    }

    public static void main(String[] args) {
        BigInteger[] numbers = generateFibonacci(1000);

        int[] firstDigits = new int[10];
        for (BigInteger number : numbers) {
            firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
        }

        for (int i = 1; i < firstDigits.length; i++) {
            System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
                    i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
        }
    }
}
Task: Nautical bell

C: #include<unistd.h>
#include<stdio.h>
#include<time.h>

#define SHORTLAG 1000
#define LONGLAG  2000

int main(){
	int i,times,hour,min,sec,min1,min2;
	
	time_t t;
	struct tm* currentTime;
	
	while(1){
		time(&t);
		currentTime = localtime(&t);
		
		hour = currentTime->tm_hour;
		min = currentTime->tm_min;
		sec = currentTime->tm_sec;
		
		hour = 12;
		min = 0;
		sec = 0;
		
		if((min==0 || min==30) && sec==0)
			times = ((hour*60 + min)%240)%8;
		if(times==0){
			times = 8;
		}	

		if(min==0){
			min1 = 0;
			min2 = 0;
		}
		
		else{
			min1 = 3;
			min2 = 0;
		}
		
		if((min==0 || min==30) && sec==0){
			printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times);
		
			for(i=1;i<=times;i++){
				printf("\a");
				
				(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);
			}
		}
	}
	return 0;
}





Java: import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class NauticalBell extends Thread {

    public static void main(String[] args) {
        NauticalBell bells = new NauticalBell();
        bells.setDaemon(true);
        bells.start();
        try {
            bells.join();
        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }

    @Override
    public void run() {
        DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        int numBells = 0;
        long time = System.currentTimeMillis();
        long next = time - (time % (24 * 60 * 60 * 1000)); 

        while (next < time) {
            next += 30 * 60 * 1000; 
            numBells = 1 + (numBells % 8);
        }

        while (true) {
            long wait = 100L;
            time = System.currentTimeMillis();
            if (time - next >= 0) {
                String bells = numBells == 1 ? "bell" : "bells";
                String timeString = sdf.format(time);
                System.out.printf("%s : %d %s\n", timeString, numBells, bells);
                next += 30 * 60 * 1000;
                wait = next - time;
                numBells = 1 + (numBells % 8);
            }
            try {
                Thread.sleep(wait);
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}
Task: Anonymous recursion

C: #include <stdio.h>

long fib(long x)
{
        long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };
        if (x < 0) {
                printf("Bad argument: fib(%ld)\n", x);
                return -1;
        }
        return fib_i(x);
}

long fib_i(long n) 
{
        printf("This is not the fib you are looking for\n");
        return -1;
}

int main()
{
        long x;
        for (x = -1; x < 4; x ++)
                printf("fib %ld = %ld\n", x, fib(x));

        printf("calling fib_i from outside fib:\n");
        fib_i(3);

        return 0;
}





Java: public static long fib(int n) {
    if (n < 0)
        throw new IllegalArgumentException("n can not be a negative number");

    return new Object() {
        private long fibInner(int n) {
            return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));
        }
    }.fibInner(n);
}
Task: Substring_Top and tail

C: #include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main( int argc, char ** argv ){
  const char * str_a = "knight";
  const char * str_b = "socks";
  const char * str_c = "brooms";

  char * new_a = malloc( strlen( str_a ) - 1 );
  char * new_b = malloc( strlen( str_b ) - 1 );
  char * new_c = malloc( strlen( str_c ) - 2 );

  strcpy( new_a, str_a + 1 );
  strncpy( new_b, str_b, strlen( str_b ) - 1 );
  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );

  printf( "%s\n%s\n%s\n", new_a, new_b, new_c );

  free( new_a );
  free( new_b );
  free( new_c );

  return 0;
}





Java: String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);


String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
Task: Use another language to call a function

C: #include <stdio.h>

extern int Query (char * Data, size_t * Length);

int main (int argc, char * argv [])
{
   char     Buffer [1024];
   size_t   Size = sizeof (Buffer);
   
   if (0 == Query (Buffer, &Size))
   {
      printf ("failed to call Query\n");
   }
   else
   {
      char * Ptr = Buffer;
      while (Size-- > 0) putchar (*Ptr++);
      putchar ('\n');
   }
}





Java: 
public class Query {
    public static boolean call(byte[] data, int[] length)
	throws java.io.UnsupportedEncodingException
    {
	String message = "Here am I";
	byte[] mb = message.getBytes("utf-8");
	if (length[0] < mb.length)
	    return false;
	length[0] = mb.length;
	System.arraycopy(mb, 0, data, 0, mb.length);
	return true;
    }
}
Task: Longest string challenge

C: #include <stdio.h>
#include <string.h>
 
int cmp(const char *p, const char *q)
{
	while (*p && *q) p = &p[1], q = &q[1];
	return *p;
}
 
int main()
{
	char line[65536];
	char buf[1000000] = {0};
	char *last = buf;
	char *next = buf;
 
	while (gets(line)) {
		strcat(line, "\n");
		if (cmp(last, line)) continue;
		if (cmp(line, last)) next = buf;
		last = next;
		strcpy(next, line);
		while (*next) next = &next[1];
	}
 
	printf("%s", buf);
	return 0;
}





Java: import java.io.File;
import java.util.Scanner;

public class LongestStringChallenge {

    public static void main(String[] args) throws Exception {
        String lines = "", longest = "";
        try (Scanner sc = new Scanner(new File("lines.txt"))) {
            while(sc.hasNext()) {
                String line = sc.nextLine();
                if (longer(longest, line))
                    lines = longest = line;
                else if (!longer(line, longest))
                    lines = lines.concat("\n").concat(line);
            }
        }
        System.out.println(lines);
    }

    static boolean longer(String a, String b) {
        try {
            String dummy = a.substring(b.length());
        } catch (StringIndexOutOfBoundsException e) {
            return true;
        }
        return false;
    }
}
Task: Create a file

C: #include <stdio.h>

int main() {
  FILE *fh = fopen("output.txt", "w");
  fclose(fh);

  return 0;
}





Java: import java.io.*;
public class CreateFileTest {
	public static void main(String args[]) {
		try {
			new File("output.txt").createNewFile();
			new File(File.separator + "output.txt").createNewFile();
			new File("docs").mkdir();
			new File(File.separator + "docs").mkdir();
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}
}
Task: Tau function

C: #include <stdio.h>


unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    
    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }
    
    for (unsigned int p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }
    
    if (n > 1) {
        total *= 2;
    }
    return total;
}

int main() {
    const unsigned int limit = 100;
    unsigned int n;

    printf("Count of divisors for the first %d positive integers:\n", limit);
    for (n = 1; n <= limit; ++n) {
        printf("%3d", divisor_count(n));
        if (n % 20 == 0) {
            printf("\n");
        }
    }

    return 0;
}





Java: public class TauFunction {
    private static long divisorCount(long n) {
        long total = 1;
        
        for (; (n & 1) == 0; n >>= 1) {
            ++total;
        }
        
        for (long p = 3; p * p <= n; p += 2) {
            long count = 1;
            for (; n % p == 0; n /= p) {
                ++count;
            }
            total *= count;
        }
        
        if (n > 1) {
            total *= 2;
        }
        return total;
    }

    public static void main(String[] args) {
        final int limit = 100;
        System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
        for (long n = 1; n <= limit; ++n) {
            System.out.printf("%3d", divisorCount(n));
            if (n % 20 == 0) {
                System.out.println();
            }
        }
    }
}
Task: Sequence of primorial primes

C: #include <gmp.h>

int main(void)
{
    mpz_t p, s;
    mpz_init_set_ui(p, 1);
    mpz_init_set_ui(s, 1);

    for (int n = 1, i = 0; i < 20; n++) {
        mpz_nextprime(s, s);
        mpz_mul(p, p, s);

        mpz_add_ui(p, p, 1);
        if (mpz_probab_prime_p(p, 25)) {
            mpz_sub_ui(p, p, 1);
            gmp_printf("%d\n", n);
            i++;
            continue;
        }

        mpz_sub_ui(p, p, 2);
        if (mpz_probab_prime_p(p, 25)) {
            mpz_add_ui(p, p, 1);
            gmp_printf("%d\n", n);
            i++;
            continue;
        }

        mpz_add_ui(p, p, 1);
    }

    mpz_clear(s);
    mpz_clear(p);
}





Java: import java.math.BigInteger;

public class PrimorialPrimes {

    final static int sieveLimit = 1550_000;
    static boolean[] notPrime = sieve(sieveLimit);

    public static void main(String[] args) {

        int count = 0;
        for (int i = 1; i < 1000_000 && count < 20; i++) {
            BigInteger b = primorial(i);
            if (b.add(BigInteger.ONE).isProbablePrime(1)
                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {
                System.out.printf("%d ", i);
                count++;
            }
        }
    }

    static BigInteger primorial(int n) {
        if (n == 0)
            return BigInteger.ONE;

        BigInteger result = BigInteger.ONE;
        for (int i = 0; i < sieveLimit && n > 0; i++) {
            if (notPrime[i])
                continue;
            result = result.multiply(BigInteger.valueOf(i));
            n--;
        }
        return result;
    }

    public static boolean[] sieve(int limit) {
        boolean[] composite = new boolean[limit];
        composite[0] = composite[1] = true;

        int max = (int) Math.sqrt(limit);
        for (int n = 2; n <= max; n++) {
            if (!composite[n]) {
                for (int k = n * n; k < limit; k += n) {
                    composite[k] = true;
                }
            }
        }
        return composite;
    }
}
Task: Factorions

C: #include <stdio.h>

int main() {    
    int n, b, d;
    unsigned long long i, j, sum, fact[12];
    
    fact[0] = 1;
    for (n = 1; n < 12; ++n) {
        fact[n] = fact[n-1] * n;
    }

    for (b = 9; b <= 12; ++b) {
        printf("The factorions for base %d are:\n", b);
        for (i = 1; i < 1500000; ++i) {
            sum = 0;
            j = i;
            while (j > 0) {
                d = j % b;
                sum += fact[d];
                j /= b;
            }
            if (sum == i) printf("%llu ", i);
        }
        printf("\n\n");
    }
    return 0;
}





Java: public class Factorion {
    public static void main(String [] args){
        System.out.println("Base 9:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,9);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
        System.out.println("\nBase 10:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,10);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
        System.out.println("\nBase 11:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,11);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
        System.out.println("\nBase 12:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,12);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
    }
    public static int factorialRec(int n){
        int result = 1;
        return n == 0 ? result : result * n * factorialRec(n-1);
    }

    public static int operate(String s, int base){
        int sum = 0;
        String strx = fromDeci(base, Integer.parseInt(s));
        for(int i = 0; i < strx.length(); i++){
            if(strx.charAt(i) == 'A'){
                sum += factorialRec(10);
            }else if(strx.charAt(i) == 'B') {
                sum += factorialRec(11);
            }else if(strx.charAt(i) == 'C') {
                sum += factorialRec(12);
            }else {
                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
            }
        }
        return sum;
    }
    
    static char reVal(int num) {
        if (num >= 0 && num <= 9)
            return (char)(num + 48);
        else
            return (char)(num - 10 + 65);
    }
    static String fromDeci(int base, int num){
        StringBuilder s = new StringBuilder();
        while (num > 0) {
            s.append(reVal(num % base));
            num /= base;
        }
        return new String(new StringBuilder(s).reverse());
    }
}