WeixiangYan/CodeTransOcean huggingface dataset:
Task: Topswops


C++: #include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>

int topswops(int n) {
  std::vector<int> list(n);
  std::iota(std::begin(list), std::end(list), 1);
  int max_steps = 0;
  do {
    auto temp_list = list;
    for (int steps = 1; temp_list[0] != 1; ++steps) {
      std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);
      if (steps > max_steps) max_steps = steps;
    }
  } while (std::next_permutation(std::begin(list), std::end(list)));
  return max_steps;
}

int main() {
  for (int i = 1; i <= 10; ++i) {
    std::cout << i << ": " << topswops(i) << std::endl;
  }
  return 0;
}




Java: public class Topswops {
    static final int maxBest = 32;
    static int[] best;

    static private void trySwaps(int[] deck, int f, int d, int n) {
        if (d > best[n])
            best[n] = d;

        for (int i = n - 1; i >= 0; i--) {
            if (deck[i] == -1 || deck[i] == i)
                break;
            if (d + best[i] <= best[n])
                return;
        }

        int[] deck2 = deck.clone();
        for (int i = 1; i < n; i++) {
            final int k = 1 << i;
            if (deck2[i] == -1) {
                if ((f & k) != 0)
                    continue;
            } else if (deck2[i] != i)
                continue;

            deck2[0] = i;
            for (int j = i - 1; j >= 0; j--)
                deck2[i - j] = deck[j]; 
            trySwaps(deck2, f | k, d + 1, n);
        }
    }

    static int topswops(int n) {
        assert(n > 0 && n < maxBest);
        best[n] = 0;
        int[] deck0 = new int[n + 1];
        for (int i = 1; i < n; i++)
            deck0[i] = -1;
        trySwaps(deck0, 1, 0, n);
        return best[n];
    }

    public static void main(String[] args) {
        best = new int[maxBest];
        for (int i = 1; i < 11; i++)
            System.out.println(i + ": " + topswops(i));
    }
}
Task: Rate counter


C++: #include <iostream>
#include <ctime>



class CRateState
{
protected:
    time_t m_lastFlush;
    time_t m_period;
    size_t m_tickCount;
public:
    CRateState(time_t period);
    void Tick();
};

CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),
                                        m_period(period),
                                        m_tickCount(0)
{ }

void CRateState::Tick()
{
    m_tickCount++;

    time_t now = std::time(NULL);

    if((now - m_lastFlush) >= m_period)
    {
        
        size_t tps = 0.0;
        if(m_tickCount > 0)
            tps = m_tickCount / (now - m_lastFlush);

        std::cout << tps << " tics per second" << std::endl;

        
        m_tickCount = 0;
        m_lastFlush = now;
    }
}



void something_we_do()
{
    
    
    
    
    
    
    
    volatile size_t anchor = 0;
    for(size_t x = 0; x < 0xffff; ++x)
    {
        anchor = x;
    }
}

int main()
{
    time_t start = std::time(NULL);

    CRateState rateWatch(5);

    
    for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))
    {
        
        something_we_do();

        
        rateWatch.Tick();
    }

    return 0;
}




Java: import java.util.function.Consumer;

public class RateCounter {

    public static void main(String[] args) {
        for (double d : benchmark(10, x -> System.out.print(""), 10))
            System.out.println(d);
    }

    static double[] benchmark(int n, Consumer<Integer> f, int arg) {
        double[] timings = new double[n];
        for (int i = 0; i < n; i++) {
            long time = System.nanoTime();
            f.accept(arg);
            timings[i] = System.nanoTime() - time;
        }
        return timings;
    }
}
Task: Sequence_ smallest number greater than previous term with exactly n divisors


C++: #include <iostream>

#define MAX 15

using namespace std;

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

int main() {
    cout << "The first " << MAX << " terms of the sequence are:" << endl;
    for (int i = 1, next = 1; next <= MAX; ++i) {
        if (next == count_divisors(i)) {           
            cout << i << " ";
            next++;
        }
    }
    cout << endl;
    return 0;
}




Java: public class AntiPrimesPlus {

    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;
        System.out.printf("The first %d terms of the sequence are:\n", max);
        for (int i = 1, next = 1; next <= max; ++i) {
            if (next == count_divisors(i)) {           
                System.out.printf("%d ", i);
                next++;
            }
        }
        System.out.println();
    }
}
Task: Odd word problem


C++: #include <iostream>
#include <cctype>
#include <functional>

using namespace std;

bool odd()
{
  function<void ()> prev = []{};
  while(true) {
    int c = cin.get();
    if (!isalpha(c)) {
      prev();
      cout.put(c);
      return c != '.';
    }
    prev = [=] { cout.put(c); prev();  };
  }
}

bool even() 
{
  while(true) {
    int c;
    cout.put(c = cin.get());
    if (!isalpha(c)) return c != '.';
  }
}


int main()
{
  bool e = false;
  while( e ? odd() : even() ) e = !e;
  return 0;
}




Java: public class OddWord {
    interface CharHandler {
	CharHandler handle(char c) throws Exception;
    }
    final CharHandler fwd = new CharHandler() {
	public CharHandler handle(char c) {
	    System.out.print(c);
	    return (Character.isLetter(c) ? fwd : rev);
	}
    };
    class Reverser extends Thread implements CharHandler {
	Reverser() {
	    setDaemon(true);
	    start();
	}
	private Character ch; 
	private char recur() throws Exception {
	    notify();
	    while (ch == null) wait();
	    char c = ch, ret = c;
	    ch = null;
	    if (Character.isLetter(c)) {
		ret = recur();
		System.out.print(c);
	    }
	    return ret;
	}
	public synchronized void run() {
	    try {
		while (true) {
		    System.out.print(recur());
		    notify();
		}
	    } catch (Exception e) {}
	}
	public synchronized CharHandler handle(char c) throws Exception {
	    while (ch != null) wait();
	    ch = c;
	    notify();
	    while (ch != null) wait();
	    return (Character.isLetter(c) ? rev : fwd);
	}
    }
    final CharHandler rev = new Reverser();

    public void loop() throws Exception {
	CharHandler handler = fwd;
	int c;
	while ((c = System.in.read()) >= 0) {
	    handler = handler.handle((char) c);
	}
    }

    public static void main(String[] args) throws Exception {
	new OddWord().loop();
    }
}
Task: Stern-Brocot sequence


C++: #include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>

unsigned gcd( unsigned i, unsigned j ) {
    return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;
}
void createSequence( std::vector<unsigned>& seq, int c ) {
    if( 1500 == seq.size() ) return;
    unsigned t = seq.at( c ) + seq.at( c + 1 );
    seq.push_back( t );
    seq.push_back( seq.at( c + 1 ) );
    createSequence( seq, c + 1 );
}
int main( int argc, char* argv[] ) {
    std::vector<unsigned> seq( 2, 1 );
    createSequence( seq, 0 );

    std::cout << "First fifteen members of the sequence:\n    ";
    for( unsigned x = 0; x < 15; x++ ) {
        std::cout << seq[x] << " ";    
    }

    std::cout << "\n\n";    
    for( unsigned x = 1; x < 11; x++ ) {
        std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );
        if( i != seq.end() ) {
            std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
        }
    }

    std::cout << "\n";
    std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );
    if( i != seq.end() ) {
        std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
    }

    std::cout << "\n";
    unsigned g;
    bool f = false;
    for( int x = 0, y = 1; x < 1000; x++, y++ ) {
        g =  gcd( seq[x], seq[y] );
	if( g != 1 ) f = true;
        std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " 
                  << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" );
    }
    std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n";
    return 0;
}




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

public class SternBrocot {
	static LinkedList<Integer> sequence = new LinkedList<Integer>(){{
		add(1); add(1);
	}};
	
	private static void genSeq(int n){
		for(int conIdx = 1; sequence.size() < n; conIdx++){
			int consider = sequence.get(conIdx);
			int pre = sequence.get(conIdx - 1);
			sequence.add(consider + pre);
			sequence.add(consider);
		}
		
	}
	
	public static void main(String[] args){
		genSeq(1200);
		System.out.println("The first 15 elements are: " + sequence.subList(0, 15));
		for(int i = 1; i <= 10; i++){
			System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1));
		}
		
		System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1));
		
		boolean failure = false;
		for(int i = 0; i < 999; i++){
			failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);
		}
		System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
	}
}
Task: Longest common suffix


C++: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>

std::string lcs(const std::vector<std::string>& strs) {
    std::vector<std::string::const_reverse_iterator> backs;
    std::string s;
    
    if (strs.size() == 0) return "";
    if (strs.size() == 1) return strs[0];
    
    for (auto& str : strs) backs.push_back(str.crbegin());
    
    while (backs[0] != strs[0].crend()) {
        char ch = *backs[0]++;
        for (std::size_t i = 1; i<strs.size(); i++) {
            if (backs[i] == strs[i].crend()) goto done;
            if (*backs[i] != ch) goto done;
            backs[i]++;
        }
        s.push_back(ch);
    }
    
done:
    reverse(s.begin(), s.end());
    return s;
}

void test(const std::vector<std::string>& strs) {
    std::cout << "[";
    for (std::size_t i = 0; i<strs.size(); i++) {
        std::cout << '"' << strs[i] << '"';
        if (i != strs.size()-1) std::cout << ", ";
    }
    std::cout << "] -> `" << lcs(strs) << "`\n";
}

int main() {
    std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"};
    std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"};
    std::vector<std::string> t3 = 
        {"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"};
    std::vector<std::string> t4 = {"longest", "common", "suffix"};
    std::vector<std::string> t5 = {""};
    std::vector<std::string> t6 = {};
    std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"};

    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};
    
    for (auto t : tests) test(t);
    return 0;
}




Java: import java.util.List;

public class App {
    private static String lcs(List<String> a) {
        var le = a.size();
        if (le == 0) {
            return "";
        }
        if (le == 1) {
            return a.get(0);
        }
        var le0 = a.get(0).length();
        var minLen = le0;
        for (int i = 1; i < le; i++) {
            if (a.get(i).length() < minLen) {
                minLen = a.get(i).length();
            }
        }
        if (minLen == 0) {
            return "";
        }
        var res = "";
        var a1 = a.subList(1, a.size());
        for (int i = 1; i < minLen; i++) {
            var suffix = a.get(0).substring(le0 - i);
            for (String e : a1) {
                if (!e.endsWith(suffix)) {
                    return res;
                }
            }
            res = suffix;
        }
        return "";
    }

    public static void main(String[] args) {
        var tests = List.of(
            List.of("baabababc", "baabc", "bbbabc"),
            List.of("baabababc", "baabc", "bbbazc"),
            List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"),
            List.of("longest", "common", "suffix"),
            List.of("suffix"),
            List.of("")
        );
        for (List<String> test : tests) {
            System.out.printf("%s -> `%s`\n", test, lcs(test));
        }
    }
}
Task: Sum of elements below main diagonal of matrix


C++: #include <iostream>
#include <vector>

template<typename T>
T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {
    T sum = 0;
    for (std::size_t y = 0; y < matrix.size(); y++)
        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)
            sum += matrix[y][x];
    return sum;
}

int main() {
    std::vector<std::vector<int>> matrix = {
        {1,3,7,8,10},
        {2,4,16,14,4},
        {3,1,9,18,11},
        {12,14,17,18,20},
        {7,1,3,9,5}
    };
    
    std::cout << sum_below_diagonal(matrix) << std::endl;
    return 0;
}




Java: public static void main(String[] args) {
    int[][] matrix = {{1, 3, 7, 8, 10},
                      {2, 4, 16, 14, 4},
                      {3, 1, 9, 18, 11},
                      {12, 14, 17, 18, 20},
                      {7, 1, 3, 9, 5}};
    int sum = 0;
    for (int row = 1; row < matrix.length; row++) {
        for (int col = 0; col < row; col++) {
            sum += matrix[row][col];
        }
    }
    System.out.println(sum);
}
Task: FASTA format


C++: #include <iostream>
#include <fstream>

int main( int argc, char **argv ){
    if( argc <= 1 ){
        std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl;
        return -1;
    }

    std::ifstream input(argv[1]);
    if(!input.good()){
        std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl;
        return -1;
    }

    std::string line, name, content;
    while( std::getline( input, line ).good() ){
        if( line.empty() || line[0] == '>' ){ 
            if( !name.empty() ){ 
                std::cout << name << " : " << content << std::endl;
                name.clear();
            }
            if( !line.empty() ){
                name = line.substr(1);
            }
            content.clear();
        } else if( !name.empty() ){
            if( line.find(' ') != std::string::npos ){ 
                name.clear();
                content.clear();
            } else {
                content += line;
            }
        }
    }
    if( !name.empty() ){ 
        std::cout << name << " : " << content << std::endl;
    }
    
    return 0;
}




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

public class ReadFastaFile {

    public static void main(String[] args) throws FileNotFoundException {

        boolean first = true;

        try (Scanner sc = new Scanner(new File("test.fasta"))) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine().trim();
                if (line.charAt(0) == '>') {
                    if (first)
                        first = false;
                    else
                        System.out.println();
                    System.out.printf("%s: ", line.substring(1));
                } else {
                    System.out.print(line);
                }
            }
        }
        System.out.println();
    }
}
Task: Pseudo-random numbers_PCG32


C++: #include <array>
#include <iostream>

class PCG32 {
private:
    const uint64_t N = 6364136223846793005;
    uint64_t state = 0x853c49e6748fea9b;
    uint64_t inc = 0xda3e39cb94b95bdb;
public:
    uint32_t nextInt() {
        uint64_t old = state;
        state = old * N + inc;
        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
        uint32_t rot = old >> 59;
        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
    }

    double nextFloat() {
        return ((double)nextInt()) / (1LL << 32);
    }

    void seed(uint64_t seed_state, uint64_t seed_sequence) {
        state = 0;
        inc = (seed_sequence << 1) | 1;
        nextInt();
        state = state + seed_state;
        nextInt();
    }
};

int main() {
    auto r = new PCG32();

    r->seed(42, 54);
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << '\n';

    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };
    r->seed(987654321, 1);
    for (size_t i = 0; i < 100000; i++) {
        int j = (int)floor(r->nextFloat() * 5.0);
        counts[j]++;
    }

    std::cout << "The counts for 100,000 repetitions are:\n";
    for (size_t i = 0; i < counts.size(); i++) {
        std::cout << "  " << i << " : " << counts[i] << '\n';
    }

    return 0;
}




Java: public class PCG32 {
    private static final long N = 6364136223846793005L;

    private long state = 0x853c49e6748fea9bL;
    private long inc = 0xda3e39cb94b95bdbL;

    public void seed(long seedState, long seedSequence) {
        state = 0;
        inc = (seedSequence << 1) | 1;
        nextInt();
        state = state + seedState;
        nextInt();
    }

    public int nextInt() {
        long old = state;
        state = old * N + inc;
        int shifted = (int) (((old >>> 18) ^ old) >>> 27);
        int rot = (int) (old >>> 59);
        return (shifted >>> rot) | (shifted << ((~rot + 1) & 31));
    }

    public double nextFloat() {
        var u = Integer.toUnsignedLong(nextInt());
        return (double) u / (1L << 32);
    }

    public static void main(String[] args) {
        var r = new PCG32();

        r.seed(42, 54);
        System.out.println(Integer.toUnsignedString(r.nextInt()));
        System.out.println(Integer.toUnsignedString(r.nextInt()));
        System.out.println(Integer.toUnsignedString(r.nextInt()));
        System.out.println(Integer.toUnsignedString(r.nextInt()));
        System.out.println(Integer.toUnsignedString(r.nextInt()));
        System.out.println();

        int[] counts = {0, 0, 0, 0, 0};
        r.seed(987654321, 1);
        for (int i = 0; i < 100_000; i++) {
            int j = (int) Math.floor(r.nextFloat() * 5.0);
            counts[j]++;
        }

        System.out.println("The counts for 100,000 repetitions are:");
        for (int i = 0; i < counts.length; i++) {
            System.out.printf("  %d : %d\n", i, counts[i]);
        }
    }
}
Task: Rep-string


C++: #include <string>
#include <vector>
#include <boost/regex.hpp>

bool is_repstring( const std::string & teststring , std::string & repunit ) {
   std::string regex( "^(.+)\\1+(.*)$" ) ;
   boost::regex e ( regex ) ;
   boost::smatch what ;
   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {
      std::string firstbracket( what[1 ] ) ;
      std::string secondbracket( what[ 2 ] ) ;
      if ( firstbracket.length( ) >= secondbracket.length( ) &&
	    firstbracket.find( secondbracket ) != std::string::npos ) {
	 repunit = firstbracket  ;
      }
   }
   return !repunit.empty( ) ;
}

int main( ) {
   std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" ,
      "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ;
   std::string theRep ;
   for ( std::string myString : teststrings ) {
      if ( is_repstring( myString , theRep ) ) {
	 std::cout << myString << " is a rep string! Here is a repeating string:\n" ;
	 std::cout << theRep << " " ;
      }
      else {
	 std::cout << myString << " is no rep string!" ;
      }
      theRep.clear( ) ;
      std::cout << std::endl ;
   }
   return 0 ;
}




Java: public class RepString {

    static final String[] input = {"1001110011", "1110111011", "0010010010",
        "1010101010", "1111111111", "0100101101", "0100100", "101", "11",
        "00", "1", "0100101"};

    public static void main(String[] args) {
        for (String s : input)
            System.out.printf("%s : %s%n", s, repString(s));
    }

    static String repString(String s) {
        int len = s.length();
        outer:
        for (int part = len / 2; part > 0; part--) {
            int tail = len % part;
            if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail)))
                continue;
            for (int j = 0; j < len / part - 1; j++) {
                int a = j * part;
                int b = (j + 1) * part;
                int c = (j + 2) * part;
                if (!s.substring(a, b).equals(s.substring(b, c)))
                    continue outer;
            }
            return s.substring(0, part);
        }
        return "none";
    }
}
Task: Literals_String


C++: auto strA = R"(this is
a newline-separated
raw string)";




Java:   char a = 'a';  
  String b = "abc";  
  char doubleQuote = '"';  
  char singleQuote = '\'';  
  String singleQuotes = "''";  
  String doubleQuotes = "\"\"";
Task: Changeable words


C++: #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

int hamming_distance(const std::string& str1, const std::string& str2) {
    size_t len1 = str1.size();
    size_t len2 = str2.size();
    if (len1 != len2)
        return 0;
    int count = 0;
    for (size_t i = 0; i < len1; ++i) {
        if (str1[i] != str2[i])
            ++count;
        
        if (count == 2)
            break;
    }
    return count;
}

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string line;
    std::vector<std::string> dictionary;
    while (getline(in, line)) {
        if (line.size() > 11)
            dictionary.push_back(line);
    }
    std::cout << "Changeable words in " << filename << ":\n";
    int n = 1;
    for (const std::string& word1 : dictionary) {
        for (const std::string& word2 : dictionary) {
            if (hamming_distance(word1, word2) == 1)
                std::cout << std::setw(2) << std::right << n++
                    << ": " << std::setw(14) << std::left << word1
                    << " -> " << word2 << '\n';
        }
    }
    return EXIT_SUCCESS;
}




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

public class ChangeableWords {
    public static void main(String[] args) {
        try {
            final String fileName = "unixdict.txt";
            List<String> dictionary = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.length() > 11)
                        dictionary.add(line);
                }
            }
            System.out.printf("Changeable words in %s:\n", fileName);
            int n = 1;
            for (String word1 : dictionary) {
                for (String word2 : dictionary) {
                    if (word1 != word2 && hammingDistance(word1, word2) == 1)
                        System.out.printf("%2d: %-14s -> %s\n", n++, word1, word2);
                }
            }
        } catch (Exception e)  {
            e.printStackTtexture();
        }
    }

    private static int hammingDistance(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        if (len1 != len2)
            return 0;
        int count = 0;
        for (int i = 0; i < len1; ++i) {
            if (str1.charAt(i) != str2.charAt(i))
                ++count;
            
            if (count == 2)
                break;
        }
        return count;
    }
}