WeixiangYan/CodeTransOcean huggingface dataset:
Task: Zumkeller numbers


C++: #include <iostream">
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <numeric>

using namespace std;


const uint* binary(uint n, uint length);



uint sum_subset_unrank_bin(const vector<uint>& d, uint r);

vector<uint> factors(uint x);

bool isPrime(uint number);

bool isZum(uint n);

ostream& operator<<(ostream& os, const vector<uint>& zumz) {
    for (uint i = 0; i < zumz.size(); i++) {
        if (i % 10 == 0)
            os << endl;
        os << setw(10) << zumz[i] << ' ';
    }
    return os;
}

int main() {
    cout << "First 220 Zumkeller numbers:" << endl;
    vector<uint> zumz;
    for (uint n = 2; zumz.size() < 220; n++)
        if (isZum(n))
            zumz.push_back(n);
    cout << zumz << endl << endl;

    cout << "First 40 odd Zumkeller numbers:" << endl;
    vector<uint> zumz2;
    for (uint n = 2; zumz2.size() < 40; n++)
        if (n % 2 && isZum(n))
            zumz2.push_back(n);
    cout << zumz2 << endl << endl;

    cout << "First 40 odd Zumkeller numbers not ending in 5:" << endl;
    vector<uint> zumz3;
    for (uint n = 2; zumz3.size() < 40; n++)
        if (n % 2 && (n % 10) !=  5 && isZum(n))
            zumz3.push_back(n);
    cout << zumz3 << endl << endl;

    return 0;
}


const uint* binary(uint n, uint length) {
    uint* bin = new uint[length];	    
    fill(bin, bin + length, 0);         
    
    for (uint i = 0; n > 0; i++) {
        uint rem = n % 2;
        n /= 2;
        if (rem)
            bin[length - 1 - i] = 1;
    }

    return bin;
}



uint sum_subset_unrank_bin(const vector<uint>& d, uint r) {
    vector<uint> subset;
    
    const uint* bits = binary(r, d.size() - 1);

    
    for (uint i = 0; i < d.size() - 1; i++)
        if (bits[i])
            subset.push_back(d[i]);

    delete[] bits;

    return accumulate(subset.begin(), subset.end(), 0u);
}

vector<uint> factors(uint x) {
    vector<uint> result;
    
    for (uint i = 1; i * i <= x; i++) {
        
        if (x % i == 0) {
            result.push_back(i);

            if (x / i != i)
                result.push_back(x / i);
        }
    }

    
    sort(result.begin(), result.end());
    return result;
}

bool isPrime(uint number) {
    if (number < 2) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;
    for (uint i = 3; i * i <= number; i += 2)
        if (number % i == 0) return false;

    return true;
}

bool isZum(uint n) {
    
    if (isPrime(n))
        return false;

    
    const auto d = factors(n);
    uint s = accumulate(d.begin(), d.end(), 0u);

    
    if (s % 2 || s < 2 * n)
        return false;

    
    
    
    if (n % 2 || d.size() >= 24)
        return true;

    if (!(s % 2) && d[d.size() - 1] <= s / 2)
        for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) 
            if (sum_subset_unrank_bin(d, x) == s / 2)
                return true; 

    
    return false;
}
Task: Suffix tree


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

struct Node {
    std::string sub = "";   
    std::vector<int> ch;    

    Node() {
        
    }

    Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {
        ch.insert(ch.end(), children);
    }
};

struct SuffixTree {
    std::vector<Node> nodes;

    SuffixTree(const std::string& str) {
        nodes.push_back(Node{});
        for (size_t i = 0; i < str.length(); i++) {
            addSuffix(str.substr(i));
        }
    }

    void visualize() {
        if (nodes.size() == 0) {
            std::cout << "<empty>\n";
            return;
        }

        std::function<void(int, const std::string&)> f;
        f = [&](int n, const std::string & pre) {
            auto children = nodes[n].ch;
            if (children.size() == 0) {
                std::cout << "- " << nodes[n].sub << '\n';
                return;
            }
            std::cout << "+ " << nodes[n].sub << '\n';

            auto it = std::begin(children);
            if (it != std::end(children)) do {
                if (std::next(it) == std::end(children)) break;
                std::cout << pre << "+-";
                f(*it, pre + "| ");
                it = std::next(it);
            } while (true);

            std::cout << pre << "+-";
            f(children[children.size() - 1], pre + "  ");
        };

        f(0, "");
    }

private:
    void addSuffix(const std::string & suf) {
        int n = 0;
        size_t i = 0;
        while (i < suf.length()) {
            char b = suf[i];
            int x2 = 0;
            int n2;
            while (true) {
                auto children = nodes[n].ch;
                if (x2 == children.size()) {
                    
                    n2 = nodes.size();
                    nodes.push_back(Node(suf.substr(i), {}));
                    nodes[n].ch.push_back(n2);
                    return;
                }
                n2 = children[x2];
                if (nodes[n2].sub[0] == b) {
                    break;
                }
                x2++;
            }
            
            auto sub2 = nodes[n2].sub;
            size_t j = 0;
            while (j < sub2.size()) {
                if (suf[i + j] != sub2[j]) {
                    
                    auto n3 = n2;
                    
                    n2 = nodes.size();
                    nodes.push_back(Node(sub2.substr(0, j), { n3 }));
                    nodes[n3].sub = sub2.substr(j); 
                    nodes[n].ch[x2] = n2;
                    break; 
                }
                j++;
            }
            i += j; 
            n = n2; 
        }
    }
};

int main() {
    SuffixTree("banana$").visualize();
}
Task: Markov chain text generator


C++: #include <ctime>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
class markov {
public:
    void create( std::string& file, unsigned int keyLen, unsigned int words ) {
        std::ifstream f( file.c_str(), std::ios_base::in );
        fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
        f.close();
        if( fileBuffer.length() < 1 ) return;
        createDictionary( keyLen );
        createText( words - keyLen );
    }
private:
    void createText( int w ) {
        std::string key, first, second;
        size_t next;
        std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();
        std::advance( it, rand() % dictionary.size() );
        key = ( *it ).first;
        std::cout << key;
        while( true ) {
            std::vector<std::string> d = dictionary[key];
            if( d.size() < 1 ) break;
            second = d[rand() % d.size()];
            if( second.length() < 1 ) break;
            std::cout << " " << second;
            if( --w < 0 ) break;
            next = key.find_first_of( 32, 0 );
            first = key.substr( next + 1 );
            key = first + " " + second;
        }
        std::cout << "\n";
    }
    void createDictionary( unsigned int kl ) {
        std::string w1, key;
        size_t wc = 0, pos, next;
        next = fileBuffer.find_first_not_of( 32, 0 );
        if( next == std::string::npos ) return;
        while( wc < kl ) {
            pos = fileBuffer.find_first_of( ' ', next );
            w1 = fileBuffer.substr( next, pos - next );
            key += w1 + " ";
            next = fileBuffer.find_first_not_of( 32, pos + 1 );
            if( next == std::string::npos ) return;
            wc++;
        }
        key = key.substr( 0, key.size() - 1 );
        while( true ) {
            next = fileBuffer.find_first_not_of( 32, pos + 1 );
            if( next == std::string::npos ) return;
            pos = fileBuffer.find_first_of( 32, next );
            w1 = fileBuffer.substr( next, pos - next );
            if( w1.size() < 1 ) break;
            if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) 
                dictionary[key].push_back( w1 );
            key = key.substr( key.find_first_of( 32 ) + 1 ) + " " + w1;
        }
    }
    std::string fileBuffer;
    std::map<std::string, std::vector<std::string> > dictionary;
};
int main( int argc, char* argv[] ) {
    srand( unsigned( time( 0 ) ) );
    markov m;
    m.create( std::string( "alice_oz.txt" ), 3, 200 );
    return 0;
}
Task: Playfair cipher


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

using namespace std;

class playfair
{
public:
    void doIt( string k, string t, bool ij, bool e )
    {
	createGrid( k, ij ); getTextReady( t, ij, e );
	if( e ) doIt( 1 ); else doIt( -1 );
	display();
    }

private:
    void doIt( int dir )
    {
	int a, b, c, d; string ntxt;
	for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
	{
	    if( getCharPos( *ti++, a, b ) )
		if( getCharPos( *ti, c, d ) )
		{
		    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
		    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
		    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
		}
	}
	_txt = ntxt;
    }

    void display()
    {
	cout << "\n\n OUTPUT:\n=========" << endl;
	string::iterator si = _txt.begin(); int cnt = 0;
	while( si != _txt.end() )
	{
	    cout << *si; si++; cout << *si << " "; si++;
	    if( ++cnt >= 26 ) cout << endl, cnt = 0;
	}
	cout << endl << endl;
    }

    char getChar( int a, int b )
    {
	return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
    }

    bool getCharPos( char l, int &a, int &b )
    {
	for( int y = 0; y < 5; y++ )
	    for( int x = 0; x < 5; x++ )
		if( _m[y][x] == l )
		{ a = x; b = y; return true; }

	return false;
    }

    void getTextReady( string t, bool ij, bool e )
    {
	for( string::iterator si = t.begin(); si != t.end(); si++ )
	{
	    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
	    if( *si == 'J' && ij ) *si = 'I';
	    else if( *si == 'Q' && !ij ) continue;
	    _txt += *si;
	}
	if( e )
	{
	    string ntxt = ""; size_t len = _txt.length();
	    for( size_t x = 0; x < len; x += 2 )
	    {
		ntxt += _txt[x];
		if( x + 1 < len )
		{
		    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
		    ntxt += _txt[x + 1];
		}
	    }
	    _txt = ntxt;
	}
	if( _txt.length() & 1 ) _txt += 'X';
    }

    void createGrid( string k, bool ij )
    {
	if( k.length() < 1 ) k = "KEYWORD"; 
	k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
	for( string::iterator si = k.begin(); si != k.end(); si++ )
	{
	    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
	    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
	    if( nk.find( *si ) == -1 ) nk += *si;
	}
	copy( nk.begin(), nk.end(), &_m[0][0] );
    }

    string _txt; char _m[5][5];
};

int main( int argc, char* argv[] )
{
    string key, i, txt; bool ij, e;
    cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
    cout << "Enter a en/decryption key: "; getline( cin, key ); 
    cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
    cout << "Enter the text: "; getline( cin, txt ); 
    playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
Task: Elementary cellular automaton_Infinite length


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

class oo {
public:
    void evolve( int l, int rule ) {
        std::string    cells = "O";
        std::cout << " Rule #" << rule << ":\n";
        for( int x = 0; x < l; x++ ) {
            addNoCells( cells );
            std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n";
            step( cells, rule );
        }
    }
private:
    void step( std::string& cells, int rule ) {
        int bin;
        std::string newCells;
        for( size_t i = 0; i < cells.length() - 2; i++ ) {
            bin = 0;
            for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {
                bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );
            }
            newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );
        }
        cells = newCells;
    }
    void addNoCells( std::string& s ) {
        char l = s.at( 0 ) == 'O' ? '.' : 'O',
             r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';
        s = l + s + r;
        s = l + s + r;
    }
};
int main( int argc, char* argv[] ) {
    oo o;
    o.evolve( 35, 90 );
    std::cout << "\n";
    return 0;
}
Task: Word break problem


C++: #include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>

struct string_comparator {
    using is_transparent = void;
    bool operator()(const std::string& lhs, const std::string& rhs) const {
        return lhs < rhs;
    }
    bool operator()(const std::string& lhs, const std::string_view& rhs) const {
        return lhs < rhs;
    }
    bool operator()(const std::string_view& lhs, const std::string& rhs) const {
        return lhs < rhs;
    }
};

using dictionary = std::set<std::string, string_comparator>;

template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
    std::string result;
    if (begin != end) {
        result += *begin++;
        for (; begin != end; ++begin) {
            result += sep;
            result += *begin;
        }
    }
    return result;
}

auto create_string(const std::string_view& s,
                   const std::vector<std::optional<size_t>>& v) {
    auto idx = s.size();
    std::vector<std::string_view> sv;
    while (v[idx].has_value()) {
        size_t prev = v[idx].value();
        sv.push_back(s.substr(prev, idx - prev));
        idx = prev;
    }
    std::reverse(sv.begin(), sv.end());
    return join(sv.begin(), sv.end(), ' ');
}

std::optional<std::string> word_break(const std::string_view& str,
                                      const dictionary& dict) {
    auto size = str.size() + 1;
    std::vector<std::optional<size_t>> possible(size);
    auto check_word = [&dict, &str](size_t i, size_t j)
            -> std::optional<size_t> {
        if (dict.find(str.substr(i, j - i)) != dict.end())
            return i;
        return std::nullopt;
    };
    for (size_t i = 1; i < size; ++i) {
        if (!possible[i].has_value())
            possible[i] = check_word(0, i);
        if (possible[i].has_value()) {
            for (size_t j = i + 1; j < size; ++j) {
                if (!possible[j].has_value())
                    possible[j] = check_word(i, j);
            }
            if (possible[str.size()].has_value())
                return create_string(str, possible);
        }
    }
    return std::nullopt;
}

int main(int argc, char** argv) {
    dictionary dict;
    dict.insert("a");
    dict.insert("bc");
    dict.insert("abc");
    dict.insert("cd");
    dict.insert("b");
    auto result = word_break("abcd", dict);
    if (result.has_value())
        std::cout << result.value() << '\n';
    return 0;
}
Task: Create an object_Native demonstration


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

using namespace std;

template<typename T>
class FixedMap : private T
{
    
    
    
    
    
    T m_defaultValues;
    
public:
    FixedMap(T map)
    : T(map), m_defaultValues(move(map)){}
    
    
    using T::cbegin;
    using T::cend;
    using T::empty;
    using T::find;
    using T::size;

    
    using T::at;
    using T::begin;
    using T::end;
    
    
    
    auto& operator[](typename T::key_type&& key)
    {
        
        return this->at(forward<typename T::key_type>(key));
    }
    
    
    
    void erase(typename T::key_type&& key)
    {
        T::operator[](key) = m_defaultValues.at(key);
    }

    
    void clear()
    {
        
        T::operator=(m_defaultValues);
    }
    
};


auto PrintMap = [](const auto &map)
{
    for(auto &[key, value] : map)
    {
        cout << "{" << key << " : " << value << "} ";
    }
    cout << "\n\n";
};

int main(void) 
{
    
    cout << "Map intialized with values\n";
    FixedMap<map<string, int>> fixedMap ({
        {"a", 1},
        {"b", 2}});
    PrintMap(fixedMap);
    
    cout << "Change the values of the keys\n";
    fixedMap["a"] = 55;
    fixedMap["b"] = 56;
    PrintMap(fixedMap);
    
    cout << "Reset the 'a' key\n";
    fixedMap.erase("a");
    PrintMap(fixedMap);
    
    cout << "Change the values the again\n";
    fixedMap["a"] = 88;
    fixedMap["b"] = 99;
    PrintMap(fixedMap);
    
    cout << "Reset all keys\n";
    fixedMap.clear();
    PrintMap(fixedMap);
  
    try
    {
        
        cout << "Try to add a new key\n";
        fixedMap["newKey"] = 99;
    }
    catch (exception &ex)
    {
        cout << "error: " << ex.what();
    }
}
Task: De Polignac numbers


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

bool is_prime(int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

bool is_depolignac_number(int n) {
    for (int p = 1; p < n; p <<= 1) {
        if (is_prime(n - p))
            return false;
    }
    return true;
}

int main() {
    std::cout.imbue(std::locale(""));
    std::cout << "First 50 de Polignac numbers:\n";
    for (int n = 1, count = 0; count < 10000; n += 2) {
        if (is_depolignac_number(n)) {
            ++count;
            if (count <= 50)
                std::cout << std::setw(5) << n
                          << (count % 10 == 0 ? '\n' : ' ');
            else if (count == 1000)
                std::cout << "\nOne thousandth: " << n << '\n';
            else if (count == 10000)
                std::cout << "\nTen thousandth: " << n << '\n';
        }
    }
}
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";

}
Task: Color wheel


C++: 
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>

namespace {

QColor hsvToRgb(int h, double s, double v) {
    double hp = h/60.0;
    double c = s * v;
    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
    double m = v - c;
    double r = 0, g = 0, b = 0;
    if (hp <= 1) {
        r = c;
        g = x;
    } else if (hp <= 2) {
        r = x;
        g = c;
    } else if (hp <= 3) {
        g = c;
        b = x;
    } else if (hp <= 4) {
        g = x;
        b = c;
    } else if (hp <= 5) {
        r = x;
        b = c;
    } else {
        r = c;
        b = x;
    }
    r += m;
    g += m;
    b += m;
    return QColor(r * 255, g * 255, b * 255);
}

}

ColorWheelWidget::ColorWheelWidget(QWidget *parent)
    : QWidget(parent) {
    setWindowTitle(tr("Color Wheel"));
    resize(400, 400);
}

void ColorWheelWidget::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    const QColor backgroundColor(0, 0, 0);
    const QColor white(255, 255, 255);
    painter.fillRect(event->rect(), backgroundColor);
    const int margin = 10;
    const double diameter = std::min(width(), height()) - 2*margin;
    QPointF center(width()/2.0, height()/2.0);
    QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
                diameter, diameter);
    for (int angle = 0; angle < 360; ++angle) {
        QColor color(hsvToRgb(angle, 1.0, 1.0));
        QRadialGradient gradient(center, diameter/2.0);
        gradient.setColorAt(0, white);
        gradient.setColorAt(1, color);
        QBrush brush(gradient);
        QPen pen(brush, 1.0);
        painter.setPen(pen);
        painter.setBrush(brush);
        painter.drawPie(rect, angle * 16, 16);
    }
}
Task: Factorial primes


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

#include <gmpxx.h>

using big_int = mpz_class;

std::string to_string(const big_int& num, size_t n) {
    std::string str = num.get_str();
    size_t len = str.size();
    if (len > n) {
        str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
        str += " (";
        str += std::to_string(len);
        str += " digits)";
    }
    return str;
}

bool is_probably_prime(const big_int& n) {
    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}

int main() {
    big_int f = 1;
    for (int i = 0, n = 1; i < 31; ++n) {
        f *= n;
        if (is_probably_prime(f - 1)) {
            ++i;
            std::cout << std::setw(2) << i << ": " << std::setw(3) << n
                      << "! - 1 = " << to_string(f - 1, 40) << '\n';
        }
        if (is_probably_prime(f + 1)) {
            ++i;
            std::cout << std::setw(2) << i << ": " << std::setw(3) << n
                      << "! + 1 = " << to_string(f + 1, 40) << '\n';
        }
    }
}
Task: Wagstaff primes


C++: #include <gmpxx.h>
#include <primesieve.hpp>

#include <iostream>

using big_int = mpz_class;

std::string to_string(const big_int& num, size_t n) {
    std::string str = num.get_str();
    size_t len = str.size();
    if (len > n) {
        str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
        str += " (";
        str += std::to_string(len);
        str += " digits)";
    }
    return str;
}

bool is_probably_prime(const big_int& n) {
    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}

int main() {
    const big_int one(1);
    primesieve::iterator pi;
    pi.next_prime();
    for (int i = 0; i < 24;) {
        uint64_t p = pi.next_prime();
        big_int n = ((one << p) + 1) / 3;
        if (is_probably_prime(n))
            std::cout << ++i << ": " << p << " - " << to_string(n, 30) << '\n';
    }
}