WeixiangYan/CodeTransOcean huggingface dataset:
Task: Waveform analysis_Doh ray me




Go: package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "math"
    "os"
)

var (
    freqs = []float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
    notes = []string{"Doh", "Ray", "Mee", "Fah", "Soh", "Lah", "Tee", "doh"}
)

func getNote(freq float64) string {
    index := len(freqs)
    for i := 0; i < len(freqs); i++ {
        if freq <= freqs[i] {
            index = i
            break
        }
    }
    switch index {
    case 0:
        return "Doh-"
    case len(freqs):
        return "doh+"
    default:
        if freqs[index]-freq <= freq-freqs[index-1] {
            return notes[index] + "-"
        }
        return notes[index-1] + "+"
    }
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    file, err := os.Open("notes.wav")
    check(err)
    defer file.Close()    
    hdr := make([]byte, 44)
    _, err = file.Read(hdr)
    check(err)
    
    sampleRate := int(binary.LittleEndian.Uint32(hdr[24:28]))
    fmt.Println("Sample Rate    :", sampleRate)
    dataLength := int(binary.LittleEndian.Uint32(hdr[40:]))
    duration := dataLength / sampleRate
    fmt.Println("Duration       :", duration)

    sum := 0.0
    sampleRateF := float64(sampleRate)
    data := make([]byte, sampleRate)
    nbytes := 20
    fmt.Println("Bytes examined :", nbytes, "per sample") 
    for j := 0; j < duration; j++ {
        _, err := file.Read(data)
        check(err)
        for i := 1; i <= nbytes; i++ {
            bf := float64(data[i]) / 32
            freq := math.Asin(bf) * sampleRateF / (float64(i) * math.Pi * 2)
            sum += freq
        }
    }
    cav := sum / (float64(duration) * float64(nbytes))
    fmt.Printf("\nComputed average frequency = %.1f Hz (%s)\n", cav, getNote(cav))

    sum = 0.0
    for i := 0; i < len(freqs); i++ {
        sum += freqs[i]
    }
    aav := sum / float64(len(freqs))
    fmt.Printf("Actual average frequency   = %.1f Hz (%s)\n", aav, getNote(aav))
}
Task: SEND + MORE = MONEY




Go: package main

import (
    "fmt"
    "time"
)

func contains(a []int, v int) bool {
    for i := 0; i < len(a); i++ {
        if a[i] == v {
            return true
        }
    }
    return false
}

func main() {
    start := time.Now()
    var sends [][4]int
    var ors [][2]int
    m := 1
    digits := []int{0, 2, 3, 4, 5, 6, 7, 8, 9}
    for s := 8; s <= 9; s++ {
        for _, e := range digits {
            if e == s {
                continue
            }
            for _, n := range digits {
                if n == s || n == e {
                    continue
                }
                for _, d := range digits {
                    if d == s || d == e || d == n {
                        continue
                    }
                    sends = append(sends, [4]int{s, e, n, d})
                }
            }
        }
    }
    for _, o := range digits {
        for _, r := range digits {
            if r != o {
                ors = append(ors, [2]int{o, r})
            }
        }
    }
    fmt.Println("Solution(s):")
    for _, send := range sends {
        SEND := 1000*send[0] + 100*send[1] + 10*send[2] + send[3]
        for _, or := range ors {
            send2 := send[:]
            or2 := or[:]
            if contains(send2, or[0]) || contains(send2, or[1]) {
                continue
            }
            MORE := 1000*m + 100*or[0] + 10*or[1] + send[1]
            for _, y := range digits {
                if contains(send2, y) || contains(or2, y) {
                    continue
                }
                MONEY := 10000*m + 1000*or[0] + 100*send[2] + 10*send[1] + y
                if SEND+MORE == MONEY {
                    fmt.Printf("%d + %d = %d\n", SEND, MORE, MONEY)
                }
            }
        }
    }
    fmt.Printf("\nTook %s.\n", time.Since(start))
}
Task: Horse racing




Go: package main

import (
    "fmt"
    "sort"
    "strings"
)

func main() {
    
    a := 100
    b := a - 8 - 2*2 
    c := a + 4 - 2*3.5
    d := a - 4 - 10*0.4 
    e := d + 7 - 2*1
    f := d + 11 - 2*(4-2)
    g := a - 10 + 10*0.2
    h := g + 6 - 2*1.5
    i := g + 15 - 2*2

    
    b += 4
    c -= 4
    h += 3
    j := a - 3 + 10*0.2

    
    b += 3
    d += 3
    i += 3
    j += 3

    
    m := map[string][2]int{
        "A": {a, 1},
        "B": {b, 0},
        "C": {c, 1},
        "D": {d, 0},
        "E": {e, 1},
        "F": {f, 1},
        "G": {g, 1},
        "H": {h, 1},
        "I": {i, 0},
        "J": {j, 0},
    }

    type kv struct {
        key   string
        value [2]int
    }

    
    l := make([]kv, len(m))
    x := 0
    for k, v := range m {
        l[x] = kv{k, v}
        x++
    }

    
    sort.Slice(l, func(i, j int) bool { return l[i].value[0] > l[j].value[0] })

    
    fmt.Println("Race 4\n")
    fmt.Println("Pos Horse  Weight  Dist  Sex")
    pos := ""
    for x := 0; x < len(l); x++ {
        wt := "9.00"
        if l[x].value[1] == 0 {
            wt = "8.11"
        }
        dist := 0.0
        if x > 0 {
            dist = float64(l[x-1].value[0]-l[x].value[0]) * 0.5
        }
        if x == 0 || dist > 0.0 {
            pos = fmt.Sprintf("%d", x+1)
        } else if !strings.HasSuffix(pos, "=") {
            pos = fmt.Sprintf("%d=", x)
        }
        sx := "colt"
        if l[x].value[1] == 0 {
            sx = "filly"
        }
        fmt.Printf("%-2s  %s      %s    %3.1f   %s\n", pos, l[x].key, wt, dist, sx)
    }

    
    wr := float64(l[0].value[0])

    
    t := 96.0 - (wr-100)/10
    min := int(t / 60)
    sec := t - float64(min)*60
    fmt.Printf("\nTime %d minute %3.1f seconds\n", min, sec)
}
Task: Combinations with repetitions_Square digit chain




Go: package main

import (
    "fmt"
    "math"
)

func endsWithOne(n int) bool {
    sum := 0
    for {
        for n > 0 {
            digit := n % 10
            sum += digit * digit
            n /= 10
        }
        if sum == 1 {
            return true
        }
        if sum == 89 {
            return false
        }
        n = sum
        sum = 0
    }
}

func main() {
    ks := [...]int{7, 8, 11, 14, 17}
    for _, k := range ks {
        sums := make([]int64, k*81+1)
        sums[0] = 1
        sums[1] = 0
        for n := 1; n <= k; n++ {
            for i := n * 81; i > 0; i-- {
                for j := 1; j < 10; j++ {
                    s := j * j
                    if s > i {
                        break
                    }
                    sums[i] += sums[i-s]
                }
            }
        }
        count1 := int64(0)
        for i := 1; i <= k*81; i++ {
            if endsWithOne(i) {
                count1 += sums[i]
            }
        }
        limit := int64(math.Pow10(k)) - 1
        fmt.Println("For k =", k, "in the range 1 to", limit)
        fmt.Println(count1, "numbers produce 1 and", limit-count1, "numbers produce 89\n")
    }
}
Task: Doubly-linked list_Element removal




Go: package main

import (
    "container/list"
    "fmt"
)

func printDll(s string, dll *list.List) {
    fmt.Printf("%s: { ", s)
    for e := dll.Front(); e != nil; e = e.Next() {
        fmt.Printf("%v ", e.Value)
    }
    fmt.Println("}")
}

func main() {
    dll := list.New()
    e1 := dll.PushBack("dog")
    e2 := dll.PushBack("cat")
    dll.PushBack("bear")
    printDll("Before removals", dll)
    dll.Remove(e2) 
    printDll("After removal 1", dll)
    dll.Remove(e1) 
    printDll("After removal 2", dll)
}
Task: Launch rocket with countdown and acceleration in stdout




Go: package main

import (
    "fmt"
    "time"
)

const rocket = `
    /\
   (  )
   (  )
  /|/\|\
 /_||||_\
`

func printRocket(above int) {
    fmt.Print(rocket)
    for i := 1; i <= above; i++ {
        fmt.Println("    ||")
    }
}

func cls() {
    fmt.Print("\x1B[2J")
}

func main() {
    
    for n := 5; n >= 1; n-- {
        cls()
        fmt.Printf("%d =>\n", n)
        printRocket(0)
        time.Sleep(time.Second)
    }

    
    cls()
    fmt.Println("Liftoff !")
    printRocket(1)
    time.Sleep(time.Second)

    
    ms := time.Duration(1000)
    for n := 2; n < 100; n++ {
        cls()
        printRocket(n)
        time.Sleep(ms * time.Millisecond)
        if ms >= 40 {
            ms -= 40
        } else {
            ms = 0
        }
    }
}
Task: Largest number divisible by its digits





Java: public class LynchBell {
    
    static String s = "";
    
    public static void main(String args[]) {
        
        int i = 98764321;
        boolean isUnique = true;
        boolean canBeDivided = true;
        while (i>0) {
            s = String.valueOf(i);
            isUnique = uniqueDigits(i);
            if (isUnique) {
                
                canBeDivided = testNumber(i);
                if(canBeDivided) {
                    System.out.println("Number found: " + i);
                    i=0;
                }
            }
            i--;
        }
    }
    
    public static boolean uniqueDigits(int i) {
        
        for (int k = 0; k<s.length();k++) {
            for(int l=k+1; l<s.length();l++) {
                if(s.charAt(l)=='0' || s.charAt(l)=='5') {
                    
                    return false;
                }
                if(s.charAt(k) == s.charAt(l)) {
                    
                    return false;
                }
            }
        }
        return true;
    }
    
    public static boolean testNumber(int i) {
        
        int j = 0;
        boolean divisible = true;
        
        for (char ch: s.toCharArray()) {
            j = Character.getNumericValue(ch);
            divisible = ((i%j)==0);
            if (!divisible) {
                return false;
            }
        }       
        return true;
    }
}
Task: Jacobi symbol





Java: public class JacobiSymbol {

    public static void main(String[] args) {
        int max = 30;
        System.out.printf("n\\k ");
        for ( int k = 1 ; k <= max ; k++ ) {
            System.out.printf("%2d  ", k);
        }
        System.out.printf("%n");
        for ( int n = 1 ; n <= max ; n += 2 ) {
            System.out.printf("%2d  ", n);
            for ( int k = 1 ; k <= max ; k++ ) {
                System.out.printf("%2d  ", jacobiSymbol(k, n));
            }
            System.out.printf("%n");
        }
    }
    
    
    
    private static int jacobiSymbol(int k, int n) {
        if ( k < 0 || n % 2 == 0 ) {
            throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n);
        }
        k %= n;
        int jacobi = 1;
        while ( k > 0 ) {
            while ( k % 2 == 0 ) {
                k /= 2;
                int r = n % 8;
                if ( r == 3 || r == 5 ) {
                    jacobi = -jacobi;
                }
            }
            int temp = n;
            n = k;
            k = temp;
            if ( k % 4 == 3 && n % 4 == 3 ) {
                jacobi = -jacobi;
            }
            k %= n;
        }
        if ( n == 1 ) {
            return jacobi;
        }
        return 0;
    }

}
Task: Determinant and permanent





Java: import java.util.Scanner;

public class MatrixArithmetic {
	public static double[][] minor(double[][] a, int x, int y){
		int length = a.length-1;
		double[][] result = new double[length][length];
		for(int i=0;i<length;i++) for(int j=0;j<length;j++){
			if(i<x && j<y){
				result[i][j] = a[i][j];
			}else if(i>=x && j<y){
				result[i][j] = a[i+1][j];
			}else if(i<x && j>=y){
				result[i][j] = a[i][j+1];
			}else{ 
				result[i][j] = a[i+1][j+1];
			}
		}
		return result;
	}
	public static double det(double[][] a){
		if(a.length == 1){
			return a[0][0];
		}else{
			int sign = 1;
			double sum = 0;
			for(int i=0;i<a.length;i++){
				sum += sign * a[0][i] * det(minor(a,0,i));
				sign *= -1;
			}
			return sum;
		}
	}
	public static double perm(double[][] a){
		if(a.length == 1){
			return a[0][0];
		}else{
			double sum = 0;
			for(int i=0;i<a.length;i++){
				sum += a[0][i] * perm(minor(a,0,i));
			}
			return sum;
		}
	}
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int size = sc.nextInt();
		double[][] a = new double[size][size];
		for(int i=0;i<size;i++) for(int j=0;j<size;j++){
			a[i][j] = sc.nextDouble();
		}
		sc.close();
		System.out.println("Determinant: "+det(a));
		System.out.println("Permanent: "+perm(a));
	}
}
Task: Sattolo cycle





Java: private static final Random rng = new Random();

void sattoloCycle(Object[] items) {
    for (int i = items.length-1; i > 0; i--) {
        int j = rng.nextInt(i);
        Object tmp = items[i];
        items[i] = items[j];
        items[j] = tmp;
    }
}
Task: FTP





Java: import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPconn {

    public static void main(String[] args) throws IOException {
        String server = "ftp.hq.nasa.gov";
        int port = 21;
        String user = "anonymous";
        String pass = "ftptest@example.com";

        OutputStream output = null;

        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);

            serverReply(ftpClient);

            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("Failure. Server reply code: " + replyCode);
                return;
            }

            serverReply(ftpClient);

            if (!ftpClient.login(user, pass)) {
                System.out.println("Could not login to the server.");
                return;
            }

            String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/";
            if (!ftpClient.changeWorkingDirectory(dir)) {
                System.out.println("Change directory failed.");
                return;
            }

            ftpClient.enterLocalPassiveMode();

            for (FTPFile file : ftpClient.listFiles())
                System.out.println(file);

            String filename = "Can People go to Mars.mp3";
            output = new FileOutputStream(filename);

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (!ftpClient.retrieveFile(filename, output)) {
                System.out.println("Retrieving file failed");
                return;
            }

            serverReply(ftpClient);

            ftpClient.logout();

        } finally {
            if (output != null)
                output.close();
        }
    }

    private static void serverReply(FTPClient ftpClient) {
        for (String reply : ftpClient.getReplyStrings()) {
            System.out.println(reply);
        }
    }
}
Task: Sorting algorithms_Cycle sort





Java: import java.util.Arrays;

public class CycleSort {

    public static void main(String[] args) {
        int[] arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1};

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

        int writes = cycleSort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println("writes: " + writes);
    }

    static int cycleSort(int[] a) {
        int writes = 0;

        for (int cycleStart = 0; cycleStart < a.length - 1; cycleStart++) {
            int val = a[cycleStart];

            
            
            int pos = cycleStart;
            for (int i = cycleStart + 1; i < a.length; i++)
                if (a[i] < val)
                    pos++;

            
            if (pos == cycleStart)
                continue;

            
            while (val == a[pos])
                pos++;

            
            int tmp = a[pos];
            a[pos] = val;
            val = tmp;
            writes++;

            
            
            while (pos != cycleStart) {
                pos = cycleStart;
                for (int i = cycleStart + 1; i < a.length; i++)
                    if (a[i] < val)
                        pos++;

                while (val == a[pos])
                    pos++;

                tmp = a[pos];
                a[pos] = val;
                val = tmp;
                writes++;
            }
        }
        return writes;
    }
}
Task: Twin primes





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

public class twinPrimes {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Search Size: ");
        BigInteger max = input.nextBigInteger();
        int counter = 0;
        for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
            }
        }
        System.out.println(counter + " twin prime pairs.");
    }
    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
                return false;
            }
        }
        return true;
    }
}
Task: Create a file on magnetic tape





Java: import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class CreateFile {
    public static void main(String[] args) throws IOException {
        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            Path path = Paths.get("tape.file");
            Files.write(path, Collections.singletonList("Hello World!"));
        } else {
            Path path = Paths.get("/dev/tape");
            Files.write(path, Collections.singletonList("Hello World!"));
        }
    }
}
Task: Recaman's sequence





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

public class RecamanSequence {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>();
        a.add(0);

        Set<Integer> used = new HashSet<>();
        used.add(0);

        Set<Integer> used1000 = new HashSet<>();
        used1000.add(0);

        boolean foundDup = false;
        int n = 1;
        while (n <= 15 || !foundDup || used1000.size() < 1001) {
            int next = a.get(n - 1) - n;
            if (next < 1 || used.contains(next)) {
                next += 2 * n;
            }
            boolean alreadyUsed = used.contains(next);
            a.add(next);
            if (!alreadyUsed) {
                used.add(next);
                if (0 <= next && next <= 1000) {
                    used1000.add(next);
                }
            }
            if (n == 14) {
                System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
            }
            if (!foundDup && alreadyUsed) {
                System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
                foundDup = true;
            }
            if (used1000.size() == 1001) {
                System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
            }
            n++;
        }
    }
}
Task: Y combinator





Java: import java.util.function.Function;

public interface YCombinator {
  interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }
  public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {
    RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));
    return r.apply(r);
  }

  public static void main(String... arguments) {
    Function<Integer,Integer> fib = Y(f -> n ->
      (n <= 2)
        ? 1
        : (f.apply(n - 1) + f.apply(n - 2))
    );
    Function<Integer,Integer> fac = Y(f -> n ->
      (n <= 1)
        ? 1
        : (n * f.apply(n - 1))
    );

    System.out.println("fib(10) = " + fib.apply(10));
    System.out.println("fac(10) = " + fac.apply(10));
  }
}
Task: Factorions





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());
    }
}
Task: Sum of divisors





Java: public class DivisorSum {
    private static long divisorSum(long n) {
        var total = 1L;
        var power = 2L;
        
        for (; (n & 1) == 0; power <<= 1, n >>= 1) {
            total += power;
        }
        
        for (long p = 3; p * p <= n; p += 2) {
            long sum = 1;
            for (power = p; n % p == 0; power *= p, n /= p) {
                sum += power;
            }
            total *= sum;
        }
        
        if (n > 1) {
            total *= n + 1;
        }
        return total;
    }

    public static void main(String[] args) {
        final long limit = 100;
        System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
        for (long n = 1; n <= limit; ++n) {
            System.out.printf("%4d", divisorSum(n));
            if (n % 10 == 0) {
                System.out.println();
            }
        }
    }
}