WeixiangYan/CodeTransOcean huggingface dataset:
Task: Find square difference


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

int main()
{
    const int maxSquareDiff = 1000;
    auto squareCheck = [maxSquareDiff](int i){return 2 * i - 1 > maxSquareDiff;};
    auto answer = std::views::iota(1) |  
      std::views::filter(squareCheck) |  
      std::views::take(1);               
    std::cout << answer.front() << '\n';
}
Task: Hickerson series of almost integers


C++: #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;

int main()
{
    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
    decfloat numerator = 1, denominator = ln_two;
    
    for(int n = 1; n <= 17; n++) {
        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;
        decfloat tenths_dig = floor((h - floor(h)) * 10);
        std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << 
            (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n";
    }
}
Task: Extra primes


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

unsigned int next_prime_digit_number(unsigned int n) {
    if (n == 0)
        return 2;
    switch (n % 10) {
    case 2:
        return n + 1;
    case 3:
    case 5:
        return n + 2;
    default:
        return 2 + next_prime_digit_number(n/10) * 10;
    }
}

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if ((n & 1) == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    if (n % 5 == 0)
        return n == 5;
    static constexpr unsigned int wheel[] = { 4,2,4,2,4,6,2,6 };
    unsigned int p = 7;
    for (;;) {
        for (unsigned int w : wheel) {
            if (p * p > n)
                return true;
            if (n % p == 0)
                return false;
            p += w;
        }
    }
}

unsigned int digit_sum(unsigned int n) {
    unsigned int sum = 0;
    for (; n > 0; n /= 10)
        sum += n % 10;
    return sum;
}

int main() {
    std::cout.imbue(std::locale(""));
    const unsigned int limit1 = 10000;
    const unsigned int limit2 = 1000000000;
    const int last = 10;
    unsigned int p = 0, n = 0;
    unsigned int extra_primes[last];
    std::cout << "Extra primes under " << limit1 << ":\n";
    while ((p = next_prime_digit_number(p)) < limit2) {
        if (is_prime(digit_sum(p)) && is_prime(p)) {
            ++n;
            if (p < limit1)
                std::cout << std::setw(2) << n << ": " << p << '\n';
            extra_primes[n % last] = p;
        }
    }
    std::cout << "\nLast " << last << " extra primes under " << limit2 << ":\n";
    for (int i = last - 1; i >= 0; --i)
        std::cout << n-i << ": " << extra_primes[(n-i) % last] << '\n';
    return 0;
}
Task: Sorting algorithms_Shell sort


C++: #include <time.h>
#include <iostream>


using namespace std;


const int MAX = 126;
class shell
{
public:
    shell() 
    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }

    void sort( int* a, int count )
    {
	_cnt = count;
	for( int x = 0; x < 9; x++ )
	    if( count > _gap[x] )
	    { _idx = x; break; }

	sortIt( a );
    }

private:	
    void sortIt( int* arr )
    {
	bool sorted = false;
	while( true )
	{
	    sorted = true;
	    int st = 0;
	    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
	    {
		if( arr[st] > arr[x] )
		{ swap( arr[st], arr[x] ); sorted = false; }
		st = x;
	    }
	    if( ++_idx >= 8 ) _idx = 8;
	    if( sorted && _idx == 8 ) break;
	}
    }

    void swap( int& a, int& b ) { int t = a; a = b; b = t; }

    int _gap[9], _idx, _cnt;
};

int main( int argc, char* argv[] )
{
    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];
    for( int x = 0; x < MAX; x++ )
	arr[x] = rand() % MAX - rand() % MAX;

    cout << " Before: \n=========\n";
    for( int x = 0; x < 7; x++ )
    {
	for( int a = 0; a < 18; a++ )
	{ cout << arr[x * 18 + a] << " "; }
	cout << endl;
    }
    cout << endl; shell s; s.sort( arr, MAX );
	
    cout << " After: \n========\n";
    for( int x = 0; x < 7; x++ )
    {
	for( int a = 0; a < 18; a++ )
	{ cout << arr[x * 18 + a] << " "; }
	cout << endl;
    }
    cout << endl << endl; return system( "pause" );
}
Task: Dice game probabilities


C++: #include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <map>


std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {
    std::map<uint32_t, uint32_t> result;
    for (uint32_t i = 1; i <= faces; ++i)
        result.emplace(i, 1);
    for (uint32_t d = 2; d <= dice; ++d) {
        std::map<uint32_t, uint32_t> tmp;
        for (const auto& p : result) {
            for (uint32_t i = 1; i <= faces; ++i)
                tmp[p.first + i] += p.second;
        }
        tmp.swap(result);
    }
    return result;
}

double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {
    auto totals1 = get_totals(dice1, faces1);
    auto totals2 = get_totals(dice2, faces2);
    double wins = 0;
    for (const auto& p1 : totals1) {
        for (const auto& p2 : totals2) {
            if (p2.first >= p1.first)
                break;
            wins += p1.second * p2.second;
        }
    }
    double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);
    return wins/total;
}

int main() {
    std::cout << std::setprecision(10);
    std::cout << probability(9, 4, 6, 6) << '\n';
    std::cout << probability(5, 10, 6, 7) << '\n';
    return 0;
}
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 ;
}
Task: Largest proper divisor of n


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

int largest_proper_divisor(int n) {
    assert(n > 0);
    if ((n & 1) == 0)
        return n >> 1;
    for (int p = 3; p * p <= n; p += 2) {
        if (n % p == 0)
            return n / p;
    }
    return 1;
}

int main() {
    for (int n = 1; n < 101; ++n) {
        std::cout << std::setw(2) << largest_proper_divisor(n)
            << (n % 10 == 0 ? '\n' : ' ');
    }
}
Task: Numbers with equal rises and falls


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

bool equal_rises_and_falls(int n) {
    int total = 0;
    for (int previous_digit = -1; n > 0; n /= 10) {
        int digit = n % 10;
        if (previous_digit > digit)
            ++total;
        else if (previous_digit >= 0 && previous_digit < digit)
            --total;
        previous_digit = digit;
    }
    return total == 0;
}

int main() {
    const int limit1 = 200;
    const int limit2 = 10000000;
    int n = 0;
    std::cout << "The first " << limit1 << " numbers in the sequence are:\n";
    for (int count = 0; count < limit2; ) {
        if (equal_rises_and_falls(++n)) {
            ++count;
            if (count <= limit1)
                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' ');
        }
    }
    std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n";
}
Task: Pseudo-random numbers_Combined recursive generator MRG32k3a


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

int64_t mod(int64_t x, int64_t y) {
    int64_t m = x % y;
    if (m < 0) {
        if (y < 0) {
            return m - y;
        } else {
            return m + y;
        }
    }
    return m;
}

class RNG {
private:
    
    const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };
    const int64_t m1 = (1LL << 32) - 209;
    std::array<int64_t, 3> x1;
    
    const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };
    const int64_t m2 = (1LL << 32) - 22853;
    std::array<int64_t, 3> x2;
    
    const int64_t d = (1LL << 32) - 209 + 1; 

public:
    void seed(int64_t state) {
        x1 = { state, 0, 0 };
        x2 = { state, 0, 0 };
    }

    int64_t next_int() {
        int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);
        int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);
        int64_t z = mod(x1i - x2i, m1);

        
        x1 = { x1i, x1[0], x1[1] };
        
        x2 = { x2i, x2[0], x2[1] };

        return z + 1;
    }

    double next_float() {
        return static_cast<double>(next_int()) / d;
    }
};

int main() {
    RNG rng;

    rng.seed(1234567);
    std::cout << rng.next_int() << '\n';
    std::cout << rng.next_int() << '\n';
    std::cout << rng.next_int() << '\n';
    std::cout << rng.next_int() << '\n';
    std::cout << rng.next_int() << '\n';
    std::cout << '\n';

    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };
    rng.seed(987654321);
    for (size_t i = 0; i < 100000; i++) 		{
        auto value = floor(rng.next_float() * 5.0);
        counts[value]++;
    }
    for (size_t i = 0; i < counts.size(); i++) 		{
        std::cout << i << ": " << counts[i] << '\n';
    }

    return 0;
}
Task: Find words which contains more than 3 e vowels


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

bool test(const std::string &line) {
    unsigned int e = 0;
    for (char c : line) {
        switch(std::tolower(c)) {
            case 'a': return false;
            case 'i': return false;
            case 'o': return false;
            case 'u': return false;
            case 'e': ++e;
        }
    }
    return e > 3;
}

int main() {
    std::ifstream dict{"unixdict.txt"};
    
    if (! dict.is_open()) {
        std::cerr << "Cannot open unixdict.txt\n";
        return 3;
    }
    
    for (std::string line; std::getline(dict, line);) {
        if (test(line)) std::cout << line << std::endl;
    }
    
    return 0;
}
Task: Find words with alternating vowels and consonants


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

bool is_vowel(char ch) {
    switch (ch) {
    case 'a': case 'A':
    case 'e': case 'E':
    case 'i': case 'I':
    case 'o': case 'O':
    case 'u': case 'U':
        return true;
    }
    return false;
}

bool alternating_vowels_and_consonants(const std::string& str) {
    for (size_t i = 1, len = str.size(); i < len; ++i) {
        if (is_vowel(str[i]) == is_vowel(str[i - 1]))
            return false;
    }
    return true;
}

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;
    for (int n = 1; getline(in, line); ) {
        if (line.size() > 9 && alternating_vowels_and_consonants(line))
            std::cout << std::setw(2) << n++ << ": " << line << '\n';
    }
    return EXIT_SUCCESS;
}
Task: Words containing _the_ substring


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

int main() {
    std::string word;
    std::ifstream file("unixdict.txt");
 
    if (!file) {
        std::cerr << "Cannot open unixdict.txt" << std::endl;
        return -1;
    }
    while (file >> word) {
        if (word.length() > 11 && word.find("the") != std::string::npos)
            std::cout << word << std::endl;
    }
    return 0;
}
Task: Special characters


C++: std::cout << "Tür\n";
std::cout << "T\u00FC\n";
Task: Base 16 numbers needing a to f


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



bool nondecimal(unsigned int n) {
    for (; n > 0; n >>= 4) {
        if ((n & 0xF) > 9)
            return true;
    }
    return false;
}

int main() {
    unsigned int count = 0;
    for (unsigned int n = 0; n < 501; ++n) {
        if (nondecimal(n)) {
            ++count;
            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
        }
    }
    std::cout << "\n\n" << count << " such numbers found.\n";
}
Task: Find words whose first and last three letters are equal


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

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 word;
    int n = 0;
    while (getline(in, word)) {
        const size_t len = word.size();
        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
            std::cout << ++n << ": " << word << '\n';
    }
    return EXIT_SUCCESS;
}
Task: Find words which contains all the vowels


C++: #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>

bool contains_all_vowels_once(const std::string& word) {
    std::bitset<5> vowels;
    for (char ch : word) {
        ch = std::tolower(static_cast<unsigned char>(ch));
        size_t bit = 0;
        switch (ch) {
        case 'a': bit = 0; break;
        case 'e': bit = 1; break;
        case 'i': bit = 2; break;
        case 'o': bit = 3; break;
        case 'u': bit = 4; break;
        default: continue;
        }
        if (vowels.test(bit))
            return false;
        vowels.set(bit);
    }
    return vowels.all();
}

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 word;
    int n = 0;
    while (getline(in, word)) {
        if (word.size() > 10 && contains_all_vowels_once(word))
            std::cout << std::setw(2) << ++n << ": " << word << '\n';
    }
    return EXIT_SUCCESS;
}
Task: Summarize primes


C++: #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;
    }

    int i = 5;
    while (i * i <= n) {
        if (n % i == 0) {
            return false;
        }
        i += 2;

        if (n % i == 0) {
            return false;
        }
        i += 4;
    }

    return true;
}

int main() {
    const int start = 1;
    const int stop = 1000;

    int sum = 0;
    int count = 0;
    int sc = 0;

    for (int p = start; p < stop; p++) {
        if (is_prime(p)) {
            count++;
            sum += p;
            if (is_prime(sum)) {
                printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
                sc++;
            }
        }
    }
    printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);

    return 0;
}
Task: Determinant and permanent


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

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
    auto it = v.cbegin();
    auto end = v.cend();

    os << '[';
    if (it != end) {
        os << *it;
        it = std::next(it);
    }
    while (it != end) {
        os << ", " << *it;
        it = std::next(it);
    }
    return os << ']';
}

using Matrix = std::vector<std::vector<double>>;

Matrix squareMatrix(size_t n) {
    Matrix m;
    for (size_t i = 0; i < n; i++) {
        std::vector<double> inner;
        for (size_t j = 0; j < n; j++) {
            inner.push_back(nan(""));
        }
        m.push_back(inner);
    }
    return m;
}

Matrix minor(const Matrix &a, int x, int y) {
    auto length = a.size() - 1;
    auto result = squareMatrix(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;
}

double det(const Matrix &a) {
    if (a.size() == 1) {
        return a[0][0];
    }

    int sign = 1;
    double sum = 0;
    for (size_t i = 0; i < a.size(); i++) {
        sum += sign * a[0][i] * det(minor(a, 0, i));
        sign *= -1;
    }
    return sum;
}

double perm(const Matrix &a) {
    if (a.size() == 1) {
        return a[0][0];
    }

    double sum = 0;
    for (size_t i = 0; i < a.size(); i++) {
        sum += a[0][i] * perm(minor(a, 0, i));
    }
    return sum;
}

void test(const Matrix &m) {
    auto p = perm(m);
    auto d = det(m);

    std::cout << m << '\n';
    std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n";
}

int main() {
    test({ {1, 2}, {3, 4} });
    test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });
    test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });

    return 0;
}
Task: Recaman's sequence


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

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
    auto i = v.cbegin();
    auto e = v.cend();
    os << '[';
    if (i != e) {
        os << *i;
        i = std::next(i);
    }
    while (i != e) {
        os << ", " << *i;
        i = std::next(i);
    }
    return os << ']';
}

int main() {
    using namespace std;

    vector<int> a{ 0 };
    set<int> used{ 0 };
    set<int> used1000{ 0 };
    bool foundDup = false;
    int n = 1;
    while (n <= 15 || !foundDup || used1000.size() < 1001) {
        int next = a[n - 1] - n;
        if (next < 1 || used.find(next) != used.end()) {
            next += 2 * n;
        }
        bool alreadyUsed = used.find(next) != used.end();
        a.push_back(next);
        if (!alreadyUsed) {
            used.insert(next);
            if (0 <= next && next <= 1000) {
                used1000.insert(next);
            }
        }
        if (n == 14) {
            cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
        }
        if (!foundDup && alreadyUsed) {
            cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
            foundDup = true;
        }
        if (used1000.size() == 1001) {
            cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
        }
        n++;
    }

    return 0;
}
Task: Descending primes


C++: #include <iostream>

bool ispr(unsigned int n) {
    if ((n & 1) == 0 || n < 2) return n == 2;
    for (unsigned int j = 3; j * j <= n; j += 2)
      if (n % j == 0) return false; return true; }

int main() {
  unsigned int c = 0, nc, pc = 9, i, a, b, l,
    ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];
  while (true) {
    nc = 0;
    for (i = 0; i < pc; i++) {
        if (ispr(a = ps[i]))
          printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
        for (b = a * 10, l = a % 10 + b++; b < l; b++)
          nxt[nc++] = b;
      }
      if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
      else break;
    }
    printf("\n%d descending primes found", c);
}
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());
}
Task: Odd squarefree semiprimes


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

bool odd_square_free_semiprime(int n) {
    if ((n & 1) == 0)
        return false;
    int count = 0;
    for (int i = 3; i * i <= n; i += 2) {
        for (; n % i == 0; n /= i) {
            if (++count > 1)
                return false;
        }
    }
    return count == 1;
}

int main() {
    const int n = 1000;
    std::cout << "Odd square-free semiprimes < " << n << ":\n";
    int count = 0;
    for (int i = 1; i < n; i += 2) {
        if (odd_square_free_semiprime(i)) {
            ++count;
            std::cout << std::setw(4) << i;
            if (count % 20 == 0)
                std::cout << '\n';
        }
    }
    std::cout << "\nCount: " << count << '\n';
    return 0;
}
Task: Harmonic series


C++: #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/gmp.hpp>

using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;

class harmonic_generator {
public:
    rational next() {
        rational result = term_;
        term_ += rational(1, ++n_);
        return result;
    }
    void reset() {
        n_ = 1;
        term_ = 1;
    }
private:
    integer n_ = 1;
    rational term_ = 1;
};

int main() {
    std::cout << "First 20 harmonic numbers:\n";
    harmonic_generator hgen;
    for (int i = 1; i <= 20; ++i)
        std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';
    
    rational h;
    for (int i = 1; i <= 80; ++i)
        h = hgen.next();
    std::cout << "\n100th harmonic number: " << h << "\n\n";

    int n = 1;
    hgen.reset();
    for (int i = 1; n <= 10; ++i) {
        if (hgen.next() > n)
            std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
    }
}
Task: Generate Chess960 starting position


C++: #include <iostream>
#include <string>
#include <time.h>
using namespace std;

namespace
{
    void placeRandomly(char* p, char c)
    {
	int loc = rand() % 8;
	if (!p[loc])
	    p[loc] = c;
	else
	    placeRandomly(p, c);    
    }
    int placeFirst(char* p, char c, int loc = 0)
    {
	while (p[loc]) ++loc;
	p[loc] = c;
        return loc;
    }

    string startPos()
    {
	char p[8]; memset( p, 0, 8 );

	
	p[2 * (rand() % 4)] = 'B';
	p[2 * (rand() % 4) + 1] = 'B';

	
	for (char c : "QNN")
	    placeRandomly(p, c);

	
	placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));

	return string(p, 8);
    }
}   

namespace chess960
{
    void generate( int c )
    {
	for( int x = 0; x < c; x++ )
	    cout << startPos() << "\n";
    }
}

int main( int argc, char* argv[] )
{
    srand( time( NULL ) );
    chess960::generate( 10 );
    cout << "\n\n";
    return system( "pause" );
}