WeixiangYan/CodeTransOcean huggingface dataset:
Task: Permutations by swapping


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

using namespace std;

vector<int> UpTo(int n, int offset = 0)
{
	vector<int> retval(n);
	for (int ii = 0; ii < n; ++ii)
		retval[ii] = ii + offset;
	return retval;
}

struct JohnsonTrotterState_
{
	vector<int> values_;
	vector<int> positions_;	
	vector<bool> directions_;
	int sign_;

	JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}

	int LargestMobile() const	
	{
		for (int r = values_.size(); r > 0; --r)
		{
			const int loc = positions_[r] + (directions_[r] ? 1 : -1);
			if (loc >= 0 && loc < values_.size() && values_[loc] < r)
				return r;
		}
		return 0;
	}

	bool IsComplete() const { return LargestMobile() == 0; }

	void operator++()	
	{
		const int r = LargestMobile();
		const int rLoc = positions_[r];
		const int lLoc = rLoc + (directions_[r] ? 1 : -1);
		const int l = values_[lLoc];
		
		swap(values_[lLoc], values_[rLoc]);
		swap(positions_[l], positions_[r]);
		sign_ = -sign_;
		
		for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)
			*pd = !*pd;
	}
};

int main(void)
{
	JohnsonTrotterState_ state(4);
	do
	{
		for (auto v : state.values_)
			cout << v << " ";
		cout << "\n";
		++state;
	} while (!state.IsComplete());
}




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: Pythagorean quadruples


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

constexpr int N = 2200;
constexpr int N2 = 2 * N * N;

int main() {
    using namespace std;

    vector<bool> found(N + 1);
    vector<bool> aabb(N2 + 1);

    int s = 3;

    for (int a = 1; a < N; ++a) {
        int aa = a * a;
        for (int b = 1; b < N; ++b) {
            aabb[aa + b * b] = true;
        }
    }

    for (int c = 1; c <= N; ++c) {
        int s1 = s;
        s += 2;
        int s2 = s;
        for (int d = c + 1; d <= N; ++d) {
            if (aabb[s1]) {
                found[d] = true;
            }
            s1 += s2;
            s2 += 2;
        }
    }

    cout << "The values of d <= " << N << " which can't be represented:" << endl;
    for (int d = 1; d <= N; ++d) {
        if (!found[d]) {
            cout << d << " ";
        }
    }
    cout << endl;

    return 0;
}




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

public class PythagoreanQuadruples {

    public static void main(String[] args) {
        long d = 2200;
        System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
    }

    
    private static List<Long> getPythagoreanQuadruples(long max) {
        List<Long> list = new ArrayList<>();
        long n = -1;
        long m = -1;
        while ( true ) {
            long nTest = (long) Math.pow(2, n+1);
            long mTest = (long) (5L * Math.pow(2, m+1));
            long test = 0;
            if ( nTest > mTest ) {
                test = mTest;
                m++;
            }
            else {
                test = nTest;
                n++;
            }
            if ( test < max ) {
                list.add(test);
            }
            else {
                break;
            }
        }
        return list;
    }

}
Task: Literals_Floating point


C++: #include <iostream>

int main()
{
  
  auto double1 = 2.5;

  
  auto float1 = 2.5f;

  
  auto longdouble1 = 2.5l;

  
  auto double2 = 2.5e-3;
  auto float2 = 2.5e3f;

  
  auto double3 = 0x1p4;
  auto float3 = 0xbeefp-8f;

  std::cout << "\ndouble1: " << double1;
  std::cout << "\nfloat1: " << float1;
  std::cout << "\nlongdouble1: " << longdouble1;
  std::cout << "\ndouble2: " << double2;
  std::cout << "\nfloat2: " << float2;
  std::cout << "\ndouble3: " << double3;
  std::cout << "\nfloat3: " << float3;
  std::cout << "\n";
}




Java: 1. 
1.0 
2432311.7567374 
1.234E-10 
1.234e-10 
758832d 
728832f 
1.0f 
758832D 
728832F 
1.0F 
1 / 2. 
1 / 2
Task: Erdős-primes


C++: #include <cstdint>
#include <iomanip>
#include <iostream>
#include <set>
#include <primesieve.hpp>

class erdos_prime_generator {
public:
    erdos_prime_generator() {}
    uint64_t next();
private:
    bool erdos(uint64_t p) const;
    primesieve::iterator iter_;
    std::set<uint64_t> primes_;
};

uint64_t erdos_prime_generator::next() {
    uint64_t prime;
    for (;;) {
        prime = iter_.next_prime();
        primes_.insert(prime);
        if (erdos(prime))
            break;
    }
    return prime;
}

bool erdos_prime_generator::erdos(uint64_t p) const {
    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {
        if (primes_.find(p - f) != primes_.end())
            return false;
    }
    return true;
}

int main() {
    std::wcout.imbue(std::locale(""));
    erdos_prime_generator epgen;
    const int max_print = 2500;
    const int max_count = 7875;
    uint64_t p;
    std::wcout << L"Erd\x151s primes less than " << max_print << L":\n";
    for (int count = 1; count <= max_count; ++count) {
        p = epgen.next();
        if (p < max_print)
            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' ');
    }
    std::wcout << L"\n\nThe " << max_count << L"th Erd\x151s prime is " << p << L".\n";
    return 0;
}




Java: import java.util.*;

public class ErdosPrimes {
    public static void main(String[] args) {
        boolean[] sieve = primeSieve(1000000);
        int maxPrint = 2500;
        int maxCount = 7875;
        System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint);
        for (int count = 0, prime = 1; count < maxCount; ++prime) {
            if (erdos(sieve, prime)) {
                ++count;
                if (prime < maxPrint) {
                    System.out.printf("%6d", prime);
                    if (count % 10 == 0)
                        System.out.println();
                }
                if (count == maxCount)
                    System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime);
            }
        }
    }

    private static boolean erdos(boolean[] sieve, int p) {
        if (!sieve[p])
            return false;
        for (int k = 1, f = 1; f < p; ++k, f *= k) {
            if (sieve[p - f])
                return false;
        }
        return true;
    }

    private static boolean[] primeSieve(int limit) {
        boolean[] sieve = new boolean[limit];
        Arrays.fill(sieve, true);
        if (limit > 0)
            sieve[0] = false;
        if (limit > 1)
            sieve[1] = false;
        for (int i = 4; i < limit; i += 2)
            sieve[i] = false;
        for (int p = 3; ; p += 2) {
            int q = p * p;
            if (q >= limit)
                break;
            if (sieve[p]) {
                int inc = 2 * p;
                for (; q < limit; q += inc)
                    sieve[q] = false;
            }
        }
        return sieve;
    }
}
Task: Break OO privacy


C++: #include <iostream>

class CWidget; 

class CFactory
{
  friend class CWidget;
private:
  unsigned int m_uiCount;
public:
  CFactory();
  ~CFactory();
  CWidget* GetWidget();
};

class CWidget
{
private:
  CFactory& m_parent;

private:
  CWidget(); 
  CWidget(const CWidget&); 
  CWidget& operator=(const CWidget&); 
public:
  CWidget(CFactory& parent);
  ~CWidget();
};


CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}


CWidget* CFactory::GetWidget()
{
  
  return new CWidget(*this);
}


CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
  ++m_parent.m_uiCount;

  std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

CWidget::~CWidget()
{
  --m_parent.m_uiCount;

  std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

int main()
{
  CFactory factory;

  CWidget* pWidget1 = factory.GetWidget();
  CWidget* pWidget2 = factory.GetWidget();
  delete pWidget1;

  CWidget* pWidget3 = factory.GetWidget();
  delete pWidget3;
  delete pWidget2;
}




Java: module BreakOO
    {
    
    class Exposed
        {
        public    String pub = "public";
        protected String pro = "protected";
        private   String pri = "private";

        @Override
        String toString()
            {
            return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
            }
        }

    void run()
        {
        @Inject Console console;

        Exposed expo = new Exposed();
        console.print($"before: {expo}");

        
        expo.pub = $"this was {expo.pub}";
     
     

        
        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
        expoPro.pro = $"this was {expoPro.pro}";
     

        
        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
        expoPri.pri = $"this was {expoPri.pri}";

        
        
        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
        expoStr.pub = $"{expoStr.pub}!!!";
        expoStr.pro = $"{expoStr.pro}!!!";
        expoStr.pri = $"{expoStr.pri}!!!";

        console.print($"after: {expo}");
        }
    }
Task: Long year


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



int p(int year) {
	return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}

int is_long_year(int year) {
	return p(year) == 4 || p(year - 1) == 3;
}

void print_long_years(int from, int to) {
	for (int year = from; year <= to; ++year) {
		if (is_long_year(year)) {
			printf("%d ", year);
		}
	}
}

int main() {

	printf("Long (53 week) years between 1800 and 2100\n\n");
	print_long_years(1800, 2100);
	printf("\n");
	return 0;
}




Java: import java.time.LocalDate;
import java.time.temporal.WeekFields;

public class LongYear {

    public static void main(String[] args) {
        System.out.printf("Long years this century:%n");
        for (int year = 2000 ; year < 2100 ; year++ ) {
            if ( longYear(year) ) {
                System.out.print(year + "  ");
            }
        }
    }
    
    private static boolean longYear(int year) {
        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;
    }

}
Task: Associative array_Merging


C++: #include <iostream>
#include <string>
#include <map>

template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
    map_type result(update);
    result.insert(original.begin(), original.end());
    return result;
}

int main() {
    typedef std::map<std::string, std::string> map;
    map original{
        {"name", "Rocket Skates"},
        {"price", "12.75"},
        {"color", "yellow"}
    };
    map update{
        {"price", "15.25"},
        {"color", "red"},
        {"year", "1974"}
    };
    map merged(merge(original, update));
    for (auto&& i : merged)
        std::cout << "key: " << i.first << ", value: " << i.second << '\n';
    return 0;
}




Java: import java.util.*;

class MergeMaps {
    public static void main(String[] args) {
        Map<String, Object> base = new HashMap<>();
        base.put("name", "Rocket Skates");
        base.put("price", 12.75);
        base.put("color", "yellow");
        Map<String, Object> update = new HashMap<>();
        update.put("price", 15.25);
        update.put("color", "red");
        update.put("year", 1974);

        Map<String, Object> result = new HashMap<>(base);
        result.putAll(update);

        System.out.println(result);
    }
}
Task: Constrained genericity


C++: template<typename T> 
struct can_eat       
{
  private:
    template<typename U, void (U::*)()> struct SFINAE {};
    template<typename U> static char Test(SFINAE<U, &U::eat>*);
    template<typename U> static int Test(...);
  public:
    static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);
};

struct potato
{ void eat(); };

struct brick
{};

template<typename T>
class FoodBox
{
    
    static_assert(can_eat<T>::value, "Only edible items are allowed in foodbox");

    
};

int main()
{
    FoodBox<potato> lunch;

    
    
}




Java: interface Eatable
{
    void eat();
}
Task: Associative array_Iteration


C++: #include <iostream>
#include <map>
#include <string>

int main() {
  std::map<std::string, int> dict {
    {"One", 1},
    {"Two", 2},
    {"Three", 7}
  };

  dict["Three"] = 3;

  std::cout << "One: " << dict["One"] << std::endl;
  std::cout << "Key/Value pairs: " << std::endl;
  for(auto& kv: dict) {
    std::cout << "  " << kv.first << ": " << kv.second << std::endl;
  }

  return 0;
}




Java: Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);


for (Map.Entry<String, Integer> e : map.entrySet()) {
    String key = e.getKey();
    Integer value = e.getValue();
    System.out.println("key = " + key + ", value = " + value);
}


for (String key : map.keySet()) {
    System.out.println("key = " + key);
}


for (Integer value : map.values()) {
    System.out.println("value = " + value);
}
Task: Define a primitive data type


C++: #include <stdexcept>

class tiny_int
{
public:
  tiny_int(int i):
    value(i)
  {
    if (value < 1)
      throw std::out_of_range("tiny_int: value smaller than 1");
    if (value > 10)
      throw std::out_of_range("tiny_int: value larger than 10");
  }
  operator int() const
  {
    return value;
  }
  tiny_int& operator+=(int i)
  {
    
    
    *this = value + i;
    return *this;
  }
  tiny_int& operator-=(int i)
  {
    *this = value - i;
    return *this;
  }
  tiny_int& operator*=(int i)
  {
    *this = value * i;
    return *this;
  }
  tiny_int& operator/=(int i)
  {
    *this = value / i;
    return *this;
  }
  tiny_int& operator<<=(int i)
  {
    *this = value << i;
    return *this;
  }
  tiny_int& operator>>=(int i)
  {
    *this = value >> i;
    return *this;
  }
  tiny_int& operator&=(int i)
  {
    *this = value & i;
    return *this;
  }
  tiny_int& operator|=(int i)
  {
    *this = value | i;
    return *this;
  }
private:
  unsigned char value; 
};




Java: class BoundedIntOutOfBoundsException extends Exception
{
  public BoundedIntOutOfBoundsException(int v, int l, int u) {
    super("value " + v + " is out of bounds [" + l + "," + u + "]");
  }
}

class BoundedInt {
  private int value;
  private int lower;
  private int upper;

  public BoundedInt(int l, int u) {
    lower = Math.min(l, u);
    upper = Math.max(l, u);
  }

  private boolean checkBounds(int v) {
    return (v >= this.lower) && (v <= this.upper);
  }

  public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
    assign(i.value()); 
  }

  public void assign(int v) throws BoundedIntOutOfBoundsException {
    if ( checkBounds(v) ) {
      this.value = v;
    } else {
      throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);
    }
  }

  public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {
    return add(i.value());
  }

  public int add(int i) throws BoundedIntOutOfBoundsException {
    if ( checkBounds(this.value + i) ) {
      this.value += i;
    }  else {
      throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);
    }
    return this.value;
  }

  public int value() {
    return this.value;
  }
}


public class Bounded {
  public static void main(String[] args) throws BoundedIntOutOfBoundsException {
    BoundedInt a = new BoundedInt(1, 10);
    BoundedInt b = new BoundedInt(1, 10);

    a.assign(6);
    try {
      b.assign(12);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    b.assign(9);
    try {
      a.add(b.value());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}
Task: Here document


C++: #include <iostream> 

int main()
{
  std::cout <<
R"EOF(  A  raw  string  begins  with  R,  then a double-quote ("),  then an optional
identifier (here I've used "EOF"),  then an opening parenthesis ('(').  If you
use  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot
contain a space,  either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.

  It  ends with a closing parenthesis (')'),  the identifer (if you used one),
and a double-quote.

  All  characters are okay in a raw string,  no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}




Java: package rosettacode.heredoc;
public class MainApp {
	public static void main(String[] args) {
		String hereDoc = """
				This is a multiline string.
				It includes all of this text,
				but on separate lines in the code.
				 """;
		System.out.println(hereDoc);
	}
}
Task: Hash join


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

using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {

  {"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};

tab_t tab2 {

  {"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};

std::ostream& operator<<(std::ostream& o, const tab_t& t) {
  for(size_t i = 0; i < t.size(); ++i) {
    o << i << ":";
    for(const auto& e : t[i]) 
      o << '\t' << e;
    o << std::endl;
  }
  return o;
}

tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
  std::unordered_multimap<std::string, size_t> hashmap;
  
  for(size_t i = 0; i < a.size(); ++i) {
    hashmap.insert(std::make_pair(a[i][columna], i));
  }
  
  tab_t result;
  for(size_t i = 0; i < b.size(); ++i) {
    auto range = hashmap.equal_range(b[i][columnb]);
    for(auto it = range.first; it != range.second; ++it) {
      tab_t::value_type row;
      row.insert(row.end() , a[it->second].begin() , a[it->second].end());
      row.insert(row.end() , b[i].begin()          , b[i].end());
      result.push_back(std::move(row));
    }
  }
  return result;
}

int main(int argc, char const *argv[])
{
  using namespace std;
  int ret = 0;
  cout << "Table A: "       << endl << tab1 << endl;
  cout << "Table B: "       << endl << tab2 << endl;
  auto tab3 = Join(tab1, 1, tab2, 0);
  cout << "Joined tables: " << endl << tab3 << endl;
  return ret;
}




Java: import java.util.*;

public class HashJoin {

    public static void main(String[] args) {
        String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
        {"18", "Popeye"}, {"28", "Alan"}};

        String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
        {"Bob", "foo"}};

        hashJoin(table1, 1, table2, 0).stream()
                .forEach(r -> System.out.println(Arrays.deepToString(r)));
    }

    static List<String[][]> hashJoin(String[][] records1, int idx1,
            String[][] records2, int idx2) {

        List<String[][]> result = new ArrayList<>();
        Map<String, List<String[]>> map = new HashMap<>();

        for (String[] record : records1) {
            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
            v.add(record);
            map.put(record[idx1], v);
        }

        for (String[] record : records2) {
            List<String[]> lst = map.get(record[idx2]);
            if (lst != null) {
                lst.stream().forEach(r -> {
                    result.add(new String[][]{r, record});
                });
            }
        }

        return result;
    }
}
Task: Polynomial synthetic division


C++: 

#include <iostream>
#include <vector>
#include <string>
#include <cmath>



std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
	std::string r = "";

	if (remainder) 
	{
		r = " r: " + std::to_string(polynomial.back());
		polynomial.pop_back();
	}

	std::string formatted = "";
	
	int degree = polynomial.size() - 1;
	int d = degree;

	for (int i : polynomial)
	{
		if (d < degree)
		{
			if (i >= 0) 
			{
				formatted += " + ";
			}
			else
			{
				formatted += " - ";
			}
		}

		formatted += std::to_string(abs(i));

		if (d > 1)
		{
			formatted += "x^" + std::to_string(d);
		}
		else if (d == 1)
		{
			formatted += "x";
		}

		d--;
	}

	return formatted;
}



std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
	std::vector<int> quotient;
	quotient = dividend;

	int normalizer = divisor[0];
	
	for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
	{
		quotient[i] /= normalizer;
		int coef = quotient[i];

		if (coef != 0) 
		{
			for (int j = 1; j < divisor.size(); j++)
			{
				quotient[i + j] += -divisor[j] * coef;
			}
        }

	}

	return quotient;
}



int main(int argc, char **argv) 
{
	std::vector<int> dividend{ 1, -12, 0, -42};
	std::vector<int> divisor{ 1, -3};

	std::cout << frmtPolynomial(dividend) << "\n";
	std::cout << frmtPolynomial(divisor) << "\n";

	std::vector<int> quotient = syntheticDiv(dividend, divisor);

	std::cout << frmtPolynomial(quotient, true) << "\n";

}




Java: import java.util.Arrays;

public class Test {

    public static void main(String[] args) {
        int[] N = {1, -12, 0, -42};
        int[] D = {1, -3};

        System.out.printf("%s / %s = %s",
                Arrays.toString(N),
                Arrays.toString(D),
                Arrays.deepToString(extendedSyntheticDivision(N, D)));
    }

    static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
        int[] out = dividend.clone();
        int normalizer = divisor[0];

        for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
            out[i] /= normalizer;

            int coef = out[i];
            if (coef != 0) {
                for (int j = 1; j < divisor.length; j++)
                    out[i + j] += -divisor[j] * coef;
            }
        }

        int separator = out.length - (divisor.length - 1);

        return new int[][]{
            Arrays.copyOfRange(out, 0, separator),
            Arrays.copyOfRange(out, separator, out.length)
        };
    }
}