_id
stringlengths
2
5
text
stringlengths
7
10.9k
title
stringclasses
1 value
c336
class matrixNG { private: virtual void consumeTerm(){} virtual void consumeTerm(int n){} virtual const bool needTerm(){} protected: int cfn = 0, thisTerm; bool haveTerm = false; friend class NG; }; class NG_4 : public matrixNG { private: int a1, a, b1, b, t; const bool needTerm() { if (b1==0 and b==0) return false; if (b1==0 or b==0) return true; else thisTerm = a/b; if (thisTerm==(int)(a1/b1)){ t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; haveTerm=true; return false; } return true; } void consumeTerm(){a=a1; b=b1;} void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;} public: NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){} }; class NG : public ContinuedFraction { private: matrixNG* ng; ContinuedFraction* n[2]; public: NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;} NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;} const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;} const bool moreTerms(){ while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm(); return ng->haveTerm; } };
c337
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<unsigned long> continued_fraction(const rational& r) { unsigned long a = r.numerator(); unsigned long b = r.denominator(); std::vector<unsigned long> result; do { result.push_back(a/b); unsigned long c = a; a = b; b = c % b; } while (a != 1); if (result.size() > 0 && result.size() % 2 == 0) { --result.back(); result.push_back(1); } return result; } unsigned long term_number(const rational& r) { unsigned long result = 0; unsigned long d = 1; unsigned long p = 0; for (unsigned long n : continued_fraction(r)) { for (unsigned long i = 0; i < n; ++i, ++p) result |= (d << p); d = !d; } return result; } int main() { rational term = 1; std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n"; for (int i = 1; i <= 20; ++i) { std::cout << std::setw(2) << i << ": " << term << '\n'; term = calkin_wilf_next(term); } rational r(83116, 51639); std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n"; }
c338
#include <array> #include <chrono> #include <iomanip> #include <iostream> #include <vector> auto init_zc() { std::array<int, 1000> zc; zc.fill(0); zc[0] = 3; for (int x = 1; x <= 9; ++x) { zc[x] = 2; zc[10 * x] = 2; zc[100 * x] = 2; for (int y = 10; y <= 90; y += 10) { zc[y + x] = 1; zc[10 * y + x] = 1; zc[10 * (y + x)] = 1; } } return zc; } template <typename clock_type> auto elapsed(const std::chrono::time_point<clock_type>& t0) { auto t1 = clock_type::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0); return duration.count(); } int main() { auto zc = init_zc(); auto t0 = std::chrono::high_resolution_clock::now(); int trail = 1, first = 0; double total = 0; std::vector<int> rfs{1}; std::cout << std::fixed << std::setprecision(10); for (int f = 2; f <= 50000; ++f) { int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size(); for (int j = trail - 1; j < len || carry != 0; ++j) { if (j < len) carry += rfs[j] * f; d999 = carry % 1000; if (j < len) rfs[j] = d999; else rfs.push_back(d999); zeroes += zc[d999]; carry /= 1000; } while (rfs[trail - 1] == 0) ++trail; d999 = rfs.back(); d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0; zeroes -= d999; int digits = rfs.size() * 3 - d999; total += double(zeroes) / digits; double ratio = total / f; if (ratio >= 0.16) first = 0; else if (first == 0) first = f; if (f == 100 || f == 1000 || f == 10000) { std::cout << "Mean proportion of zero digits in factorials to " << f << " is " << ratio << ". (" << elapsed(t0) << "ms)\n"; } } std::cout << "The mean proportion dips permanently below 0.16 at " << first << ". (" << elapsed(t0) << "ms)\n"; }
c339
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&); public: abelian_sandpile(); explicit abelian_sandpile(std::initializer_list<int> init); void stabilize(); bool is_stable() const; void topple(); abelian_sandpile& operator+=(const abelian_sandpile&); bool operator==(const abelian_sandpile&); private: int& cell_value(size_t row, size_t column) { return cells_[cell_index(row, column)]; } static size_t cell_index(size_t row, size_t column) { return row * sp_columns + column; } static size_t row_index(size_t cell_index) { return cell_index/sp_columns; } static size_t column_index(size_t cell_index) { return cell_index % sp_columns; } std::array<int, sp_cells> cells_; }; abelian_sandpile::abelian_sandpile() { cells_.fill(0); } abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) { assert(init.size() == sp_cells); std::copy(init.begin(), init.end(), cells_.begin()); } abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) { for (size_t i = 0; i < sp_cells; ++i) cells_[i] += other.cells_[i]; stabilize(); return *this; } bool abelian_sandpile::operator==(const abelian_sandpile& other) { return cells_ == other.cells_; } bool abelian_sandpile::is_stable() const { return std::none_of(cells_.begin(), cells_.end(), [](int a) { return a >= sp_limit; }); } void abelian_sandpile::topple() { for (size_t i = 0; i < sp_cells; ++i) { if (cells_[i] >= sp_limit) { cells_[i] -= sp_limit; size_t row = row_index(i); size_t column = column_index(i); if (row > 0) ++cell_value(row - 1, column); if (row + 1 < sp_rows) ++cell_value(row + 1, column); if (column > 0) ++cell_value(row, column - 1); if (column + 1 < sp_columns) ++cell_value(row, column + 1); break; } } } void abelian_sandpile::stabilize() { while (!is_stable()) topple(); } abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) { abelian_sandpile c(a); c += b; return c; } std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) { for (size_t i = 0; i < sp_cells; ++i) { if (i > 0) out << (as.column_index(i) == 0 ? '\n' : ' '); out << as.cells_[i]; } return out << '\n'; } int main() { std::cout << std::boolalpha; std::cout << "Avalanche:\n"; abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3}; while (!sp.is_stable()) { std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; sp.topple(); } std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; std::cout << "Commutativity:\n"; abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3}; abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0}; abelian_sandpile sum1(s1 + s2); abelian_sandpile sum2(s2 + s1); std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n"; std::cout << "s1 + s2 = \n" << sum1; std::cout << "\ns2 + s1 = \n" << sum2; std::cout << '\n'; std::cout << "Identity:\n"; abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3}; abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2}; abelian_sandpile sum3(s3 + s3_id); abelian_sandpile sum4(s3_id + s3_id); std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n'; std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n"; std::cout << "s3 + s3_id = \n" << sum3; std::cout << "\ns3_id + s3_id = \n" << sum4; return 0; }
c340
#include <array> #include <iostream> #include <numeric> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::uint128_t; class magic_number_generator { public: magic_number_generator() : magic_(10) { std::iota(magic_.begin(), magic_.end(), 0); } bool next(uint128_t& n); public: std::vector<uint128_t> magic_; size_t index_ = 0; int digits_ = 2; }; bool magic_number_generator::next(uint128_t& n) { if (index_ == magic_.size()) { std::vector<uint128_t> magic; for (uint128_t m : magic_) { if (m == 0) continue; uint128_t n = 10 * m; for (int d = 0; d < 10; ++d, ++n) { if (n % digits_ == 0) magic.push_back(n); } } index_ = 0; ++digits_; magic_ = std::move(magic); } if (magic_.empty()) return false; n = magic_[index_++]; return true; } std::array<int, 10> get_digits(uint128_t n) { std::array<int, 10> result = {}; for (; n > 0; n /= 10) ++result[static_cast<int>(n % 10)]; return result; } int main() { int count = 0, dcount = 0; uint128_t magic = 0, p = 10; std::vector<int> digit_count; std::array<int, 10> digits0 = {1,1,1,1,1,1,1,1,1,1}; std::array<int, 10> digits1 = {0,1,1,1,1,1,1,1,1,1}; std::vector<uint128_t> pandigital0, pandigital1; for (magic_number_generator gen; gen.next(magic);) { if (magic >= p) { p *= 10; digit_count.push_back(dcount); dcount = 0; } auto digits = get_digits(magic); if (digits == digits0) pandigital0.push_back(magic); else if (digits == digits1) pandigital1.push_back(magic); ++count; ++dcount; } digit_count.push_back(dcount); std::cout << "There are " << count << " magic numbers.\n\n"; std::cout << "The largest magic number is " << magic << ".\n\n"; std::cout << "Magic number count by digits:\n"; for (int i = 0; i < digit_count.size(); ++i) std::cout << i + 1 << '\t' << digit_count[i] << '\n'; std::cout << "\nMagic numbers that are minimally pandigital in 1-9:\n"; for (auto m : pandigital1) std::cout << m << '\n'; std::cout << "\nMagic numbers that are minimally pandigital in 0-9:\n"; for (auto m : pandigital0) std::cout << m << '\n'; }
c341
#include <iostream> #include <list> #include <string> #include <vector> using namespace std; void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) { for(auto it = start; it != sentinel; ++it) { cout << *it << " "; } cout << "\n"; } void FirstFourthFifth(input_iterator auto it) { cout << *it; advance(it, 3); cout << ", " << *it; advance(it, 1); cout << ", " << *it; cout << "\n"; } int main() { vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; list<string> colors{"Red", "Orange", "Yellow", "Green", "Blue", "Purple"}; cout << "All elements:\n"; PrintContainer(days.begin(), days.end()); PrintContainer(colors.begin(), colors.end()); cout << "\nFirst, fourth, and fifth elements:\n"; FirstFourthFifth(days.begin()); FirstFourthFifth(colors.begin()); cout << "\nReverse first, fourth, and fifth elements:\n"; FirstFourthFifth(days.rbegin()); FirstFourthFifth(colors.rbegin()); }
c342
#include <bitset> #include <cctype> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> size_t consonants(const std::string& word) { std::bitset<26> bits; size_t bit = 0; for (char ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); if (ch < 'a' || ch > 'z') continue; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: bit = ch - 'a'; if (bits.test(bit)) return 0; bits.set(bit); break; } } return bits.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 word; std::map<size_t, std::vector<std::string>, std::greater<int>> map; while (getline(in, word)) { if (word.size() <= 10) continue; size_t count = consonants(word); if (count != 0) map[count].push_back(word); } const int columns = 4; for (const auto& p : map) { std::cout << p.first << " consonants (" << p.second.size() << "):\n"; int n = 0; for (const auto& word : p.second) { std::cout << std::left << std::setw(18) << word; ++n; if (n % columns == 0) std::cout << '\n'; } if (n % columns != 0) std::cout << '\n'; std::cout << '\n'; } return EXIT_SUCCESS; }
c343
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" 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; prime_sieve sieve(UCHAR_MAX); auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); }; int n = 0; while (getline(in, line)) { if (std::all_of(line.begin(), line.end(), is_prime)) { ++n; std::cout << std::right << std::setw(2) << n << ": " << std::left << std::setw(10) << line; if (n % 4 == 0) std::cout << '\n'; } } return EXIT_SUCCESS; }
c344
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; if (n == 1) return a1_; big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1); a0_ = a1_; a1_ = a; return a; } 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); return str; } int main() { riordan_number_generator rng; std::cout << "First 32 Riordan numbers:\n"; int i = 1; for (; i <= 32; ++i) { std::cout << std::setw(14) << rng.next() << (i % 4 == 0 ? '\n' : ' '); } for (; i < 1000; ++i) rng.next(); auto num = rng.next(); ++i; std::cout << "\nThe 1000th is " << to_string(num, 40) << " (" << num.get_str().size() << " digits).\n"; for (; i < 10000; ++i) rng.next(); num = rng.next(); std::cout << "The 10000th is " << to_string(num, 40) << " (" << num.get_str().size() << " digits).\n"; }
c345
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } int main() { std::cout.imbue(std::locale("")); std::cout << "First 50 numbers which are the cube roots of the products of " "their proper divisors:\n"; for (unsigned int n = 1, count = 0; count < 50000; ++n) { if (n == 1 || divisor_count(n) == 8) { ++count; if (count <= 50) std::cout << std::setw(3) << n << (count % 10 == 0 ? '\n' : ' '); else if (count == 500 || count == 5000 || count == 50000) std::cout << std::setw(6) << count << "th: " << n << '\n'; } } }
c346
#include <array> #include <iostream> #include <primesieve.hpp> class ormiston_triple_generator { public: ormiston_triple_generator() { for (int i = 0; i < 2; ++i) { primes_[i] = pi_.next_prime(); digits_[i] = get_digits(primes_[i]); } } std::array<uint64_t, 3> next_triple() { for (;;) { uint64_t prime = pi_.next_prime(); auto digits = get_digits(prime); bool is_triple = digits == digits_[0] && digits == digits_[1]; uint64_t prime0 = primes_[0]; primes_[0] = primes_[1]; primes_[1] = prime; digits_[0] = digits_[1]; digits_[1] = digits; if (is_triple) return {prime0, primes_[0], primes_[1]}; } } private: static std::array<int, 10> get_digits(uint64_t n) { std::array<int, 10> result = {}; for (; n > 0; n /= 10) ++result[n % 10]; return result; } primesieve::iterator pi_; std::array<uint64_t, 2> primes_; std::array<std::array<int, 10>, 2> digits_; }; int main() { ormiston_triple_generator generator; int count = 0; std::cout << "Smallest members of first 25 Ormiston triples:\n"; for (; count < 25; ++count) { auto primes = generator.next_triple(); std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\n' : ' '); } std::cout << '\n'; for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) { auto primes = generator.next_triple(); if (primes[2] > limit) { std::cout << "Number of Ormiston triples < " << limit << ": " << count << '\n'; limit *= 10; } } }
c347
#include <algorithm> #include <iostream> #include <vector> std::vector<unsigned int> divisors(unsigned int n) { std::vector<unsigned int> result{1}; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) result.push_back(power); for (unsigned int p = 3; p * p <= n; p += 2) { size_t size = result.size(); for (power = p; n % p == 0; power *= p, n /= p) for (size_t i = 0; i != size; ++i) result.push_back(power * result[i]); } if (n > 1) { size_t size = result.size(); for (size_t i = 0; i != size; ++i) result.push_back(n * result[i]); } return result; } unsigned long long modpow(unsigned long long base, unsigned int exp, unsigned int mod) { if (mod == 1) return 0; unsigned long long result = 1; base %= mod; for (; exp != 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 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}; for (unsigned int p = 7;;) { for (unsigned int w : wheel) { if (p * p > n) return true; if (n % p == 0) return false; p += w; } } } bool is_poulet_number(unsigned int n) { return modpow(2, n - 1, n) == 1 && !is_prime(n); } bool is_sp_num(unsigned int n) { if (!is_poulet_number(n)) return false; auto div = divisors(n); return all_of(div.begin() + 1, div.end(), [](unsigned int d) { return modpow(2, d, d) == 2; }); } int main() { std::cout.imbue(std::locale("")); unsigned int n = 1, count = 0; std::cout << "First 20 super-Poulet numbers:\n"; for (; count < 20; n += 2) { if (is_sp_num(n)) { ++count; std::cout << n << ' '; } } std::cout << '\n'; for (unsigned int limit = 1000000; limit <= 10000000; limit *= 10) { for (;;) { n += 2; if (is_sp_num(n)) { ++count; if (n > limit) break; } } std::cout << "\nIndex and value of first super-Poulet greater than " << limit << ":\n#" << count << " is " << n << '\n'; } }
c348
#include <iostream> #include <string> #include <windows.h> using namespace std; typedef unsigned char byte; enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR }; class fieldData { public: fieldData() : value( CLOSED ), open( false ) {} byte value; bool open, mine; }; class game { public: ~game() { if( field ) delete [] field; } game( int x, int y ) { go = false; wid = x; hei = y; field = new fieldData[x * y]; memset( field, 0, x * y * sizeof( fieldData ) ); oMines = ( ( 22 - rand() % 11 ) * x * y ) / 100; mMines = 0; int mx, my, m = 0; for( ; m < oMines; m++ ) { do { mx = rand() % wid; my = rand() % hei; } while( field[mx + wid * my].mine ); field[mx + wid * my].mine = true; } graphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; graphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; } void gameLoop() { string c, r, a; int col, row; while( !go ) { drawBoard(); cout << "Enter column, row and an action( c r a ):\nActions: o => open, f => flag, ? => unknown\n"; cin >> c >> r >> a; if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32; col = c[0] - 65; row = r[0] - 49; makeMove( col, row, a ); } } private: void makeMove( int x, int y, string a ) { fieldData* fd = &field[wid * y + x]; if( fd->open && fd->value < CLOSED ) { cout << "This cell is already open!"; Sleep( 3000 ); return; } if( a[0] == 'O' ) openCell( x, y ); else if( a[0] == 'F' ) { fd->open = true; fd->value = FLAG; mMines++; checkWin(); } else { fd->open = true; fd->value = UNKNOWN; } } bool openCell( int x, int y ) { if( !isInside( x, y ) ) return false; if( field[x + y * wid].mine ) boom(); else { if( field[x + y * wid].value == FLAG ) { field[x + y * wid].value = CLOSED; field[x + y * wid].open = false; mMines--; } recOpen( x, y ); checkWin(); } return true; } void drawBoard() { system( "cls" ); cout << "Marked mines: " << mMines << " from " << oMines << "\n\n"; for( int x = 0; x < wid; x++ ) cout << " " << ( char )( 65 + x ) << " "; cout << "\n"; int yy; for( int y = 0; y < hei; y++ ) { yy = y * wid; for( int x = 0; x < wid; x++ ) cout << "+---"; cout << "+\n"; fieldData* fd; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; cout<< "| "; if( !fd->open ) cout << ( char )graphs[1] << " "; else { if( fd->value > 9 ) cout << ( char )graphs[fd->value - 9] << " "; else { if( fd->value < 1 ) cout << " "; else cout << ( char )(fd->value + 48 ) << " "; } } } cout << "| " << y + 1 << "\n"; } for( int x = 0; x < wid; x++ ) cout << "+---"; cout << "+\n\n"; } void checkWin() { int z = wid * hei - oMines, yy; fieldData* fd; for( int y = 0; y < hei; y++ ) { yy = wid * y; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; if( fd->open && fd->value != FLAG ) z--; } } if( !z ) lastMsg( "Congratulations, you won the game!"); } void boom() { int yy; fieldData* fd; for( int y = 0; y < hei; y++ ) { yy = wid * y; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; if( fd->value == FLAG ) { fd->open = true; fd->value = fd->mine ? MINE : ERR; } else if( fd->mine ) { fd->open = true; fd->value = MINE; } } } lastMsg( "B O O O M M M M M !" ); } void lastMsg( string s ) { go = true; drawBoard(); cout << s << "\n\n"; } bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); } void recOpen( int x, int y ) { if( !isInside( x, y ) || field[x + y * wid].open ) return; int bc = getMineCount( x, y ); field[x + y * wid].open = true; field[x + y * wid].value = bc; if( bc ) return; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( xx == 0 && yy == 0 ) continue; recOpen( x + xx, y + yy ); } } int getMineCount( int x, int y ) { int m = 0; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( xx == 0 && yy == 0 ) continue; if( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++; } return m; } int wid, hei, mMines, oMines; fieldData* field; bool go; int graphs[6]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); game g( 4, 6 ); g.gameLoop(); return system( "pause" ); }
c349
#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; }
c350
#include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(int limit) { std::vector<bool> sieve(limit, 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, sq = 9; sq < limit; p += 2) { if (sieve[p]) { for (int q = sq; q < limit; q += p << 1) sieve[q] = false; } sq += (p + 1) << 2; } return sieve; } void print_non_twin_prime_sums(const std::vector<bool>& sums) { int count = 0; for (size_t i = 2; i < sums.size(); i += 2) { if (!sums[i]) { ++count; std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' '); } } std::cout << "\nFound " << count << '\n'; } int main() { const int limit = 100001; std::vector<bool> sieve = prime_sieve(limit + 2); for (size_t i = 0; i < limit; ++i) { if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2])) sieve[i] = false; } std::vector<bool> twin_prime_sums(limit, false); for (size_t i = 0; i < limit; ++i) { if (sieve[i]) { for (size_t j = i; i + j < limit; ++j) { if (sieve[j]) twin_prime_sums[i + j] = true; } } } std::cout << "Non twin prime sums:\n"; print_non_twin_prime_sums(twin_prime_sums); sieve[1] = true; for (size_t i = 1; i + 1 < limit; ++i) { if (sieve[i]) twin_prime_sums[i + 1] = true; } std::cout << "\nNon twin prime sums (including 1):\n"; print_non_twin_prime_sums(twin_prime_sums); }
c351
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) cout << ", "; } template<typename P, typename... Ts> void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true) { std::apply ( [&payloads, isLast](Ts const&... tupleArgs) { size_t n{0}; cout << "["; (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...); cout << "]"; cout << (isLast ? "\n" : ",\n"); }, nestedTuple ); } void FindUniqueIndexes(set<int> &indexes, int index) { indexes.insert(index); } template<typename... Ts> void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple) { std::apply ( [&indexes](Ts const&... tupleArgs) { (FindUniqueIndexes(indexes, tupleArgs),...); }, nestedTuple ); } template<typename P> void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads) { for(size_t i = 0; i < size(payloads); i++) { if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n"; } } int main() { vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"}; const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; auto tpl = make_tuple(make_tuple( make_tuple(1, 2), make_tuple(3, 4, 1), 5)); cout << "Mapping indexes to payloads:\n"; PrintPayloads(payloads, tpl); cout << "\nFinding unused payloads:\n"; set<int> usedIndexes; FindUniqueIndexes(usedIndexes, tpl); PrintUnusedPayloads(usedIndexes, payloads); cout << "\nMapping to some out of range payloads:\n"; PrintPayloads(shortPayloads, tpl); return 0; }
c352
#include <iomanip> #include <iostream> #include <sstream> #include <utility> #include <primesieve.hpp> uint64_t digit_sum(uint64_t n) { uint64_t sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } class honaker_prime_generator { public: std::pair<uint64_t, uint64_t> next(); private: primesieve::iterator pi_; uint64_t index_ = 0; }; std::pair<uint64_t, uint64_t> honaker_prime_generator::next() { for (;;) { uint64_t prime = pi_.next_prime(); ++index_; if (digit_sum(index_) == digit_sum(prime)) return std::make_pair(index_, prime); } } std::ostream& operator<<(std::ostream& os, const std::pair<uint64_t, uint64_t>& p) { std::ostringstream str; str << '(' << p.first << ", " << p.second << ')'; return os << str.str(); } int main() { honaker_prime_generator hpg; std::cout << "First 50 Honaker primes (index, prime):\n"; int i = 1; for (; i <= 50; ++i) std::cout << std::setw(11) << hpg.next() << (i % 5 == 0 ? '\n' : ' '); for (; i < 10000; ++i) hpg.next(); std::cout << "\nTen thousandth: " << hpg.next() << '\n'; }
c353
#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'; } } }
c354
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector> typedef std::vector<char> vecChar; class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST"; if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10; if( !rpt && clr_count < code_len ) clr_count = code_len; if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20; if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20; codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt; for( size_t s = 0; s < colorsCnt; s++ ) { colors.append( 1, color.at( s ) ); } } void play() { bool win = false; combo = getCombo(); while( guessCnt ) { showBoard(); if( checkInput( getInput() ) ) { win = true; break; } guessCnt--; } if( win ) { std::cout << "\n\n--------------------------------\n" << "Very well done!\nYou found the code: " << combo << "\n--------------------------------\n\n"; } else { std::cout << "\n\n--------------------------------\n" << "I am sorry, you couldn't make it!\nThe code was: " << combo << "\n--------------------------------\n\n"; } } private: void showBoard() { vecChar::iterator y; for( int x = 0; x < guesses.size(); x++ ) { std::cout << "\n--------------------------------\n"; std::cout << x + 1 << ": "; for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) { std::cout << *y << " "; } std::cout << " : "; for( y = results[x].begin(); y != results[x].end(); y++ ) { std::cout << *y << " "; } int z = codeLen - results[x].size(); if( z > 0 ) { for( int x = 0; x < z; x++ ) std::cout << "- "; } } std::cout << "\n\n"; } std::string getInput() { std::string a; while( true ) { std::cout << "Enter your guess (" << colors << "): "; a = ""; std::cin >> a; std::transform( a.begin(), a.end(), a.begin(), ::toupper ); if( a.length() > codeLen ) a.erase( codeLen ); bool r = true; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { if( colors.find( *x ) == std::string::npos ) { r = false; break; } } if( r ) break; } return a; } bool checkInput( std::string a ) { vecChar g; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { g.push_back( *x ); } guesses.push_back( g ); int black = 0, white = 0; std::vector<bool> gmatch( codeLen, false ); std::vector<bool> cmatch( codeLen, false ); for( int i = 0; i < codeLen; i++ ) { if( a.at( i ) == combo.at( i ) ) { gmatch[i] = true; cmatch[i] = true; black++; } } for( int i = 0; i < codeLen; i++ ) { if (gmatch[i]) continue; for( int j = 0; j < codeLen; j++ ) { if (i == j || cmatch[j]) continue; if( a.at( i ) == combo.at( j ) ) { cmatch[j] = true; white++; break; } } } vecChar r; for( int b = 0; b < black; b++ ) r.push_back( 'X' ); for( int w = 0; w < white; w++ ) r.push_back( 'O' ); results.push_back( r ); return ( black == codeLen ); } std::string getCombo() { std::string c, clr = colors; int l, z; for( size_t s = 0; s < codeLen; s++ ) { z = rand() % ( int )clr.length(); c.append( 1, clr[z] ); if( !repeatClr ) clr.erase( z, 1 ); } return c; } size_t codeLen, colorsCnt, guessCnt; bool repeatClr; std::vector<vecChar> guesses, results; std::string colors, combo; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); master m( 4, 8, 12, false ); m.play(); return 0; }
c355
#include <algorithm> #include <cstdint> #include <iostream> #include <numeric> #include <vector> std::vector<uint64_t> divisors(uint64_t n) { std::vector<uint64_t> result{1}; uint64_t power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) result.push_back(power); for (uint64_t p = 3; p * p <= n; p += 2) { size_t size = result.size(); for (power = p; n % p == 0; power *= p, n /= p) for (size_t i = 0; i != size; ++i) result.push_back(power * result[i]); } if (n > 1) { size_t size = result.size(); for (size_t i = 0; i != size; ++i) result.push_back(n * result[i]); } sort(result.begin(), result.end()); return result; } uint64_t ipow(uint64_t base, uint64_t exp) { if (exp == 0) return 1; if ((exp & 1) == 0) return ipow(base * base, exp >> 1); return base * ipow(base * base, (exp - 1) >> 1); } uint64_t zsigmondy(uint64_t n, uint64_t a, uint64_t b) { auto p = ipow(a, n) - ipow(b, n); auto d = divisors(p); if (d.size() == 2) return p; std::vector<uint64_t> dms(n - 1); for (uint64_t m = 1; m < n; ++m) dms[m - 1] = ipow(a, m) - ipow(b, m); for (auto i = d.rbegin(); i != d.rend(); ++i) { uint64_t z = *i; if (all_of(dms.begin(), dms.end(), [z](uint64_t x) { return std::gcd(x, z) == 1; })) return z; } return 1; } void test(uint64_t a, uint64_t b) { std::cout << "Zsigmondy(n, " << a << ", " << b << "):\n"; for (uint64_t n = 1; n <= 20; ++n) { std::cout << zsigmondy(n, a, b) << ' '; } std::cout << "\n\n"; } int main() { test(2, 1); test(3, 1); test(4, 1); test(5, 1); test(6, 1); test(7, 1); test(3, 2); test(5, 3); test(7, 3); test(7, 5); }
c356
#include <algorithm> #include <cctype> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <sstream> #include <string> #include <vector> using bigram = std::pair<char, char>; std::multiset<bigram> bigrams(const std::string& phrase) { std::multiset<bigram> result; std::istringstream is(phrase); std::string word; while (is >> word) { for (char& ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); } size_t length = word.size(); if (length == 1) { result.emplace(word[0], '\0'); } else { for (size_t i = 0; i + 1 < length; ++i) { result.emplace(word[i], word[i + 1]); } } } return result; } double sorensen(const std::string& s1, const std::string& s2) { auto a = bigrams(s1); auto b = bigrams(s2); std::multiset<bigram> c; std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.begin())); return (2.0 * c.size()) / (a.size() + b.size()); } int main() { std::vector<std::string> tasks; std::ifstream is("tasks.txt"); if (!is) { std::cerr << "Cannot open tasks file.\n"; return EXIT_FAILURE; } std::string task; while (getline(is, task)) { tasks.push_back(task); } const size_t tc = tasks.size(); const std::string tests[] = {"Primordial primes", "Sunkist-Giuliani formula", "Sieve of Euripides", "Chowder numbers"}; std::vector<std::pair<double, size_t>> sdi(tc); std::cout << std::fixed; for (const std::string& test : tests) { for (size_t i = 0; i != tc; ++i) { sdi[i] = std::make_pair(sorensen(tasks[i], test), i); } std::partial_sort(sdi.begin(), sdi.begin() + 5, sdi.end(), [](const std::pair<double, size_t>& a, const std::pair<double, size_t>& b) { return a.first > b.first; }); std::cout << test << " >\n"; for (size_t i = 0; i < 5 && i < tc; ++i) { std::cout << " " << sdi[i].first << ' ' << tasks[sdi[i].second] << '\n'; } std::cout << '\n'; } return EXIT_SUCCESS; }
c371
#include <windows.h> #include <string> #include <complex> const int BMP_SIZE = 600, ITERATIONS = 512; const long double FCT = 2.85, hFCT = FCT / 2.0; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } DWORD* bits() const { return ( DWORD* )pBits; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class julia { public: void draw( std::complex<long double> k ) { bmp.create( BMP_SIZE, BMP_SIZE ); DWORD* bits = bmp.bits(); int res, pos; std::complex<long double> c, factor( FCT / BMP_SIZE, FCT / BMP_SIZE ) ; for( int y = 0; y < BMP_SIZE; y++ ) { pos = y * BMP_SIZE; c.imag( ( factor.imag() * y ) + -hFCT ); for( int x = 0; x < BMP_SIZE; x++ ) { c.real( factor.real() * x + -hFCT ); res = inSet( c, k ); if( res ) { int n_res = res % 255; if( res < ( ITERATIONS >> 1 ) ) res = RGB( n_res << 2, n_res << 3, n_res << 4 ); else res = RGB( n_res << 4, n_res << 2, n_res << 5 ); } bits[pos++] = res; } } bmp.saveBitmap( "./js.bmp" ); } private: int inSet( std::complex<long double> z, std::complex<long double> c ) { long double dist; for( int ec = 0; ec < ITERATIONS; ec++ ) { z = z * z; z = z + c; dist = ( z.imag() * z.imag() ) + ( z.real() * z.real() ); if( dist > 3 ) return( ec ); } return 0; } myBitmap bmp; }; int main( int argc, char* argv[] ) { std::complex<long double> c; long double factor = FCT / BMP_SIZE; c.imag( ( factor * 184 ) + -1.4 ); c.real( ( factor * 307 ) + -2.0 ); julia j; j.draw( c ); return 0; }
c372
#include <utility> #include <iterator> #include <iostream> #include <ostream> #include <algorithm> #include <iterator> template<typename ForwardIterator> std::pair<ForwardIterator, ForwardIterator> max_subseq(ForwardIterator begin, ForwardIterator end) { typedef typename std::iterator_traits<ForwardIterator>::value_type value_type; ForwardIterator seq_begin = begin, seq_end = seq_begin; value_type seq_sum = value_type(); ForwardIterator current_begin = begin; value_type current_sum = value_type(); value_type zero = value_type(); for (ForwardIterator iter = begin; iter != end; ++iter) { value_type value = *iter; if (zero < value) { if (current_sum < zero) { current_sum = zero; current_begin = iter; } } else { if (seq_sum < current_sum) { seq_begin = current_begin; seq_end = iter; seq_sum = current_sum; } } current_sum += value; } if (seq_sum < current_sum) { seq_begin = current_begin; seq_end = end; seq_sum = current_sum; } return std::make_pair(seq_begin, seq_end); } int array[] = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 }; template<typename T, int N> int* end(T (&arr)[N]) { return arr+N; } int main() { std::pair<int*, int*> seq = max_subseq(array, end(array)); std::copy(seq.first, seq.second, std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0; }
c373
#include <iostream> int main() { LOOP: std::cout << "Hello, World!\n"; goto LOOP; }
c374
#include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> template <typename StringType> size_t levenshtein_distance(const StringType& s1, const StringType& s2) { const size_t m = s1.size(); const size_t n = s2.size(); if (m == 0) return n; if (n == 0) return m; std::vector<size_t> costs(n + 1); std::iota(costs.begin(), costs.end(), 0); size_t i = 0; for (auto c1 : s1) { costs[0] = i + 1; size_t corner = i; size_t j = 0; for (auto c2 : s2) { size_t upper = costs[j + 1]; costs[j + 1] = (c1 == c2) ? corner : 1 + std::min(std::min(upper, corner), costs[j]); corner = upper; ++j; } ++i; } return costs[n]; } int main() { std::wstring s0 = L"rosettacode"; std::wstring s1 = L"raisethysword"; std::wcout << L"distance between " << s0 << L" and " << s1 << L": " << levenshtein_distance(s0, s1) << std::endl; return 0; }
c375
#include <cstdlib> #include <iostream> #include <vector> #include <utility> #include <algorithm> #include <ctime> #include <iomanip> int main( ) { typedef std::vector<std::pair<std::string, double> >::const_iterator SPI ; typedef std::vector<std::pair<std::string , double> > ProbType ; ProbType probabilities ; probabilities.push_back( std::make_pair( "aleph" , 1/5.0 ) ) ; probabilities.push_back( std::make_pair( "beth" , 1/6.0 ) ) ; probabilities.push_back( std::make_pair( "gimel" , 1/7.0 ) ) ; probabilities.push_back( std::make_pair( "daleth" , 1/8.0 ) ) ; probabilities.push_back( std::make_pair( "he" , 1/9.0 ) ) ; probabilities.push_back( std::make_pair( "waw" , 1/10.0 ) ) ; probabilities.push_back( std::make_pair( "zayin" , 1/11.0 ) ) ; probabilities.push_back( std::make_pair( "heth" , 1759/27720.0 ) ) ; std::vector<std::string> generated ; std::vector<int> decider ; for ( int i = 0 ; i < probabilities.size( ) ; i++ ) { if ( i == 0 ) { decider.push_back( 27720 * (probabilities[ i ].second) ) ; } else { int number = 0 ; for ( int j = 0 ; j < i ; j++ ) { number += 27720 * ( probabilities[ j ].second ) ; } number += 27720 * probabilities[ i ].second ; decider.push_back( number ) ; } } srand( time( 0 ) ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { int randnumber = rand( ) % 27721 ; int j = 0 ; while ( randnumber > decider[ j ] ) j++ ; generated.push_back( ( probabilities[ j ]).first ) ; } std::cout << "letter frequency attained frequency expected\n" ; for ( SPI i = probabilities.begin( ) ; i != probabilities.end( ) ; i++ ) { std::cout << std::left << std::setw( 8 ) << i->first ; int found = std::count ( generated.begin( ) , generated.end( ) , i->first ) ; std::cout << std::left << std::setw( 21 ) << found / 1000000.0 ; std::cout << std::left << std::setw( 17 ) << i->second << '\n' ; } return 0 ; }
c376
#include <iostream> #include <algorithm> #include <vector> #include <utility> int gcd(int a, int b) { int c; while (b) { c = a; a = b; b = c % b; } return a; } int main() { using intpair = std::pair<int,int>; std::vector<intpair> pairs = { {21,15}, {17,23}, {36,12}, {18,29}, {60,15} }; pairs.erase( std::remove_if( pairs.begin(), pairs.end(), [](const intpair& x) { return gcd(x.first, x.second) != 1; } ), pairs.end() ); for (auto& x : pairs) { std::cout << "{" << x.first << ", " << x.second << "}" << std::endl; } return 0; }
c377
#include <gmpxx.h> #include <chrono> using namespace std; using namespace chrono; void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, const mpf_class& op2) { rop1 = (op1 + op2) / 2; rop2 = op1 * op2; mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); } int main(void) { auto st = steady_clock::now(); mpf_set_default_prec(300000); mpf_class x0, y0, resA, resB, Z; x0 = 1; y0 = 0.5; Z = 0.25; mpf_sqrt(y0.get_mpf_t(), y0.get_mpf_t()); int n = 1; for (int i = 0; i < 8; i++) { agm(resA, resB, x0, y0); Z -= n * (resA - x0) * (resA - x0); n *= 2; agm(x0, y0, resA, resB); Z -= n * (x0 - resA) * (x0 - resA); n *= 2; } x0 = x0 * x0 / Z; printf("Took %f ms for computation.\n", duration<double>(steady_clock::now() - st).count() * 1000.0); st = steady_clock::now(); gmp_printf ("%.89412Ff\n", x0.get_mpf_t()); printf("Took %f ms for output.\n", duration<double>(steady_clock::now() - st).count() * 1000.0); return 0; }
c378
#include <algorithm> #include <iostream> #include <string> void comb(int N, int K) { std::string bitmask(K, 1); bitmask.resize(N, 0); do { for (int i = 0; i < N; ++i) { if (bitmask[i]) std::cout << " " << i; } std::cout << std::endl; } while (std::prev_permutation(bitmask.begin(), bitmask.end())); } int main() { comb(5, 3); }
c379
#include <QApplication> #include <QMainWindow> int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow window; window.show(); return app.exec(); }
c380
#include <iostream> #include <string> void base2_increment(std::string& s) { size_t z = s.rfind('0'); if (z != std::string::npos) { s[z] = '1'; size_t count = s.size() - (z + 1); s.replace(z + 1, count, count, '0'); } else { s.assign(s.size() + 1, '0'); s[0] = '1'; } } int main() { std::cout << "Decimal\tBinary\n"; std::string s("1"); for (unsigned int n = 1; ; ++n) { unsigned int i = n + (n << s.size()); if (i >= 1000) break; std::cout << i << '\t' << s << s << '\n'; base2_increment(s); } }
c381
#include <windows.h> #include <iostream> #include <string> using namespace std; const int PLAYERS = 2, MAX_POINTS = 100; class player { public: player() { reset(); } void reset() { name = ""; current_score = round_score = 0; } string getName() { return name; } void setName( string n ) { name = n; } int getCurrScore() { return current_score; } void addCurrScore() { current_score += round_score; } int getRoundScore() { return round_score; } void addRoundScore( int rs ) { round_score += rs; } void zeroRoundScore() { round_score = 0; } private: string name; int current_score, round_score; }; class pigGame { public: pigGame() { resetPlayers(); } void play() { while( true ) { system( "cls" ); int p = 0; while( true ) { if( turn( p ) ) { praise( p ); break; } ++p %= PLAYERS; } string r; cout << "Do you want to play again ( y / n )? "; cin >> r; if( r != "Y" && r != "y" ) return; resetPlayers(); } } private: void resetPlayers() { system( "cls" ); string n; for( int p = 0; p < PLAYERS; p++ ) { _players[p].reset(); cout << "Enter name player " << p + 1 << ": "; cin >> n; _players[p].setName( n ); } } void praise( int p ) { system( "cls" ); cout << "CONGRATULATIONS " << _players[p].getName() << ", you are the winner!" << endl << endl; cout << "Final Score" << endl; drawScoreboard(); cout << endl << endl; } void drawScoreboard() { for( int p = 0; p < PLAYERS; p++ ) cout << _players[p].getName() << ": " << _players[p].getCurrScore() << " points" << endl; cout << endl; } bool turn( int p ) { system( "cls" ); drawScoreboard(); _players[p].zeroRoundScore(); string r; int die; while( true ) { cout << _players[p].getName() << ", your round score is: " << _players[p].getRoundScore() << endl; cout << "What do you want to do (H)old or (R)oll? "; cin >> r; if( r == "h" || r == "H" ) { _players[p].addCurrScore(); return _players[p].getCurrScore() >= MAX_POINTS; } if( r == "r" || r == "R" ) { die = rand() % 6 + 1; if( die == 1 ) { cout << _players[p].getName() << ", your turn is over." << endl << endl; system( "pause" ); return false; } _players[p].addRoundScore( die ); } cout << endl; } return false; } player _players[PLAYERS]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); pigGame pg; pg.play(); return 0; }
c382
#include <iostream> #include <string> std::string to_roman(int value) { struct romandata_t { int value; char const* numeral; }; static romandata_t const romandata[] = { 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC", 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I", 0, NULL }; std::string result; for (romandata_t const* current = romandata; current->value > 0; ++current) { while (value >= current->value) { result += current->numeral; value -= current->value; } } return result; } int main() { for (int i = 1; i <= 4000; ++i) { std::cout << to_roman(i) << std::endl; } }
c383
#include <cstdint> #include <iomanip> #include <iostream> #include <primesieve.hpp> bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } int main() { const uint64_t limit = 1000000; std::cout << "Frobenius numbers less than " << limit << " (asterisk marks primes):\n"; primesieve::iterator it; uint64_t prime1 = it.next_prime(); for (int count = 1;; ++count) { uint64_t prime2 = it.next_prime(); uint64_t frobenius = prime1 * prime2 - prime1 - prime2; if (frobenius >= limit) break; std::cout << std::setw(6) << frobenius << (is_prime(frobenius) ? '*' : ' ') << (count % 10 == 0 ? '\n' : ' '); prime1 = prime2; } std::cout << '\n'; }
c384
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d != 0) return false; if (set.find(d) != set.end()) { return false; } set.insert(d); } return true; } int main() { for (int i = 98764321; i > 0; i--) { if (checkDec(i)) { std::cout << i << "\n"; break; } } return 0; }
c385
#include <iostream> using std::cout; int main() { for(int bottles(99); bottles > 0; bottles -= 1){ cout << bottles << " bottles of beer on the wall\n" << bottles << " bottles of beer\n" << "Take one down, pass it around\n" << bottles - 1 << " bottles of beer on the wall\n\n"; } }
c386
#include<iostream> using namespace std; int main() { int q,r; for(q=0;q<16;q++){ for(r=10;r<16;r++){ std::cout<<16*q+r<<" "; } } return 0; }
c387
#include <time.h> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> #include <string> enum color { red, green, purple }; enum symbol { oval, squiggle, diamond }; enum number { one, two, three }; enum shading { solid, open, striped }; class card { public: card( color c, symbol s, number n, shading h ) { clr = c; smb = s; nbr = n; shd = h; } color getColor() { return clr; } symbol getSymbol() { return smb; } number getNumber() { return nbr; } shading getShading() { return shd; } std::string toString() { std::string str = "["; str += clr == red ? "red " : clr == green ? "green " : "purple "; str += nbr == one ? "one " : nbr == two ? "two " : "three "; str += smb == oval ? "oval " : smb == squiggle ? "squiggle " : "diamond "; str += shd == solid ? "solid" : shd == open ? "open" : "striped"; return str + "]"; } private: color clr; symbol smb; number nbr; shading shd; }; typedef struct { std::vector<size_t> index; } set; class setPuzzle { public: setPuzzle() { for( size_t c = red; c <= purple; c++ ) { for( size_t s = oval; s <= diamond; s++ ) { for( size_t n = one; n <= three; n++ ) { for( size_t h = solid; h <= striped; h++ ) { card crd( static_cast<color> ( c ), static_cast<symbol> ( s ), static_cast<number> ( n ), static_cast<shading>( h ) ); _cards.push_back( crd ); } } } } } void create( size_t countCards, size_t countSets, std::vector<card>& cards, std::vector<set>& sets ) { while( true ) { sets.clear(); cards.clear(); std::random_shuffle( _cards.begin(), _cards.end() ); for( size_t f = 0; f < countCards; f++ ) { cards.push_back( _cards.at( f ) ); } for( size_t c1 = 0; c1 < cards.size() - 2; c1++ ) { for( size_t c2 = c1 + 1; c2 < cards.size() - 1; c2++ ) { for( size_t c3 = c2 + 1; c3 < cards.size(); c3++ ) { if( testSet( &cards.at( c1 ), &cards.at( c2 ), &cards.at( c3 ) ) ) { set s; s.index.push_back( c1 ); s.index.push_back( c2 ); s.index.push_back( c3 ); sets.push_back( s ); } } } } if( sets.size() == countSets ) return; } } private: bool testSet( card* c1, card* c2, card* c3 ) { int c = ( c1->getColor() + c2->getColor() + c3->getColor() ) % 3, s = ( c1->getSymbol() + c2->getSymbol() + c3->getSymbol() ) % 3, n = ( c1->getNumber() + c2->getNumber() + c3->getNumber() ) % 3, h = ( c1->getShading() + c2->getShading() + c3->getShading() ) % 3; return !( c + s + n + h ); } std::vector<card> _cards; }; void displayCardsSets( std::vector<card>& cards, std::vector<set>& sets ) { size_t cnt = 1; std::cout << " ** DEALT " << cards.size() << " CARDS: **\n"; for( std::vector<card>::iterator i = cards.begin(); i != cards.end(); i++ ) { std::cout << std::setw( 2 ) << cnt++ << ": " << ( *i ).toString() << "\n"; } std::cout << "\n ** CONTAINING " << sets.size() << " SETS: **\n"; for( std::vector<set>::iterator i = sets.begin(); i != sets.end(); i++ ) { for( size_t j = 0; j < ( *i ).index.size(); j++ ) { std::cout << " " << std::setiosflags( std::ios::left ) << std::setw( 34 ) << cards.at( ( *i ).index.at( j ) ).toString() << " : " << std::resetiosflags( std::ios::left ) << std::setw( 2 ) << ( *i ).index.at( j ) + 1 << "\n"; } std::cout << "\n"; } std::cout << "\n\n"; } int main( int argc, char* argv[] ) { srand( static_cast<unsigned>( time( NULL ) ) ); setPuzzle p; std::vector<card> v9, v12; std::vector<set> s4, s6; p.create( 9, 4, v9, s4 ); p.create( 12, 6, v12, s6 ); displayCardsSets( v9, s4 ); displayCardsSets( v12, s6 ); return 0; }
c388
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif class bignum { private: vector<usingle> rep_; public: explicit bignum(usingle n = 0) { if (n > 0) rep_.push_back(n); } bool equals(usingle n) const { if (n == 0) return rep_.empty(); if (rep_.size() > 1) return false; return rep_[0] == n; } bignum add(usingle addend) const { bignum result(0); udouble sum = addend; for (size_t i = 0; i < rep_.size(); ++i) { sum += rep_[i]; result.rep_.push_back(sum & (((udouble)1 << word_len) - 1)); sum >>= word_len; } if (sum > 0) result.rep_.push_back((usingle)sum); return result; } bignum add(const bignum& addend) const { bignum result(0); udouble sum = 0; size_t sz1 = rep_.size(); size_t sz2 = addend.rep_.size(); for (size_t i = 0; i < max(sz1, sz2); ++i) { if (i < sz1) sum += rep_[i]; if (i < sz2) sum += addend.rep_[i]; result.rep_.push_back(sum & (((udouble)1 << word_len) - 1)); sum >>= word_len; } if (sum > 0) result.rep_.push_back((usingle)sum); return result; } bignum multiply(usingle factor) const { bignum result(0); udouble product = 0; for (size_t i = 0; i < rep_.size(); ++i) { product += (udouble)rep_[i] * factor; result.rep_.push_back(product & (((udouble)1 << word_len) - 1)); product >>= word_len; } if (product > 0) result.rep_.push_back((usingle)product); return result; } void divide(usingle divisor, bignum& quotient, usingle& remainder) const { quotient.rep_.resize(0); udouble dividend = 0; remainder = 0; for (size_t i = rep_.size(); i > 0; --i) { dividend = ((udouble)remainder << word_len) + rep_[i - 1]; usingle quo = (usingle)(dividend / divisor); remainder = (usingle)(dividend % divisor); if (quo > 0 || i < rep_.size()) quotient.rep_.push_back(quo); } reverse(quotient.rep_.begin(), quotient.rep_.end()); } }; ostream& operator<<(ostream& os, const bignum& x); ostream& operator<<(ostream& os, const bignum& x) { string rep; bignum dividend = x; bignum quotient; usingle remainder; while (true) { dividend.divide(10, quotient, remainder); rep += (char)('0' + remainder); if (quotient.equals(0)) break; dividend = quotient; } reverse(rep.begin(), rep.end()); os << rep; return os; } bignum lfact(usingle n); bignum lfact(usingle n) { bignum result(0); bignum f(1); for (usingle k = 1; k <= n; ++k) { result = result.add(f); f = f.multiply(k); } return result; } int main() { for (usingle i = 0; i <= 10; ++i) { cout << "!" << i << " = " << lfact(i) << endl; } for (usingle i = 20; i <= 110; i += 10) { cout << "!" << i << " = " << lfact(i) << endl; } for (usingle i = 1000; i <= 10000; i += 1000) { stringstream ss; ss << lfact(i); cout << "!" << i << " has " << ss.str().size() << " digits." << endl; } }
c389
#include <iostream> bool circle(int x, int y, int c, int r) { return (r * r) >= ((x = x / 2) * x) + ((y = y - c) * y); } char pixel(int x, int y, int r) { if (circle(x, y, -r / 2, r / 6)) { return '#'; } if (circle(x, y, r / 2, r / 6)) { return '.'; } if (circle(x, y, -r / 2, r / 2)) { return '.'; } if (circle(x, y, r / 2, r / 2)) { return '#'; } if (circle(x, y, 0, r)) { if (x < 0) { return '.'; } else { return '#'; } } return ' '; } void yinYang(int r) { for (int y = -r; y <= r; y++) { for (int x = -2 * r; x <= 2 * r; x++) { std::cout << pixel(x, y, r); } std::cout << '\n'; } } int main() { yinYang(18); return 0; }
c390
struct link { link* next; int data; };
c391
#include <iostream> #include <vector> #include <numeric> float sum(const std::vector<float> &array) { return std::accumulate(array.begin(), array.end(), 0.0); } float square(float x) { return x * x; } float mean(const std::vector<float> &array) { return sum(array) / array.size(); } float averageSquareDiff(float a, const std::vector<float> &predictions) { std::vector<float> results; for (float x : predictions) results.push_back(square(x - a)); return mean(results); } void diversityTheorem(float truth, const std::vector<float> &predictions) { float average = mean(predictions); std::cout << "average-error: " << averageSquareDiff(truth, predictions) << "\n" << "crowd-error: " << square(truth - average) << "\n" << "diversity: " << averageSquareDiff(average, predictions) << std::endl; } int main() { diversityTheorem(49, {48,47,51}); diversityTheorem(49, {48,47,51,42}); return 0; }
c392
#include <algorithm> #include <iostream> #include <string> #include <vector> typedef unsigned char ubyte; const auto BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::vector<ubyte> encode(const std::vector<ubyte>& source) { auto it = source.cbegin(); auto end = source.cend(); std::vector<ubyte> sink; while (it != end) { auto b1 = *it++; int acc; sink.push_back(BASE64[b1 >> 2]); acc = (b1 & 0x3) << 4; if (it != end) { auto b2 = *it++; acc |= (b2 >> 4); sink.push_back(BASE64[acc]); acc = (b2 & 0xF) << 2; if (it != end) { auto b3 = *it++; acc |= (b3 >> 6); sink.push_back(BASE64[acc]); sink.push_back(BASE64[b3 & 0x3F]); } else { sink.push_back(BASE64[acc]); sink.push_back('='); } } else { sink.push_back(BASE64[acc]); sink.push_back('='); sink.push_back('='); } } return sink; } int findIndex(ubyte val) { if ('A' <= val && val <= 'Z') { return val - 'A'; } if ('a' <= val && val <= 'z') { return val - 'a' + 26; } if ('0' <= val && val <= '9') { return val - '0' + 52; } if ('+' == val) { return 62; } if ('/' == val) { return 63; } return -1; } std::vector<ubyte> decode(const std::vector<ubyte>& source) { if (source.size() % 4 != 0) { throw new std::runtime_error("Error in size to the decode method"); } auto it = source.cbegin(); auto end = source.cend(); std::vector<ubyte> sink; while (it != end) { auto b1 = *it++; auto b2 = *it++; auto b3 = *it++; auto b4 = *it++; auto i1 = findIndex(b1); auto i2 = findIndex(b2); auto acc = i1 << 2; acc |= i2 >> 4; sink.push_back(acc); if (b3 != '=') { auto i3 = findIndex(b3); acc = (i2 & 0xF) << 4; acc |= i3 >> 2; sink.push_back(acc); if (b4 != '=') { auto i4 = findIndex(b4); acc = (i3 & 0x3) << 6; acc |= i4; sink.push_back(acc); } } } return sink; } int main() { using namespace std; string data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"; vector<ubyte> datav{ begin(data), end(data) }; cout << data << "\n\n" << decode(datav).data() << endl; return 0; }
c393
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); const uint64_t limit = 10000000000; uint64_t max_diff = 0; primesieve::iterator pi; uint64_t p1 = pi.next_prime(); for (uint64_t p = 10;;) { uint64_t p2 = pi.next_prime(); if (p2 >= p) { std::cout << "Largest gap between primes under " << p << " is " << max_diff << ".\n"; if (p == limit) break; p *= 10; } if (p2 - p1 > max_diff) max_diff = p2 - p1; p1 = p2; } }
c394
#include <tr1/functional> #include <iostream> using namespace std; using namespace std::tr1; void first(function<void()> f) { f(); } void second() { cout << "second\n"; } int main() { first(second); }
c395
#include <iostream> unsigned int ackermann(unsigned int m, unsigned int n) { if (m == 0) { return n + 1; } if (n == 0) { return ackermann(m - 1, 1); } return ackermann(m - 1, ackermann(m, n - 1)); } int main() { for (unsigned int m = 0; m < 4; ++m) { for (unsigned int n = 0; n < 10; ++n) { std::cout << "A(" << m << ", " << n << ") = " << ackermann(m, n) << "\n"; } } }
c396
#include <algorithm> template <typename Iterator> double median(Iterator begin, Iterator end) { Iterator middle = begin + (end - begin) / 2; std::nth_element(begin, middle, end); if ((end - begin) % 2 != 0) { return *middle; } else { Iterator lower_middle = std::max_element(begin, middle); return (*middle + *lower_middle) / 2.0; } } #include <iostream> int main() { double a[] = {4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}; double b[] = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2}; std::cout << median(a+0, a + sizeof(a)/sizeof(a[0])) << std::endl; std::cout << median(b+0, b + sizeof(b)/sizeof(b[0])) << std::endl; return 0; }
c397
#include <algorithm> #include <iostream> #include <vector> using namespace std; const vector<string> MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; struct Birthday { int month, day; friend ostream &operator<<(ostream &, const Birthday &); }; ostream &operator<<(ostream &out, const Birthday &birthday) { return out << MONTHS[birthday.month - 1] << ' ' << birthday.day; } template <typename C> bool monthUniqueIn(const Birthday &b, const C &container) { auto it = cbegin(container); auto end = cend(container); int count = 0; while (it != end) { if (it->month == b.month) { count++; } it = next(it); } return count == 1; } template <typename C> bool dayUniqueIn(const Birthday &b, const C &container) { auto it = cbegin(container); auto end = cend(container); int count = 0; while (it != end) { if (it->day == b.day) { count++; } it = next(it); } return count == 1; } template <typename C> bool monthWithUniqueDayIn(const Birthday &b, const C &container) { auto it = cbegin(container); auto end = cend(container); while (it != end) { if (it->month == b.month && dayUniqueIn(*it, container)) { return true; } it = next(it); } return false; } int main() { vector<Birthday> choices = { {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}, }; vector<Birthday> filtered; for (auto bd : choices) { if (!monthUniqueIn(bd, choices)) { filtered.push_back(bd); } } vector<Birthday> filtered2; for (auto bd : filtered) { if (!monthWithUniqueDayIn(bd, filtered)) { filtered2.push_back(bd); } } vector<Birthday> filtered3; for (auto bd : filtered2) { if (dayUniqueIn(bd, filtered2)) { filtered3.push_back(bd); } } vector<Birthday> filtered4; for (auto bd : filtered3) { if (monthUniqueIn(bd, filtered3)) { filtered4.push_back(bd); } } if (filtered4.size() == 1) { cout << "Cheryl's birthday is " << filtered4[0] << '\n'; } else { cout << "Something went wrong!\n"; } return 0; }
c398
#include <iostream> #include <utility> using namespace std; int main(void) { cout << "Find a solution to i = 2 * j - 7\n"; pair<int, int> answer; for(int i = 0; true; i++) { for(int j = 0; j < i; j++) { if( i == 2 * j - 7) { answer = make_pair(i, j); goto loopexit; } } } loopexit: cout << answer.first << " = 2 * " << answer.second << " - 7\n\n"; goto spagetti; int k; k = 9; spagetti: cout << "k = " << k << "\n"; }
c399
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; vector<string> rd{ "22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999" }; for (uint64_t ii = 2; ii < 5; ii++) { cout << "First 10 super-" << ii << " numbers:\n"; int count = 0; for (uint64_t j = 3; ; j++) { auto k = ii * ipow(j, ii); auto kstr = to_string(k); auto needle = rd[(size_t)(ii - 2)]; auto res = kstr.find(needle); if (res != string::npos) { count++; cout << j << ' '; if (count == 10) { cout << "\n\n"; break; } } } } return 0; }
c400
#include<iostream> #include<conio.h> using namespace std; typedef unsigned long ulong; int ith_digit_finder(long long n, long b, long i){ while(i>0){ n/=b; i--; } return (n%b); } long eeuclid(long m, long b, long *inverse){ long A1 = 1, A2 = 0, A3 = m, B1 = 0, B2 = 1, B3 = b, T1, T2, T3, Q; cout<<endl<<"eeuclid() started"<<endl; while(1){ if(B3 == 0){ *inverse = 0; return A3; } if(B3 == 1){ *inverse = B2; return B3; } Q = A3/B3; T1 = A1 - Q*B1; T2 = A2 - Q*B2; T3 = A3 - Q*B3; A1 = B1; A2 = B2; A3 = B3; B1 = T1; B2 = T2; B3 = T3; } cout<<endl<<"ending eeuclid() "<<endl; } long long mon_red(long m, long m_dash, long T, int n, long b = 2){ long long A,ui, temp, Ai; if( m_dash < 0 ) m_dash = m_dash + b; A = T; for(int i = 0; i<n; i++){ Ai = ith_digit_finder(A, b, i); ui = ( ( Ai % b) * m_dash ) % b; temp = ui*m*power(b, i); A = A + temp; } A = A/power(b, n); if(A >= m) A = A - m; return A; } int main(){ long a, b, c, d=0, e, inverse = 0; cout<<"m >> "; cin >> a; cout<<"T >> "; cin>>b; cout<<"Radix b >> "; cin>>c; eeuclid(c, a, &d); e = mon_red(a, -d, b, length_finder(a, c), c); cout<<"Montgomery domain representation = "<<e; return 0; }
c401
#include <iostream> #include <iomanip> #include <string> #include <gmpxx.h> std::string smallest_six(unsigned int n) { mpz_class pow = 1; std::string goal = std::to_string(n); while (pow.get_str().find(goal) == std::string::npos) { pow *= 6; } return pow.get_str(); } int main() { for (unsigned int i=0; i<22; i++) { std::cout << std::setw(2) << i << ": " << smallest_six(i) << std::endl; } return 0; }
c402
#include <vector> #include <iostream> using namespace std; class ludic { public: void ludicList() { _list.push_back( 1 ); vector<int> v; for( int x = 2; x < 22000; x++ ) v.push_back( x ); while( true ) { vector<int>::iterator i = v.begin(); int z = *i; _list.push_back( z ); while( true ) { i = v.erase( i ); if( distance( i, v.end() ) <= z - 1 ) break; advance( i, z - 1 ); } if( v.size() < 1 ) return; } } void show( int s, int e ) { for( int x = s; x < e; x++ ) cout << _list[x] << " "; } void findTriplets( int e ) { int lu, x = 0; while( _list[x] < e ) { lu = _list[x]; if( inList( lu + 2 ) && inList( lu + 6 ) ) cout << "(" << lu << " " << lu + 2 << " " << lu + 6 << ")\n"; x++; } } int count( int e ) { int x = 0, c = 0; while( _list[x++] <= 1000 ) c++; return c; } private: bool inList( int lu ) { for( int x = 0; x < 250; x++ ) if( _list[x] == lu ) return true; return false; } vector<int> _list; }; int main( int argc, char* argv[] ) { ludic l; l.ludicList(); cout << "first 25 ludic numbers:" << "\n"; l.show( 0, 25 ); cout << "\n\nThere are " << l.count( 1000 ) << " ludic numbers <= 1000" << "\n"; cout << "\n2000 to 2005'th ludic numbers:" << "\n"; l.show( 1999, 2005 ); cout << "\n\nall triplets of ludic numbers < 250:" << "\n"; l.findTriplets( 250 ); cout << "\n\n"; return system( "pause" ); }
c403
#include <iostream> int main() { int undefined; if (undefined == 42) { std::cout << "42"; } if (undefined != 42) { std::cout << "not 42"; } }
c404
#include <iostream> unsigned int sum_square_digits(unsigned int n) { int i,num=n,sum=0; while (num > 0) { int digit=num % 10; num=(num - digit)/10; sum+=digit*digit; } return sum; } int main(void) { unsigned int i=0,result=0, count=0; for (i=1; i<=100000000; i++) { if ((i != 1) || (i != 89)) { result = sum_square_digits(i); } else { result = i; } while ((result != 1) && (result != 89)) { result = sum_square_digits(result); } if (result == 89) { count++; } } std::cout << count << std::endl; return 0; }
c405
#include <iostream> #include <fstream> #include <set> #include <sstream> #include <string> #include <vector> std::vector<std::string> longest_substrings_without_repeats(const std::string& str) { size_t max_length = 0; std::vector<std::string> result; size_t length = str.size(); for (size_t offset = 0; offset < length; ++offset) { std::set<char> characters; size_t len = 0; for (; offset + len < length; ++len) { if (characters.find(str[offset + len]) != characters.end()) break; characters.insert(str[offset + len]); } if (len > max_length) { result.clear(); max_length = len; } if (len == max_length) result.push_back(str.substr(offset, max_length)); } return result; } void print_strings(const std::vector<std::string>& strings) { std::cout << "["; for (size_t i = 0, n = strings.size(); i < n; ++i) { if (i > 0) std::cout << ", "; std::cout << '\'' << strings[i] << '\''; } std::cout << "]"; } void test1() { for (std::string str : { "xyzyabcybdfd", "xyzyab", "zzzzz", "a", "thisisastringtest", "" }) { std::cout << "Input: '" << str << "'\nResult: "; print_strings(longest_substrings_without_repeats(str)); std::cout << "\n\n"; } } std::string slurp(std::istream& in) { std::ostringstream out; out << in.rdbuf(); return out.str(); } void test2(const std::string& filename) { std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return; } std::cout << "Longest substring with no repeats found in '" << filename << "': "; print_strings(longest_substrings_without_repeats(slurp(in))); std::cout << "\n"; } int main() { test1(); test2("unixdict.txt"); }
c406
#include <iostream> #include <algorithm> #include<cstdio> using namespace std; void Pascal_Triangle(int size) { int a[100][100]; int i, j; for (i = 1; i <= size; i++) { a[i][1] = a[1][i] = 1; } for (i = 2; i <= size; i++) { for (j = 2; j <= size - i; j++) { if (a[i - 1][j] == 0 || a[i][j - 1] == 0) { break; } a[i][j] = a[i - 1][j] + a[i][j - 1]; } } int row,space; for (i = 1; i < size; i++) { space=row=i; j=1; while(space<=size+(size-i)+1){ cout<<" "; space++; } while(j<=i){ if (a[row][j] == 0){ break; } if(j==1){ printf("%d",a[row--][j++]); } else printf("%6d",a[row--][j++]); } cout<<"\n\n"; } } int main() { int size; cin>>size; Pascal_Triangle(size); } }
c407
#include <assert.h> #include <cmath> #include <vector> #include <iostream> template<int N> struct MomentsAccumulator_ { std::vector<double> m_; MomentsAccumulator_() : m_(N + 1, 0.0) {} void operator()(double v) { double inc = 1.0; for (auto& mi : m_) { mi += inc; inc *= v; } } }; double Stdev(const std::vector<double>& moments) { assert(moments.size() > 2); assert(moments[0] > 0.0); const double mean = moments[1] / moments[0]; const double meanSquare = moments[2] / moments[0]; return sqrt(meanSquare - mean * mean); } int main(void) { std::vector<int> data({ 2, 4, 4, 4, 5, 5, 7, 9 }); MomentsAccumulator_<2> accum; for (auto d : data) { accum(d); std::cout << "Running stdev: " << Stdev(accum.m_) << "\n"; } }
c408
#include <algorithm> #include <array> #include <chrono> #include <iomanip> #include <iostream> #include <mutex> #include <random> #include <thread> using namespace std; constexpr int bucket_count = 15; void equalizer(array<int, bucket_count>& buckets, array<mutex, bucket_count>& bucket_mutex) { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dist_bucket(0, bucket_count - 1); while (true) { int from = dist_bucket(gen); int to = dist_bucket(gen); if (from != to) { lock_guard<mutex> lock_first(bucket_mutex[min(from, to)]); lock_guard<mutex> lock_second(bucket_mutex[max(from, to)]); int diff = buckets[from] - buckets[to]; int amount = abs(diff / 2); if (diff < 0) { swap(from, to); } buckets[from] -= amount; buckets[to] += amount; } } } void randomizer(array<int, bucket_count>& buckets, array<mutex, bucket_count>& bucket_mutex) { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dist_bucket(0, bucket_count - 1); while (true) { int from = dist_bucket(gen); int to = dist_bucket(gen); if (from != to) { lock_guard<mutex> lock_first(bucket_mutex[min(from, to)]); lock_guard<mutex> lock_second(bucket_mutex[max(from, to)]); uniform_int_distribution<> dist_amount(0, buckets[from]); int amount = dist_amount(gen); buckets[from] -= amount; buckets[to] += amount; } } } void print_buckets(const array<int, bucket_count>& buckets) { int total = 0; for (const int& bucket : buckets) { total += bucket; cout << setw(3) << bucket << ' '; } cout << "= " << setw(3) << total << endl; } int main() { random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dist(0, 99); array<int, bucket_count> buckets; array<mutex, bucket_count> bucket_mutex; for (int& bucket : buckets) { bucket = dist(gen); } print_buckets(buckets); thread t_eq(equalizer, ref(buckets), ref(bucket_mutex)); thread t_rd(randomizer, ref(buckets), ref(bucket_mutex)); while (true) { this_thread::sleep_for(chrono::seconds(1)); for (mutex& mutex : bucket_mutex) { mutex.lock(); } print_buckets(buckets); for (mutex& mutex : bucket_mutex) { mutex.unlock(); } } return 0; }
c409
#include <iostream> #include <cmath> using namespace std; const string animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}; const string elements[]={"Wood","Fire","Earth","Metal","Water"}; string getElement(int year) { int element = floor((year-4)%10/2); return elements[element]; } string getAnimal(int year) { return animals[(year-4)%12]; } string getYY(int year) { if(year%2==0) { return "yang"; } else { return "yin"; } } int main() { int years[]={1935,1938,1968,1972,1976,2017}; for(int i=0;i<6;i++) { cout << years[i] << " is the year of the " << getElement(years[i]) << " " << getAnimal(years[i]) << " (" << getYY(years[i]) << ")." << endl; } return 0; }
c410
#include <deque> #include <iostream> int hcseq(int n) { static std::deque<int> seq(2, 1); while (seq.size() < n) { int x = seq.back(); seq.push_back(seq[x-1] + seq[seq.size()-x]); } return seq[n-1]; } int main() { int pow2 = 1; for (int i = 0; i < 20; ++i) { int pow2next = 2*pow2; double max = 0; for (int n = pow2; n < pow2next; ++n) { double anon = hcseq(n)/double(n); if (anon > max) max = anon; } std::cout << "maximum of a(n)/n between 2^" << i << " (" << pow2 << ") and 2^" << i+1 << " (" << pow2next << ") is " << max << "\n"; pow2 = pow2next; } }
c411
#include <iostream> #include <algorithm> #include <vector> std::vector<int> findProperDivisors ( int n ) { std::vector<int> divisors ; for ( int i = 1 ; i < n / 2 + 1 ; i++ ) { if ( n % i == 0 ) divisors.push_back( i ) ; } return divisors ; } int main( ) { std::vector<int> deficients , perfects , abundants , divisors ; for ( int n = 1 ; n < 20001 ; n++ ) { divisors = findProperDivisors( n ) ; int sum = std::accumulate( divisors.begin( ) , divisors.end( ) , 0 ) ; if ( sum < n ) { deficients.push_back( n ) ; } if ( sum == n ) { perfects.push_back( n ) ; } if ( sum > n ) { abundants.push_back( n ) ; } } std::cout << "Deficient : " << deficients.size( ) << std::endl ; std::cout << "Perfect  : " << perfects.size( ) << std::endl ; std::cout << "Abundant  : " << abundants.size( ) << std::endl ; return 0 ; }
c412
#include <vector> #include <iostream> #include <algorithm> #include <sstream> #include <string> #include <cmath> bool isPrime ( int number ) { if ( number <= 1 ) return false ; if ( number == 2 ) return true ; for ( int i = 2 ; i <= std::sqrt( number ) ; i++ ) { if ( number % i == 0 ) return false ; } return true ; } int reverseNumber ( int n ) { std::ostringstream oss ; oss << n ; std::string numberstring ( oss.str( ) ) ; std::reverse ( numberstring.begin( ) , numberstring.end( ) ) ; return std::stoi ( numberstring ) ; } bool isEmirp ( int n ) { return isPrime ( n ) && isPrime ( reverseNumber ( n ) ) && n != reverseNumber ( n ) ; } int main( ) { std::vector<int> emirps ; int i = 1 ; while ( emirps.size( ) < 20 ) { if ( isEmirp( i ) ) { emirps.push_back( i ) ; } i++ ; } std::cout << "The first 20 emirps:\n" ; for ( int i : emirps ) std::cout << i << " " ; std::cout << '\n' ; int newstart = 7700 ; while ( newstart < 8001 ) { if ( isEmirp ( newstart ) ) std::cout << newstart << '\n' ; newstart++ ; } while ( emirps.size( ) < 10000 ) { if ( isEmirp ( i ) ) { emirps.push_back( i ) ; } i++ ; } std::cout << "the 10000th emirp is " << emirps[9999] << " !\n" ; return 0 ; }
c413
#include <algorithm> #include <array> #include <iterator> #include <limits> #include <tuple> namespace detail_ { constexpr auto digits = std::array{'0','1','2','3','4','5','6','7','8','9'}; template <typename OutputIterator> constexpr auto encode_run_length(std::size_t n, OutputIterator out) { constexpr auto base = digits.size(); auto const num_digits = [base](auto n) { auto d = std::size_t{1}; while ((n /= digits.size())) ++d; return d; }(n); auto base_power = [base](auto n) { auto res = decltype(base){1}; for (auto i = decltype(n){1}; i < n; ++i) res *= base; return res; }; for (auto i = decltype(num_digits){0}; i < num_digits; ++i) *out++ = digits[(n / base_power(num_digits - i)) % base]; return out; } template <typename InputIterator> auto decode_run_length(InputIterator first, InputIterator last) { auto count = std::size_t{0}; while (first != last) { auto const p = std::find(digits.begin(), digits.end(), *first); if (p == digits.end()) break; count *= digits.size(); count += std::distance(digits.begin(), p); ++first; } return std::tuple{count, first}; } } template <typename InputIterator, typename OutputIterator> constexpr auto encode(InputIterator first, InputIterator last, OutputIterator out) { while (first != last) { auto const value = *first++; auto count = std::size_t{1}; while (first != last && *first == value) { ++count; ++first; } out = detail_::encode_run_length(count, out); *out++ = value; } return out; } template <typename InputIterator, typename OutputIterator> auto decode(InputIterator first, InputIterator last, OutputIterator out) { while (first != last) { using detail_::digits; auto count = std::size_t{1}; if (std::find(digits.begin(), digits.end(), *first) != digits.end()) std::tie(count, first) = detail_::decode_run_length(first, last); out = std::fill_n(out, count, *first++); } return out; } template <typename Range, typename OutputIterator> constexpr auto encode(Range&& range, OutputIterator out) { using std::begin; using std::end; return encode(begin(range), end(range), out); } template <typename Range, typename OutputIterator> auto decode(Range&& range, OutputIterator out) { using std::begin; using std::end; return decode(begin(range), end(range), out); } #include <iostream> #include <string_view> int main() { using namespace std::literals; constexpr auto test_string = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"sv; std::cout << "Input: \"" << test_string << "\"\n"; std::cout << "Output: \""; encode(test_string, std::ostreambuf_iterator<char>{std::cout}); std::cout << "\"\n"; auto encoded_str = std::string{}; auto decoded_str = std::string{}; encode(test_string, std::back_inserter(encoded_str)); decode(encoded_str, std::back_inserter(decoded_str)); std::cout.setf(std::cout.boolalpha); std::cout << "Round trip works: " << (test_string == decoded_str) << '\n'; }
c414
#include <windows.h> #include <iostream> #include <string> using namespace std; enum states { SEED, GROWING, MOVING, REST }; enum treeStates { NONE, MOVER, TREE }; const int MAX_SIDE = 480, MAX_MOVERS = 511, MAX_CELLS = 15137; class point { public: point() { x = y = 0; } point( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } int x, y; }; class movers { public: point pos; bool moving; movers() : moving( false ){} }; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file; GetObject( bmp, sizeof( bitmap ), &bitmap ); dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() { return hdc; } int getWidth() { return width; } int getHeight() { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class brownianTree { public: brownianTree() { _bmp.create( MAX_SIDE, MAX_SIDE ); init(); } void init() { _cellCount = 0; ZeroMemory( _grid, sizeof( _grid ) ); _bmp.clear(); _state = SEED; } bool mainLoop() { switch( _state ) { case REST: saveTree(); return false; case SEED: doSeed(); break; case GROWING: startMovers(); break; case MOVING: moveMovers(); } return true; } myBitmap* getBmp() { return &_bmp; } private: void saveTree() { for( int y = 0; y < MAX_SIDE; y++ ) for( int x = 0; x < MAX_SIDE; x++ ) if( _grid[x][y] == TREE ) SetPixel( _bmp.getDC(), x, y, RGB( 255, 120, 0 ) ); _bmp.saveBitmap( "f:\\rc\\tree.bmp" ); } void doSeed() { int x = MAX_SIDE - MAX_SIDE / 2, y = MAX_SIDE / 4; _grid[rand() % x + y][rand() % x + y] = TREE; _cellCount++; _state = GROWING; } void addMover( movers* m ) { m->moving = true; int x = MAX_SIDE - MAX_SIDE / 2, y = MAX_SIDE / 4, a, b; while( true ) { a = rand() % x + y; b = rand() % x + y; if( _grid[a][b] == NONE ) break; } m->pos.set( a, b ); _grid[a][b] = MOVER; } void startMovers() { movers* m; for( int c = 0; c < MAX_MOVERS; c++ ) { m = &_movers[c]; addMover( m ); } _state = MOVING; } void addToTree( movers* m ) { m->moving = false; _grid[m->pos.x][m->pos.y] = TREE; if( ++_cellCount >= MAX_CELLS ) _state = REST; COORD c = { 0, 1 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << "Cells added: " << _cellCount << " from " << MAX_CELLS << " => " << static_cast<float>( 100 * _cellCount ) / static_cast<float>( MAX_CELLS ) << "% "; } bool moveIt( movers* m ) { point f[8]; int ff = 0; for( int y = -1; y < 2; y++ ) { for( int x = -1; x < 2; x++ ) { if( !x && !y ) continue; int a = m->pos.x + x, b = m->pos.y + y; if( a < 0 || b < 0 || a >= MAX_SIDE || b >= MAX_SIDE ) { addToTree( m ); return true; } switch( _grid[a][b] ) { case TREE: addToTree( m ); return true; case NONE: f[ff++].set( a, b ); } } } if( ff < 1 ) return false; _grid[m->pos.x][m->pos.y] = NONE; m->pos = f[rand() % ff]; _grid[m->pos.x][m->pos.y] = MOVER; return false; } void moveMovers() { movers* mm; for( int m = 0; m < MAX_MOVERS; m++ ) { mm = &_movers[m]; if( !mm->moving ) continue; if( moveIt( mm ) && _cellCount < MAX_CELLS ) addMover( mm ); } } states _state; BYTE _grid[MAX_SIDE][MAX_SIDE]; myBitmap _bmp; int _cellCount; movers _movers[MAX_MOVERS]; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() ); brownianTree tree; DWORD now = GetTickCount(); while( tree.mainLoop() ); now = GetTickCount() - now; cout << endl << endl << "It took " << now / 1000 << " seconds to complete the task!" << endl << endl; BitBlt( GetDC( GetConsoleWindow() ), 20, 90, MAX_SIDE, MAX_SIDE, tree.getBmp()->getDC(), 0, 0, SRCCOPY ); system( "pause" ); return 0; }
c415
#include <fstream> #include <iostream> #include <locale> using namespace std; int main(void) { std::locale::global(std::locale("")); std::cout.imbue(std::locale()); ifstream in("input.txt"); wchar_t c; while ((c = in.get()) != in.eof()) wcout<<c; in.close(); return EXIT_SUCCESS; }
c416
#include <iostream> #include <iomanip> #include <cmath> #include <algorithm> size_t table_column_width(const int min, const int max) { unsigned int abs_max = std::max(max*max, min*min); size_t colwidth = 2 + std::log10(abs_max); if (min < 0 && max > 0) ++colwidth; return colwidth; } struct Writer_ { decltype(std::setw(1)) fmt_; Writer_(size_t w) : fmt_(std::setw(w)) {} template<class T_> Writer_& operator()(const T_& info) { std::cout << fmt_ << info; return *this; } }; void print_table_header(const int min, const int max) { Writer_ write(table_column_width(min, max)); write(" "); for(int col = min; col <= max; ++col) write(col); std::cout << std::endl << std::endl; } void print_table_row(const int num, const int min, const int max) { Writer_ write(table_column_width(min, max)); write(num); for(int multiplicand = min; multiplicand < num; ++multiplicand) write(" "); for(int multiplicand = num; multiplicand <= max; ++multiplicand) write(num * multiplicand); std::cout << std::endl << std::endl; } void print_table(const int min, const int max) { print_table_header(min, max); for(int row = min; row <= max; ++row) print_table_row(row, min, max); } int main() { print_table(1, 12); return 0; }
c417
#include <iostream> #include <cmath> #include <cassert> using namespace std; inline double Det(double a, double b, double c, double d) { return a*d - b*c; } bool LineLineIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, double &ixOut, double &iyOut) { double detL1 = Det(x1, y1, x2, y2); double detL2 = Det(x3, y3, x4, y4); double x1mx2 = x1 - x2; double x3mx4 = x3 - x4; double y1my2 = y1 - y2; double y3my4 = y3 - y4; double denom = Det(x1mx2, y1my2, x3mx4, y3my4); if(denom == 0.0) { ixOut = NAN; iyOut = NAN; return false; } double xnom = Det(detL1, x1mx2, detL2, x3mx4); double ynom = Det(detL1, y1my2, detL2, y3my4); ixOut = xnom / denom; iyOut = ynom / denom; if(!isfinite(ixOut) || !isfinite(iyOut)) return false; return true; } int main() { double x1=4.0, y1=0.0; double x2=6.0, y2=10.0; double x3=0.0, y3=3.0; double x4=10.0, y4=7.0; double ix = -1.0, iy = -1.0; bool result = LineLineIntersect(x1, y1, x2, y2, x3, y3, x4, y4, ix, iy); cout << "result " << result << "," << ix << "," << iy << endl; double eps = 1e-6; assert(result == true); assert(fabs(ix - 5.0) < eps); assert(fabs(iy - 5.0) < eps); return 0; }
c418
for (container_type::iterator i = container.begin(); i != container.end(); ++i) { std::cout << *i << "\n"; }
c419
#include <iostream> #include <string> void string_has_repeated_character(const std::string& str) { size_t len = str.length(); std::cout << "input: \"" << str << "\", length: " << len << '\n'; for (size_t i = 0; i < len; ++i) { for (size_t j = i + 1; j < len; ++j) { if (str[i] == str[j]) { std::cout << "String contains a repeated character.\n"; std::cout << "Character '" << str[i] << "' (hex " << std::hex << static_cast<unsigned int>(str[i]) << ") occurs at positions " << std::dec << i + 1 << " and " << j + 1 << ".\n\n"; return; } } } std::cout << "String contains no repeated characters.\n\n"; } int main() { string_has_repeated_character(""); string_has_repeated_character("."); string_has_repeated_character("abcABC"); string_has_repeated_character("XYZ ZYX"); string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"); return 0; }
c420
#include <iostream> #include <vector> #include <cmath> #include <numeric> int main( ) { std::vector<int> numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast<double>( numbers.size() ) ); std::cout << "The quadratic mean of the numbers 1 .. " << numbers.size() << " is " << meansquare << " !\n" ; return 0 ; }
c421
#include <iostream> #include <sstream> #include <iterator> #include <climits> #include <deque> template<typename OutIter> bool parse_number_list_with_ranges(std::istream& is, OutIter out) { int number; while (is >> number) { *out++ = number; char c; if (is >> c) switch(c) { case ',': continue; case '-': { int number2; if (is >> number2) { if (number2 < number) return false; while (number < number2) *out++ = ++number; char c2; if (is >> c2) if (c2 == ',') continue; else return false; else return is.eof(); } else return false; } default: return is.eof(); } else return is.eof(); } return false; } int main() { std::istringstream example("-6,-3--1,3-5,7-11,14,15,17-20"); std::deque<int> v; bool success = parse_number_list_with_ranges(example, std::back_inserter(v)); if (success) { std::copy(v.begin(), v.end()-1, std::ostream_iterator<int>(std::cout, ",")); std::cout << v.back() << "\n"; } else std::cout << "an error occured."; }
c422
#include <algorithm> #include <iostream> #include <vector> const int STX = 0x02; const int ETX = 0x03; void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; } std::string bwt(const std::string &s) { for (char c : s) { if (c == STX || c == ETX) { throw std::runtime_error("Input can't contain STX or ETX"); } } std::string ss; ss += STX; ss += s; ss += ETX; std::vector<std::string> table; for (size_t i = 0; i < ss.length(); i++) { table.push_back(ss); rotate(ss); } std::sort(table.begin(), table.end()); std::string out; for (auto &s : table) { out += s[s.length() - 1]; } return out; } std::string ibwt(const std::string &r) { int len = r.length(); std::vector<std::string> table(len); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { table[j] = r[j] + table[j]; } std::sort(table.begin(), table.end()); } for (auto &row : table) { if (row[row.length() - 1] == ETX) { return row.substr(1, row.length() - 2); } } return {}; } std::string makePrintable(const std::string &s) { auto ls = s; for (auto &c : ls) { if (c == STX) { c = '^'; } else if (c == ETX) { c = '|'; } } return ls; } int main() { auto tests = { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" }; for (auto &test : tests) { std::cout << makePrintable(test) << "\n"; std::cout << " --> "; std::string t; try { t = bwt(test); std::cout << makePrintable(t) << "\n"; } catch (std::runtime_error &e) { std::cout << "Error " << e.what() << "\n"; } std::string r = ibwt(t); std::cout << " --> " << r << "\n\n"; } return 0; }
c423
#include <functional> #include <iostream> #include <random> class BinarySearchTree { private: struct Node { int key; Node *left, *right; Node(int k) : key(k), left(nullptr), right(nullptr) { } } *root; public: BinarySearchTree() : root(nullptr) { } bool insert(int key) { if (root == nullptr) { root = new Node(key); } else { auto n = root; Node *parent; while (true) { if (n->key == key) { return false; } parent = n; bool goLeft = key < n->key; n = goLeft ? n->left : n->right; if (n == nullptr) { if (goLeft) { parent->left = new Node(key); } else { parent->right = new Node(key); } break; } } } return true; } friend std::ostream &operator<<(std::ostream &, const BinarySearchTree &); }; template<typename T> void display(std::ostream &os, const T *n) { if (n != nullptr) { os << "Node("; display(os, n->left); os << ',' << n->key << ','; display(os, n->right); os << ")"; } else { os << '-'; } } std::ostream &operator<<(std::ostream &os, const BinarySearchTree &bst) { display(os, bst.root); return os; } int main() { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, 200); auto rng = std::bind(distribution, generator); BinarySearchTree tree; tree.insert(100); for (size_t i = 0; i < 20; i++) { tree.insert(rng()); } std::cout << tree << '\n'; return 0; }
c424
#include <fstream> #include <boost/array.hpp> #include <string> #include <cstdlib> #include <ctime> #include <sstream> void makeGap( int gap , std::string & text ) { for ( int i = 0 ; i < gap ; i++ ) text.append( " " ) ; } int main( ) { boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ; int headgap = 3 ; int bodygap = 3 ; int tablegap = 6 ; int rowgap = 9 ; std::string tabletext( "<html>\n" ) ; makeGap( headgap , tabletext ) ; tabletext += "<head></head>\n" ; makeGap( bodygap , tabletext ) ; tabletext += "<body>\n" ; makeGap( tablegap , tabletext ) ; tabletext += "<table>\n" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "<thead align=\"right\">\n" ; makeGap( tablegap, tabletext ) ; tabletext += "<tr><th></th>" ; for ( int i = 0 ; i < 3 ; i++ ) { tabletext += "<td>" ; tabletext += *(chars.begin( ) + i ) ; tabletext += "</td>" ; } tabletext += "</tr>\n" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "</thead>" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "<tbody align=\"right\">\n" ; srand( time( 0 ) ) ; for ( int row = 0 ; row < 5 ; row++ ) { makeGap( rowgap , tabletext ) ; std::ostringstream oss ; tabletext += "<tr><td>" ; oss << row ; tabletext += oss.str( ) ; for ( int col = 0 ; col < 3 ; col++ ) { oss.str( "" ) ; int randnumber = rand( ) % 10000 ; oss << randnumber ; tabletext += "<td>" ; tabletext.append( oss.str( ) ) ; tabletext += "</td>" ; } tabletext += "</tr>\n" ; } makeGap( tablegap + 1 , tabletext ) ; tabletext += "</tbody>\n" ; makeGap( tablegap , tabletext ) ; tabletext += "</table>\n" ; makeGap( bodygap , tabletext ) ; tabletext += "</body>\n" ; tabletext += "</html>\n" ; std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ; htmltable << tabletext ; htmltable.close( ) ; return 0 ; }
c425
#include <string> #include <boost/regex.hpp> #include <boost/asio.hpp> #include <vector> #include <utility> #include <iostream> #include <sstream> #include <cstdlib> #include <algorithm> #include <iomanip> struct Sort { bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b ) const { return a.second > b.second ; } } ; int main( ) { try { boost::asio::io_service io_service ; boost::asio::ip::tcp::resolver resolver ( io_service ) ; boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ; boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ; boost::asio::ip::tcp::resolver::iterator end ; boost::asio::ip::tcp::socket socket( io_service ) ; boost::system::error_code error = boost::asio::error::host_not_found ; while ( error && endpoint_iterator != end ) { socket.close( ) ; socket.connect( *endpoint_iterator++ , error ) ; } if ( error ) throw boost::system::system_error ( error ) ; boost::asio::streambuf request ; std::ostream request_stream( &request ) ; request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ; request_stream << "Host: " << "rosettacode.org" << "\r\n" ; request_stream << "Accept: */*\r\n" ; request_stream << "Connection: close\r\n\r\n" ; boost::asio::write( socket , request ) ; boost::asio::streambuf response ; std::istream response_stream ( &response ) ; boost::asio::read_until( socket , response , "\r\n\r\n" ) ; boost::regex e( "<li><a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)</a>\\s?\\((\\d+) members\\)</li>" ) ; std::ostringstream line ; std::vector<std::pair<std::string , int> > languages ; boost::smatch matches ; while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) { line << &response ; if ( boost::regex_search( line.str( ) , matches , e ) ) { std::string lang( matches[2].first , matches[2].second ) ; int zahl = atoi ( lang.c_str( ) ) ; languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ; } line.str( "") ; } if ( error != boost::asio::error::eof ) throw boost::system::system_error( error ) ; std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ; int n = 1 ; for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ; spi != languages.end( ) ; ++spi ) { std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right << spi->second << " - " << spi->first << '\n' ; n++ ; } } catch ( std::exception &ex ) { std::cout << "Exception: " << ex.what( ) << '\n' ; } return 0 ; }
c426
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, {2, 1000000000, false}, }; for (auto intv : intervals) { if (intv.start == 2) { std::cout << "eban numbers up to and including " << intv.end << ":\n"; } else { std::cout << "eban numbers bwteen " << intv.start << " and " << intv.end << " (inclusive):\n"; } int count = 0; for (int i = intv.start; i <= intv.end; i += 2) { int b = i / 1000000000; int r = i % 1000000000; int m = r / 1000000; r = i % 1000000; int t = r / 1000; r %= 1000; if (m >= 30 && m <= 66) m %= 10; if (t >= 30 && t <= 66) t %= 10; if (r >= 30 && r <= 66) r %= 10; if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (intv.print) std::cout << i << ' '; count++; } } } } } if (intv.print) { std::cout << '\n'; } std::cout << "count = " << count << "\n\n"; } return 0; }
c427
template<typename Number> Number power(Number base, int exponent) { int zerodir; Number factor; if (exponent < 0) { zerodir = 1; factor = Number(1)/base; } else { zerodir = -1; factor = base; } Number result(1); while (exponent != 0) { if (exponent % 2 != 0) { result *= factor; exponent += zerodir; } else { factor *= factor; exponent /= 2; } } return result; }
c428
#include <iostream> #include <string> #include <queue> #include <utility> int main() { std::priority_queue<std::pair<int, std::string> > pq; pq.push(std::make_pair(3, "Clear drains")); pq.push(std::make_pair(4, "Feed cat")); pq.push(std::make_pair(5, "Make tea")); pq.push(std::make_pair(1, "Solve RC tasks")); pq.push(std::make_pair(2, "Tax return")); while (!pq.empty()) { std::cout << pq.top().first << ", " << pq.top().second << std::endl; pq.pop(); } return 0; }
c429
#include <iomanip> #include <iostream> class Date { private: int year, month, day; public: Date(std::string str) { if (isValidDate(str)) { year = atoi(&str[0]); month = atoi(&str[5]); day = atoi(&str[8]); } else { throw std::exception("Invalid date"); } } int getYear() { return year; } int getMonth() { return month; } int getDay() { return day; } static bool isValidDate(std::string str) { if (str.length() != 10 || str[4] != '-' || str[7] != '-') { return false; } if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) { return false; } if (!isdigit(str[5]) || !isdigit(str[6])) { return false; } if (!isdigit(str[8]) || !isdigit(str[9])) { return false; } int year = atoi(&str[0]); int month = atoi(&str[5]); int day = atoi(&str[8]); if (year <= 0 || month <= 0 || day <= 0) { return false; } if (month > 12) { return false; } switch (month) { case 2: if (day > 29) { return false; } if (!isLeapYear(year) && day == 29) { return false; } break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (day > 31) { return false; } break; default: if (day > 30) { return false; } break; } return true; } static bool isLeapYear(int year) { if (year > 1582) { return ((year % 4 == 0) && (year % 100 > 0)) || (year % 400 == 0); } if (year > 10) { return year % 4 == 0; } return false; } friend std::ostream &operator<<(std::ostream &, Date &); }; std::ostream &operator<<(std::ostream &os, Date &d) { os << std::setfill('0') << std::setw(4) << d.year << '-'; os << std::setfill('0') << std::setw(2) << d.month << '-'; os << std::setfill('0') << std::setw(2) << d.day; return os; } int diffDays(Date date1, Date date2) { int d1m = (date1.getMonth() + 9) % 12; int d1y = date1.getYear() - d1m / 10; int d2m = (date2.getMonth() + 9) % 12; int d2y = date2.getYear() - d2m / 10; int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1); int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1); return days2 - days1; } int main() { std::string ds1 = "2019-01-01"; std::string ds2 = "2019-12-02"; if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) { Date d1(ds1); Date d2(ds2); std::cout << "Days difference : " << diffDays(d1, d2); } else { std::cout << "Dates are invalid.\n"; } return 0; }
c430
#ifndef TASK_H #define TASK_H #include <QWidget> class QPushButton ; class QString ; class QLineEdit ; class QLabel ; class QVBoxLayout ; class QHBoxLayout ; class MyWidget : public QWidget { Q_OBJECT public: MyWidget( QWidget *parent = 0 ) ; private slots: void buttonChange( const QString & ) ; void addField( ) ; void subtractField( ) ; private : QVBoxLayout *thisWidgetLayout ; QLabel *instruction ; QPushButton *increment ; QPushButton *decrement ; QLineEdit *entryField ; QHBoxLayout *lowerPart ; } ; #endif
c431
#include <iostream> #include <string> using namespace std; int main() { string story, input; while(true) { getline(cin, input); if(input == "\r") break; story += input; } int begin; while((begin = story.find("<")) != string::npos) { int end = story.find(">"); string cat = story.substr(begin + 1, end - begin - 1); cout << "Give me a " << cat << ": "; cin >> input; while((begin = story.find("<" + cat + ">")) != string::npos) { story.replace(begin, cat.length()+2, input); } } cout << endl << story; return 0; }
c432
#include <iostream> class T { public: virtual void identify() { std::cout << "I am a genuine T" << std::endl; } virtual T* clone() { return new T(*this); } virtual ~T() {} }; class S: public T { public: virtual void identify() { std::cout << "I am an S" << std::endl; } virtual S* clone() { return new S(*this); } }; class X { public: X(T* t): member(t) {} X(X const& other): member(other.member->clone()) {} X& operator=(X const& other) { T* new_member = other.member->clone(); delete member; member = new_member; } ~X() { delete member; } void identify_member() { member->identify(); } private: T* member; }; int main() { X original(new S); X copy = original; copy.identify_member(); }
c433
#include <algorithm> #include <cctype> #include <string> #include <iostream> const std::string alphabet("abcdefghijklmnopqrstuvwxyz"); bool is_pangram(std::string s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); std::sort(s.begin(), s.end()); return std::includes(s.begin(), s.end(), alphabet.begin(), alphabet.end()); } int main() { const auto examples = {"The quick brown fox jumps over the lazy dog", "The quick white cat jumps over the lazy dog"}; std::cout.setf(std::ios::boolalpha); for (auto& text : examples) { std::cout << "Is \"" << text << "\" a pangram? - " << is_pangram(text) << std::endl; } }
c434
#include <string> #include <iomanip> #include <iostream> #define HEIGHT 16 #define WIDTH 6 #define ASCII_START 32 #define ASCII_END 128 #define SPACE 32 #define DELETE 127 std::string displayAscii(int ascii) { switch(ascii) { case SPACE: return "Spc"; case DELETE: return "Del"; default: return std::string(1,char(ascii)); } } int main(void) { for(int row = 0; row < HEIGHT; ++row) { for(int col = 0; col < WIDTH; ++col) { int ascii = ASCII_START + row + col*HEIGHT; std::cout << std::right << std::setw(3) << ascii << " : " \ << std::left << std::setw(6) << displayAscii(ascii); } std::cout << std::endl; } }
c435
#include <array> #include <iomanip> #include <iostream> #include <vector> int indexOf(const std::vector<int> &haystack, int needle) { auto it = haystack.cbegin(); auto end = haystack.cend(); int idx = 0; for (; it != end; it = std::next(it)) { if (*it == needle) { return idx; } idx++; } return -1; } bool getDigits(int n, int le, std::vector<int> &digits) { while (n > 0) { auto r = n % 10; if (r == 0 || indexOf(digits, r) >= 0) { return false; } le--; digits[le] = r; n /= 10; } return true; } int removeDigit(const std::vector<int> &digits, int le, int idx) { static std::array<int, 5> pows = { 1, 10, 100, 1000, 10000 }; int sum = 0; auto pow = pows[le - 2]; for (int i = 0; i < le; i++) { if (i == idx) continue; sum += digits[i] * pow; pow /= 10; } return sum; } int main() { std::vector<std::pair<int, int>> lims = { {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764} }; std::array<int, 5> count; std::array<std::array<int, 10>, 5> omitted; std::fill(count.begin(), count.end(), 0); std::for_each(omitted.begin(), omitted.end(), [](auto &a) { std::fill(a.begin(), a.end(), 0); } ); for (size_t i = 0; i < lims.size(); i++) { std::vector<int> nDigits(i + 2); std::vector<int> dDigits(i + 2); for (int n = lims[i].first; n <= lims[i].second; n++) { std::fill(nDigits.begin(), nDigits.end(), 0); bool nOk = getDigits(n, i + 2, nDigits); if (!nOk) { continue; } for (int d = n + 1; d <= lims[i].second + 1; d++) { std::fill(dDigits.begin(), dDigits.end(), 0); bool dOk = getDigits(d, i + 2, dDigits); if (!dOk) { continue; } for (size_t nix = 0; nix < nDigits.size(); nix++) { auto digit = nDigits[nix]; auto dix = indexOf(dDigits, digit); if (dix >= 0) { auto rn = removeDigit(nDigits, i + 2, nix); auto rd = removeDigit(dDigits, i + 2, dix); if ((double)n / d == (double)rn / rd) { count[i]++; omitted[i][digit]++; if (count[i] <= 12) { std::cout << n << '/' << d << " = " << rn << '/' << rd << " by omitting " << digit << "'s\n"; } } } } } } std::cout << '\n'; } for (int i = 2; i <= 5; i++) { std::cout << "There are " << count[i - 2] << ' ' << i << "-digit fractions of which:\n"; for (int j = 1; j <= 9; j++) { if (omitted[i - 2][j] == 0) { continue; } std::cout << std::setw(6) << omitted[i - 2][j] << " have " << j << "'s omitted\n"; } std::cout << '\n'; } return 0; }
c436
#include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <map> #include <numeric> #include <set> #include <string> bool is_deranged(const std::string& left, const std::string& right) { return (left.size() == right.size()) && (std::inner_product(left.begin(), left.end(), right.begin(), 0, std::plus<int>(), std::equal_to<char>()) == 0); } int main() { std::ifstream input("unixdict.txt"); if (!input) { std::cerr << "can't open input file\n"; return EXIT_FAILURE; } typedef std::set<std::string> WordList; typedef std::map<std::string, WordList> AnagraMap; AnagraMap anagrams; std::pair<std::string, std::string> result; size_t longest = 0; for (std::string value; input >> value; ) { std::string key(value); std::sort(key.begin(), key.end()); if (longest < value.length()) { if (0 < anagrams.count(key)) { for (const auto& prior : anagrams[key]) { if (is_deranged(prior, value)) { result = std::make_pair(prior, value); longest = value.length(); } } } } anagrams[key].insert(value); } std::cout << result.first << ' ' << result.second << '\n'; return EXIT_SUCCESS; }
c437
#include <iomanip> #include <iostream> #include <tuple> #include <vector> const std::string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; std::string encodeNegativeBase(int64_t n, int b) { if (b < -62 || b > -1) { throw std::runtime_error("Argument out of range: b"); } if (n == 0) { return "0"; } std::string output; int64_t nn = n; while (nn != 0) { int rem = nn % b; nn /= b; if (rem < 0) { nn++; rem -= b; } output += DIGITS[rem]; } std::reverse(output.begin(), output.end()); return output; } int64_t decodeNegativeBase(const std::string& ns, int b) { if (b < -62 || b > -1) { throw std::runtime_error("Argument out of range: b"); } if (ns == "0") { return 0; } int64_t total = 0; int64_t bb = 1; for (auto it = ns.crbegin(); it != ns.crend(); it = std::next(it)) { auto ptr = std::find(DIGITS.cbegin(), DIGITS.cend(), *it); if (ptr != DIGITS.cend()) { auto idx = ptr - DIGITS.cbegin(); total += idx * bb; } bb *= b; } return total; } int main() { using namespace std; vector<pair<int64_t, int>> nbl({ make_pair(10, -2), make_pair(146, -3), make_pair(15, -10), make_pair(142961, -62) }); for (auto& p : nbl) { string ns = encodeNegativeBase(p.first, p.second); cout << setw(12) << p.first << " encoded in base " << setw(3) << p.second << " = " << ns.c_str() << endl; int64_t n = decodeNegativeBase(ns, p.second); cout << setw(12) << ns.c_str() << " decoded in base " << setw(3) << p.second << " = " << n << endl; cout << endl; } return 0; }
c438
#include <algorithm> #include <iostream> #include <vector> std::vector<int> digits(int n) { std::vector<int> result; while (n > 0) { auto rem = n % 10; result.push_back(rem); n /= 10; } std::reverse(result.begin(), result.end()); return result; } bool is_strange(int n) { auto test = [](int a, int b) { auto v = std::abs(a - b); return v == 2 || v == 3 || v == 5 || v == 7; }; auto xs = digits(n); for (size_t i = 1; i < xs.size(); i++) { if (!test(xs[i - 1], xs[i])) { return false; } } return true; } int main() { std::vector<int> xs; for (int i = 100; i <= 500; i++) { if (is_strange(i)) { xs.push_back(i); } } std::cout << "Strange numbers in range [100..500]\n"; std::cout << "(Total: " << xs.size() << ")\n\n"; for (size_t i = 0; i < xs.size(); i++) { std::cout << xs[i]; if ((i + 1) % 10 == 0) { std::cout << '\n'; } else { std::cout << ' '; } } return 0; }
c439
#include <iostream> std::string scs(std::string x, std::string y) { if (x.empty()) { return y; } if (y.empty()) { return x; } if (x[0] == y[0]) { return x[0] + scs(x.substr(1), y.substr(1)); } if (scs(x, y.substr(1)).size() <= scs(x.substr(1), y).size()) { return y[0] + scs(x, y.substr(1)); } else { return x[0] + scs(x.substr(1), y); } } int main() { auto res = scs("abcbdab", "bdcaba"); std::cout << res << '\n'; return 0; }
c440
#include <queue> #include <cassert> int main() { std::queue<int> q; assert( q.empty() ); q.push(1); assert( !q.empty() ); assert( q.front() == 1 ); q.push(2); assert( !q.empty() ); assert( q.front() == 1 ); q.push(3); assert( !q.empty() ); assert( q.front() == 1 ); q.pop(); assert( !q.empty() ); assert( q.front() == 2); q.pop(); assert( !q.empty() ); assert( q.front() == 3); q.push(4); assert( !q.empty() ); assert( q.front() == 3); q.pop(); assert( !q.empty() ); assert( q.front() == 4); q.pop(); assert( q.empty() ); q.push(5); assert( !q.empty() ); assert( q.front() == 5); q.pop(); assert( q.empty() ); }
c441
#include <iostream> #include <random> int main() { std::random_device rd; std::uniform_int_distribution<long> dist; std::cout << "Random Number: " << dist(rd) << std::endl; }
c442
#include <iostream> int countDivisors(int n) { if (n < 2) return 1; int count = 2; for (int i = 2; i <= n/2; ++i) { if (n%i == 0) ++count; } return count; } int main() { int maxDiv = 0, count = 0; std::cout << "The first 20 anti-primes are:" << std::endl; for (int n = 1; count < 20; ++n) { int d = countDivisors(n); if (d > maxDiv) { std::cout << n << " "; maxDiv = d; count++; } } std::cout << std::endl; return 0; }
c443
void move(int n, int from, int to, int via) { if (n == 1) { std::cout << "Move disk from pole " << from << " to pole " << to << std::endl; } else { move(n - 1, from, via, to); move(1, from, to, via); move(n - 1, via, to, from); } }
c444
#include <iostream> int main() { unsigned i = 0; do { std::cout << std::oct << i << std::endl; ++i; } while(i != 0); return 0; }
c445
#include <string> #include <algorithm> #include <iostream> #include <vector> #include <regex> std::string findExtension ( const std::string & filename ) { auto position = filename.find_last_of ( '.' ) ; if ( position == std::string::npos ) return "" ; else { std::string extension ( filename.substr( position + 1 ) ) ; if (std::regex_search (extension, std::regex("[^A-Za-z0-9]") )) return "" ; else return extension ; } } int main( ) { std::vector<std::string> filenames {"picture.jpg" , "http: "myuniquefile.longextension" , "IAmAFileWithoutExtension" , "/path/to.my/file" , "file.odd_one", "thisismine." } ; std::vector<std::string> extensions( filenames.size( ) ) ; std::transform( filenames.begin( ) , filenames.end( ) , extensions.begin( ) , findExtension ) ; for ( int i = 0 ; i < filenames.size( ) ; i++ ) std::cout << filenames[i] << " has extension : " << extensions[i] << " !\n" ; return 0 ; }
c446
#include <iostream> #include <tuple> class Vector { private: double _x, _y, _z; public: Vector(double x, double y, double z) : _x(x), _y(y), _z(z) { } double getX() { return _x; } double getY() { return _y; } double getZ() { return _z; } double abs() { return sqrt(_x * _x + _y * _y + _z * _z); } Vector operator+(const Vector& rhs) const { return Vector(_x + rhs._x, _y + rhs._y, _z + rhs._z); } Vector operator*(double m) const { return Vector(_x * m, _y * m, _z * m); } Vector operator/(double m) const { return Vector(_x / m, _y / m, _z / m); } friend std::ostream& operator<<(std::ostream& os, const Vector& v); }; std::ostream& operator<<(std::ostream& os, const Vector& v) { return os << '(' << v._x << ", " << v._y << ", " << v._z << ')'; } std::pair<Vector, Vector> orbitalStateVectors( double semiMajorAxis, double eccentricity, double inclination, double longitudeOfAscendingNode, double argumentOfPeriapsis, double trueAnomaly ) { auto mulAdd = [](const Vector& v1, double x1, const Vector& v2, double x2) { return v1 * x1 + v2 * x2; }; auto rotate = [mulAdd](const Vector& iv, const Vector& jv, double alpha) { return std::make_pair( mulAdd(iv, +cos(alpha), jv, sin(alpha)), mulAdd(iv, -sin(alpha), jv, cos(alpha)) ); }; Vector i(1, 0, 0); Vector j(0, 1, 0); Vector k(0, 0, 1); auto p = rotate(i, j, longitudeOfAscendingNode); i = p.first; j = p.second; p = rotate(j, k, inclination); j = p.first; p = rotate(i, j, argumentOfPeriapsis); i = p.first; j = p.second; auto l = semiMajorAxis * ((eccentricity == 1.0) ? 2.0 : (1.0 - eccentricity * eccentricity)); auto c = cos(trueAnomaly); auto s = sin(trueAnomaly); auto r = l / (1.0 + eccentricity * c);; auto rprime = s * r * r / l; auto position = mulAdd(i, c, j, s) * r; auto speed = mulAdd(i, rprime * c - r * s, j, rprime * s + r * c); speed = speed / speed.abs(); speed = speed * sqrt(2.0 / r - 1.0 / semiMajorAxis); return std::make_pair(position, speed); } int main() { auto res = orbitalStateVectors(1.0, 0.1, 0.0, 355.0 / (113.0 * 6.0), 0.0, 0.0); std::cout << "Position : " << res.first << '\n'; std::cout << "Speed  : " << res.second << '\n'; return 0; }
c447
#include <windows.h> #include <sstream> #include <iostream> using namespace std; class floyds_tri { public: floyds_tri() { lastLineLen = 0; } ~floyds_tri() { killArray(); } void create( int rows ) { _rows = rows; calculateLastLineLen(); display(); } private: void killArray() { if( lastLineLen ) delete [] lastLineLen; } void calculateLastLineLen() { killArray(); lastLineLen = new BYTE[_rows]; int s = 1 + ( _rows * ( _rows - 1 ) ) / 2; for( int x = s, ix = 0; x < s + _rows; x++, ix++ ) { ostringstream cvr; cvr << x; lastLineLen[ix] = static_cast<BYTE>( cvr.str().size() ); } } void display() { cout << endl << "Floyd\'s Triangle - " << _rows << " rows" << endl << "===============================================" << endl; int number = 1; for( int r = 0; r < _rows; r++ ) { for( int c = 0; c <= r; c++ ) { ostringstream cvr; cvr << number++; string str = cvr.str(); while( str.length() < lastLineLen[c] ) str = " " + str; cout << str << " "; } cout << endl; } } int _rows; BYTE* lastLineLen; }; int main( int argc, char* argv[] ) { floyds_tri t; int s; while( true ) { cout << "Enter the size of the triangle ( 0 to QUIT ): "; cin >> s; if( !s ) return 0; if( s > 0 ) t.create( s ); cout << endl << endl; system( "pause" ); } return 0; }
c448
#include <windows.h> #include <iostream> using namespace std; class calender { public: void drawCalender( int y ) { year = y; for( int i = 0; i < 12; i++ ) firstdays[i] = getfirstday( i ); isleapyear(); build(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } int getfirstday( int m ) { int y = year; int f = y + 1 + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } void build() { int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); COORD pos = { 0, ystr }; draw(); for( int i = 0; i < 4; i++ ) { for( int j = 0; j < 3; j++ ) { int d = firstdays[fd++], dm = days[m++]; pos.X = d * 3 + start; SetConsoleCursorPosition( h, pos ); for( int dd = 0; dd < dm; dd++ ) { if( dd < 9 ) cout << 0 << dd + 1 << " "; else cout << dd + 1 << " "; pos.X += 3; if( pos.X - start > 20 ) { pos.X = start; pos.Y++; SetConsoleCursorPosition( h, pos ); } } start += 23; pos.X = start; pos.Y = ystr; SetConsoleCursorPosition( h, pos ); } ystr += 9; start = 2; pos.Y = ystr; } } void draw() { system( "cls" ); cout << "+--------------------------------------------------------------------+" << endl; cout << "| [SNOOPY] |" << endl; cout << "| |" << endl; cout << "| == " << year << " == |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JANUARY | FEBRUARY | MARCH |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| APRIL | MAY | JUNE |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| JULY | AUGUST | SEPTEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "| | | |" << endl; cout << "+----------------------+----------------------+----------------------+" << endl; } int firstdays[12], year; bool isleap; }; int main( int argc, char* argv[] ) { int y; calender cal; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; cal.drawCalender( y ); cout << endl << endl << endl << endl << endl << endl << endl << endl; system( "pause" ); } return 0; }
c449
#include <algorithm> #include <chrono> #include <iostream> #include <random> #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 << ", "; os << *it; it = std::next(it); } return os << ']'; } void printSquare(const std::vector<std::vector<int>> &latin) { for (auto &row : latin) { std::cout << row << '\n'; } std::cout << '\n'; } void latinSquare(int n) { if (n <= 0) { std::cout << "[]\n"; return; } unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); auto g = std::default_random_engine(seed); std::vector<std::vector<int>> latin; for (int i = 0; i < n; ++i) { std::vector<int> inner; for (int j = 0; j < n; ++j) { inner.push_back(j); } latin.push_back(inner); } std::shuffle(latin[0].begin(), latin[0].end(), g); for (int i = 1; i < n - 1; ++i) { bool shuffled = false; while (!shuffled) { std::shuffle(latin[i].begin(), latin[i].end(), g); for (int k = 0; k < i; ++k) { for (int j = 0; j < n; ++j) { if (latin[k][j] == latin[i][j]) { goto shuffling; } } } shuffled = true; shuffling: {} } } for (int j = 0; j < n; ++j) { std::vector<bool> used(n, false); for (int i = 0; i < n - 1; ++i) { used[latin[i][j]] = true; } for (int k = 0; k < n; ++k) { if (!used[k]) { latin[n - 1][j] = k; break; } } } printSquare(latin); } int main() { latinSquare(5); latinSquare(5); latinSquare(10); return 0; }