_id
stringlengths
2
5
text
stringlengths
7
10.9k
title
stringclasses
1 value
c860
#include <iomanip> #include <map> #include <vector> #include <iostream> using namespace std; void calcMDR( int n, int c, int& a, int& b ) { int m = n % 10; n /= 10; while( n ) { m *= ( n % 10 ); n /= 10; } if( m >= 10 ) calcMDR( m, ++c, a, b ); else { a = m; b = c; } } void table() { map<int, vector<int> > mp; int n = 0, a, b; bool f = true; while( f ) { f = false; calcMDR( n, 1, a, b ); mp[a].push_back( n ); n++; for( int x = 0; x < 10; x++ ) if( mp[x].size() < 5 ) { f = true; break; } } cout << "| MDR | [n0..n4]\n+-------+------------------------------------+\n"; for( int x = 0; x < 10; x++ ) { cout << right << "| " << setw( 6 ) << x << "| "; for( vector<int>::iterator i = mp[x].begin(); i != mp[x].begin() + 5; i++ ) cout << setw( 6 ) << *i << " "; cout << "|\n"; } cout << "+-------+------------------------------------+\n\n"; } int main( int argc, char* argv[] ) { cout << "| NUMBER | MDR | MP |\n+----------+----------+----------+\n"; int numbers[] = { 123321, 7739, 893, 899998 }, a, b; for( int x = 0; x < 4; x++ ) { cout << right << "| " << setw( 9 ) << numbers[x] << "| "; calcMDR( numbers[x], 1, a, b ); cout << setw( 9 ) << a << "| " << setw( 9 ) << b << "|\n"; } cout << "+----------+----------+----------+\n\n"; table(); return system( "pause" ); }
c861
#include<graphics.h> #include<iostream> int main() { int k; initwindow(1500,810,"Rosetta Cuboid"); do{ std::cout<<"Enter ratio of sides ( 0 or -ve to exit) : "; std::cin>>k; if(k>0){ bar3d(100, 100, 100 + 2*k, 100 + 4*k, 3*k, 1); } }while(k>0); return 0; }
c862
#include <cstdlib> #include <fstream> #include <iostream> bool is_abc_word(const std::string& word) { bool a = false; bool b = false; for (char ch : word) { switch (ch) { case 'a': if (!a) a = true; break; case 'b': if (!b) { if (!a) return false; b = true; } break; case 'c': return b; } } return false; } int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string word; int n = 1; while (getline(in, word)) { if (is_abc_word(word)) std::cout << n++ << ": " << word << '\n'; } return EXIT_SUCCESS; }
c863
#include <Windows.h> int main() { bool showCursor = false; HANDLE std_out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(out, &cursorInfo); cursorInfo.bVisible = showCursor; SetConsoleCursorInfo(out, &cursorInfo); }
c864
#include <string> #include <numeric> int main() { std::string lower(26,' '); std::iota(lower.begin(), lower.end(), 'a'); }
c865
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> bool is_probably_prime(const mpz_class& n) { return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0; } 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; } int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int count_all(const std::string& str, int rem) { int count = 0; if (rem == 0) { switch (str.back()) { case '1': case '3': case '7': case '9': if (is_probably_prime(mpz_class(str))) ++count; break; default: break; } } else { for (int i = 1; i <= std::min(9, rem); ++i) count += count_all(str + char('0' + i), rem - i); } return count; } int main() { std::cout.imbue(std::locale("")); const int limit = 5000; std::cout << "Primes < " << limit << " whose digits sum to 25:\n"; int count = 0; for (int p = 1; p < limit; ++p) { if (digit_sum(p) == 25 && is_prime(p)) { ++count; std::cout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' '); } } std::cout << '\n'; auto start = std::chrono::steady_clock::now(); count = count_all("", 25); auto end = std::chrono::steady_clock::now(); std::cout << "\nThere are " << count << " primes whose digits sum to 25 and include no zeros.\n"; std::cout << "Time taken: " << std::chrono::duration<double>(end - start).count() << "s\n"; return 0; }
c866
#include <vector> #include <string> #include <sstream> #include <iostream> #include <cmath> #include <algorithm> #include <iterator> #include <cstdlib> double rpn(const std::string &expr){ std::istringstream iss(expr); std::vector<double> stack; std::cout << "Input\tOperation\tStack after" << std::endl; std::string token; while (iss >> token) { std::cout << token << "\t"; double tokenNum; if (std::istringstream(token) >> tokenNum) { std::cout << "Push\t\t"; stack.push_back(tokenNum); } else { std::cout << "Operate\t\t"; double secondOperand = stack.back(); stack.pop_back(); double firstOperand = stack.back(); stack.pop_back(); if (token == "*") stack.push_back(firstOperand * secondOperand); else if (token == "/") stack.push_back(firstOperand / secondOperand); else if (token == "-") stack.push_back(firstOperand - secondOperand); else if (token == "+") stack.push_back(firstOperand + secondOperand); else if (token == "^") stack.push_back(std::pow(firstOperand, secondOperand)); else { std::cerr << "Error" << std::endl; std::exit(1); } } std::copy(stack.begin(), stack.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; } return stack.back(); } int main() { std::string s = " 3 4 2 * 1 5 - 2 3 ^ ^ / + "; std::cout << "Final answer: " << rpn(s) << std::endl; return 0; }
c867
#include <iostream> #include <QDomDocument> #include <QObject> int main() { QDomDocument doc; doc.setContent( QObject::tr( "<Students>\n" "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" "<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n" "<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n" "<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n" "<Pet Type=\"dog\" Name=\"Rover\" />\n" "</Student>\n" "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n" "</Students>")); QDomElement n = doc.documentElement().firstChildElement("Student"); while(!n.isNull()) { std::cout << qPrintable(n.attribute("Name")) << std::endl; n = n.nextSiblingElement(); } return 0; }
c868
#include <cstdlib> #include <algorithm> #include <iterator> template<typename RandomAccessIterator> void knuthShuffle(RandomAccessIterator begin, RandomAccessIterator end) { for(unsigned int n = end - begin - 1; n >= 1; --n) { unsigned int k = rand() % (n + 1); if(k != n) { std::iter_swap(begin + k, begin + n); } } }
c869
#include <set> #include <iostream> #include <iterator> #include <algorithm> namespace set_display { template <class T> std::ostream& operator<<(std::ostream& os, const std::set<T>& set) { os << '['; if (!set.empty()) { std::copy(set.begin(), --set.end(), std::ostream_iterator<T>(os, ", ")); os << *--set.end(); } return os << ']'; } } template <class T> bool contains(const std::set<T>& set, const T& key) { return set.count(key) != 0; } template <class T> std::set<T> set_union(const std::set<T>& a, const std::set<T>& b) { std::set<T> result; std::set_union(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end())); return result; } template <class T> std::set<T> set_intersection(const std::set<T>& a, const std::set<T>& b) { std::set<T> result; std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end())); return result; } template <class T> std::set<T> set_difference(const std::set<T>& a, const std::set<T>& b) { std::set<T> result; std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end())); return result; } template <class T> bool is_subset(const std::set<T>& set, const std::set<T>& subset) { return std::includes(set.begin(), set.end(), subset.begin(), subset.end()); } int main() { using namespace set_display; std::set<int> a{2, 5, 7, 5, 9, 2}; std::set<int> b{1, 5, 9, 7, 4 }; std::cout << "a = " << a << '\n'; std::cout << "b = " << b << '\n'; int value1 = 8, value2 = 5; std::cout << "Set a " << (contains(a, value1) ? "contains " : "does not contain ") << value1 << '\n'; std::cout << "Set a " << (contains(a, value2) ? "contains " : "does not contain ") << value2 << '\n'; std::cout << "Union of a and b: " << set_union(a, b) << '\n'; std::cout << "Intersection of a and b: " << set_intersection(a, b) << '\n'; std::cout << "Difference of a and b: " << set_difference(a, b) << '\n'; std::set<int> sub{5, 9}; std::cout << "Set b " << (is_subset(a, b) ? "is" : "is not") << " a subset of a\n"; std::cout << "Set " << sub << ' ' << (is_subset(a, sub) ? "is" : "is not") << " a subset of a\n"; std::set<int> copy = a; std::cout << "a " << (a == copy ? "equals " : "does not equal ") << copy << '\n'; return 0; }
c870
#include <cmath> #include <iostream> #include <tuple> #include <vector> using triple = std::tuple<int, int, int>; void print_triple(std::ostream& out, const triple& t) { out << '(' << std::get<0>(t) << ',' << std::get<1>(t) << ',' << std::get<2>(t) << ')'; } void print_vector(std::ostream& out, const std::vector<triple>& vec) { if (vec.empty()) return; auto i = vec.begin(); print_triple(out, *i++); for (; i != vec.end(); ++i) { out << ' '; print_triple(out, *i); } out << "\n\n"; } int isqrt(int n) { return static_cast<int>(std::sqrt(n)); } int main() { const int min = 1, max = 13; std::vector<triple> solutions90, solutions60, solutions120; for (int a = min; a <= max; ++a) { int a2 = a * a; for (int b = a; b <= max; ++b) { int b2 = b * b, ab = a * b; int c2 = a2 + b2; int c = isqrt(c2); if (c <= max && c * c == c2) solutions90.emplace_back(a, b, c); else { c2 = a2 + b2 - ab; c = isqrt(c2); if (c <= max && c * c == c2) solutions60.emplace_back(a, b, c); else { c2 = a2 + b2 + ab; c = isqrt(c2); if (c <= max && c * c == c2) solutions120.emplace_back(a, b, c); } } } } std::cout << "There are " << solutions60.size() << " solutions for gamma = 60 degrees:\n"; print_vector(std::cout, solutions60); std::cout << "There are " << solutions90.size() << " solutions for gamma = 90 degrees:\n"; print_vector(std::cout, solutions90); std::cout << "There are " << solutions120.size() << " solutions for gamma = 120 degrees:\n"; print_vector(std::cout, solutions120); const int max2 = 10000; int count = 0; for (int a = min; a <= max2; ++a) { for (int b = a + 1; b <= max2; ++b) { int c2 = a * a + b * b - a * b; int c = isqrt(c2); if (c <= max2 && c * c == c2) ++count; } } std::cout << "There are " << count << " solutions for gamma = 60 degrees in the range " << min << " to " << max2 << " where the sides are not all of the same length.\n"; return 0; }
c871
#include<iostream> #include<unistd.h> int main() { pid_t pid = fork(); if (pid == 0) { std::cout << "This is the new process\n"; } else if (pid > 0) { std::cout << "This is the original process\n"; } else { std::cerr << "ERROR: Something went wrong\n"; } return 0; }
c872
#include <iostream> double f(double x) { return (x*x*x - 3*x*x + 2*x); } int main() { double step = 0.001; double start = -1; double stop = 3; double value = f(start); double sign = (value > 0); if ( 0 == value ) std::cout << "Root found at " << start << std::endl; for( double x = start + step; x <= stop; x += step ) { value = f(x); if ( ( value > 0 ) != sign ) std::cout << "Root found near " << x << std::endl; else if ( 0 == value ) std::cout << "Root found at " << x << std::endl; sign = ( value > 0 ); } }
c873
template<int N> struct Half { enum { Result = N >> 1 }; }; template<int N> struct Double { enum { Result = N << 1 }; }; template<int N> struct IsEven { static const bool Result = (N & 1) == 0; }; template<int Multiplier, int Multiplicand> struct EthiopianMultiplication { template<bool Cond, int Plier, int RunningTotal> struct AddIfNot { enum { Result = Plier + RunningTotal }; }; template<int Plier, int RunningTotal> struct AddIfNot <true, Plier, RunningTotal> { enum { Result = RunningTotal }; }; template<int Plier, int Plicand, int RunningTotal> struct Loop { enum { Result = Loop<Half<Plier>::Result, Double<Plicand>::Result, AddIfNot<IsEven<Plier>::Result, Plicand, RunningTotal >::Result >::Result }; }; template<int Plicand, int RunningTotal> struct Loop <0, Plicand, RunningTotal> { enum { Result = RunningTotal }; }; enum { Result = Loop<Multiplier, Multiplicand, 0>::Result }; }; #include <iostream> int main(int, char **) { std::cout << EthiopianMultiplication<17, 54>::Result << std::endl; return 0; }
c874
#include <iostream> #include <cmath> #include <utility> #include <vector> #include <stdexcept> using namespace std; typedef std::pair<double, double> Point; double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd) { double dx = lineEnd.first - lineStart.first; double dy = lineEnd.second - lineStart.second; double mag = pow(pow(dx,2.0)+pow(dy,2.0),0.5); if(mag > 0.0) { dx /= mag; dy /= mag; } double pvx = pt.first - lineStart.first; double pvy = pt.second - lineStart.second; double pvdot = dx * pvx + dy * pvy; double dsx = pvdot * dx; double dsy = pvdot * dy; double ax = pvx - dsx; double ay = pvy - dsy; return pow(pow(ax,2.0)+pow(ay,2.0),0.5); } void RamerDouglasPeucker(const vector<Point> &pointList, double epsilon, vector<Point> &out) { if(pointList.size()<2) throw invalid_argument("Not enough points to simplify"); double dmax = 0.0; size_t index = 0; size_t end = pointList.size()-1; for(size_t i = 1; i < end; i++) { double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]); if (d > dmax) { index = i; dmax = d; } } if(dmax > epsilon) { vector<Point> recResults1; vector<Point> recResults2; vector<Point> firstLine(pointList.begin(), pointList.begin()+index+1); vector<Point> lastLine(pointList.begin()+index, pointList.end()); RamerDouglasPeucker(firstLine, epsilon, recResults1); RamerDouglasPeucker(lastLine, epsilon, recResults2); out.assign(recResults1.begin(), recResults1.end()-1); out.insert(out.end(), recResults2.begin(), recResults2.end()); if(out.size()<2) throw runtime_error("Problem assembling output"); } else { out.clear(); out.push_back(pointList[0]); out.push_back(pointList[end]); } } int main() { vector<Point> pointList; vector<Point> pointListOut; pointList.push_back(Point(0.0, 0.0)); pointList.push_back(Point(1.0, 0.1)); pointList.push_back(Point(2.0, -0.1)); pointList.push_back(Point(3.0, 5.0)); pointList.push_back(Point(4.0, 6.0)); pointList.push_back(Point(5.0, 7.0)); pointList.push_back(Point(6.0, 8.1)); pointList.push_back(Point(7.0, 9.0)); pointList.push_back(Point(8.0, 9.0)); pointList.push_back(Point(9.0, 9.0)); RamerDouglasPeucker(pointList, 1.0, pointListOut); cout << "result" << endl; for(size_t i=0;i< pointListOut.size();i++) { cout << pointListOut[i].first << "," << pointListOut[i].second << endl; } return 0; }
c875
template<class InputIterator, class InputIterator2> void writedat(const char* filename, InputIterator xbegin, InputIterator xend, InputIterator2 ybegin, InputIterator2 yend, int xprecision=3, int yprecision=5) { std::ofstream f; f.exceptions(std::ofstream::failbit | std::ofstream::badbit); f.open(filename); for ( ; xbegin != xend and ybegin != yend; ++xbegin, ++ybegin) f << std::setprecision(xprecision) << *xbegin << '\t' << std::setprecision(yprecision) << *ybegin << '\n'; }
c876
#include <iostream> float epsilon() { float eps = 1.0f; while (1.0f + eps != 1.0f) eps /= 2.0f; return eps; } float kahanSum(std::initializer_list<float> nums) { float sum = 0.0f; float c = 0.0f; for (auto num : nums) { float y = num - c; float t = sum + y; c = (t - sum) - y; sum = t; } return sum; } int main() { using namespace std; float a = 1.f; float b = epsilon(); float c = -b; cout << "Epsilon = " << b << endl; cout << "(a + b) + c = " << (a + b) + c << endl; cout << "Kahan sum = " << kahanSum({ a, b, c }) << endl; return 0; }
c877
template<typename T> void swap(T& left, T& right) { T tmp(left); left = right; right = tmp; }
c878
#include <iomanip> #include <iostream> #include <list> using namespace std; void sieve(int limit, list<int> &primes) { bool *c = new bool[limit + 1]; for (int i = 0; i <= limit; i++) c[i] = false; int p = 3, n = 0; int p2 = p * p; while (p2 <= limit) { for (int i = p2; i <= limit; i += 2 * p) c[i] = true; do p += 2; while (c[p]); p2 = p * p; } for (int i = 3; i <= limit; i += 2) if (!c[i]) primes.push_back(i); delete [] c; } int findPeriod(int n) { int r = 1, rr, period = 0; for (int i = 1; i <= n + 1; ++i) r = (10 * r) % n; rr = r; do { r = (10 * r) % n; period++; } while (r != rr); return period; } int main() { int count = 0, index = 0; int numbers[] = {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000}; list<int> primes; list<int> longPrimes; int numberCount = sizeof(numbers) / sizeof(int); int *totals = new int[numberCount]; cout << "Please wait." << endl << endl; sieve(64000, primes); for (list<int>::iterator iterPrime = primes.begin(); iterPrime != primes.end(); iterPrime++) { if (findPeriod(*iterPrime) == *iterPrime - 1) longPrimes.push_back(*iterPrime); } for (list<int>::iterator iterLongPrime = longPrimes.begin(); iterLongPrime != longPrimes.end(); iterLongPrime++) { if (*iterLongPrime > numbers[index]) totals[index++] = count; ++count; } totals[numberCount - 1] = count; cout << "The long primes up to " << totals[0] << " are:" << endl; cout << "["; int i = 0; for (list<int>::iterator iterLongPrime = longPrimes.begin(); iterLongPrime != longPrimes.end() && i < totals[0]; iterLongPrime++, i++) { cout << *iterLongPrime << " "; } cout << "\b]" << endl; cout << endl << "The number of long primes up to:" << endl; for (int i = 0; i < 8; ++i) cout << " " << setw(5) << numbers[i] << " is " << totals[i] << endl; delete [] totals; }
c879
#include <iostream> #include <cmath> #include <utility> template<class P_> P_ IncFirst(const P_& src) {return P_(src.first + 1, src.second);} std::pair<int, int> DigitalRoot(unsigned long long digits, int base = 10) { int x = SumDigits(digits, base); return x < base ? std::make_pair(1, x) : IncFirst(DigitalRoot(x, base)); } int main() { const unsigned long long ip[] = {961038,923594037444,670033,448944221089}; for (auto i:ip){ auto res = DigitalRoot(i); std::cout << i << " has digital root " << res.second << " and additive persistance " << res.first << "\n"; } std::cout << "\n"; const unsigned long long hip[] = {0x7e0,0x14e344,0xd60141,0x12343210}; for (auto i:hip){ auto res = DigitalRoot(i,16); std::cout << std::hex << i << " has digital root " << res.second << " and additive persistance " << res.first << "\n"; } return 0; }
c880
void number_reversal_game() { cout << "Number Reversal Game. Type a number to flip the first n numbers."; cout << "You win by sorting the numbers in ascending order."; cout << "Anything besides numbers are ignored.\n"; cout << "\t |1__2__3__4__5__6__7__8__9|\n"; int list[9] = {1,2,3,4,5,6,7,8,9}; do { shuffle_list(list,9); } while(check_array(list, 9)); int tries=0; unsigned int i; int input; while(!check_array(list, 9)) { cout << "Round " << tries << ((tries<10) ? " : " : " : "); for(i=0;i<9;i++)cout << list[i] << " "; cout << " Gimme that number:"; while(1) { cin >> input; if(input>1&&input<10) break; cout << "\nPlease enter a number between 2 and 9:"; } tries++; do_flip(list, 9, input); } cout << "Hurray! You solved it in %d moves!\n"; }
c881
namespace rosettacode { template<typename T> class queue { public: queue(); ~queue(); void push(T const& t); T pop(); bool empty(); private: void drop(); struct node; node* head; node* tail; }; template<typename T> struct queue<T>::node { T data; node* next; node(T const& t): data(t), next(0) {} }; template<typename T> queue<T>::queue(): head(0) { } template<typename T> inline void queue<T>::drop() { node* n = head; head = head->next; delete n; } template<typename T> queue<T>::~queue() { while (!empty()) drop(); } template<typename T> void queue<T>::push(T const& t) { node*& next = head? tail->next : head; next = new node(t); tail = next; } template<typename T> T queue<T>::pop() { T tmp = head->data; drop(); return tmp; } template<typename T> bool queue<T>::empty() { return head == 0; } }
c882
#include <fstream> #include <iostream> std::string execute(const std::string& command) { system((command + " > temp.txt").c_str()); std::ifstream ifs("temp.txt"); std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() }; ifs.close(); if (std::remove("temp.txt") != 0) { perror("Error deleting temporary file"); } return ret; } int main() { std::cout << execute("whoami") << '\n'; }
c883
#include <iostream> #include <vector> #include <algorithm> #include <stdexcept> #include <memory> #include <sys/time.h> using std::cout; using std::endl; class StopTimer { public: StopTimer(): begin_(getUsec()) {} unsigned long long getTime() const { return getUsec() - begin_; } private: static unsigned long long getUsec() { timeval tv; const int res = ::gettimeofday(&tv, 0); if(res) return 0; return tv.tv_usec + 1000000 * tv.tv_sec; } unsigned long long begin_; }; struct KnapsackTask { struct Item { std::string name; unsigned w, v, qty; Item(): w(), v(), qty() {} Item(const std::string& iname, unsigned iw, unsigned iv, unsigned iqty): name(iname), w(iw), v(iv), qty(iqty) {} }; typedef std::vector<Item> Items; struct Solution { unsigned v, w; unsigned long long iterations, usec; std::vector<unsigned> n; Solution(): v(), w(), iterations(), usec() {} }; KnapsackTask(): maxWeight_(), totalWeight_() {} void add(const Item& item) { const unsigned totalItemWeight = item.w * item.qty; if(const bool invalidItem = !totalItemWeight) throw std::logic_error("Invalid item: " + item.name); totalWeight_ += totalItemWeight; items_.push_back(item); } const Items& getItems() const { return items_; } void setMaxWeight(unsigned maxWeight) { maxWeight_ = maxWeight; } unsigned getMaxWeight() const { return std::min(totalWeight_, maxWeight_); } private: unsigned maxWeight_, totalWeight_; Items items_; }; class BoundedKnapsackRecursiveSolver { public: typedef KnapsackTask Task; typedef Task::Item Item; typedef Task::Items Items; typedef Task::Solution Solution; void solve(const Task& task) { Impl(task, solution_).solve(); } const Solution& getSolution() const { return solution_; } private: class Impl { struct Candidate { unsigned v, n; bool visited; Candidate(): v(), n(), visited(false) {} }; typedef std::vector<Candidate> Cache; public: Impl(const Task& task, Solution& solution): items_(task.getItems()), maxWeight_(task.getMaxWeight()), maxColumnIndex_(task.getItems().size() - 1), solution_(solution), cache_(task.getMaxWeight() * task.getItems().size()), iterations_(0) {} void solve() { if(const bool nothingToSolve = !maxWeight_ || items_.empty()) return; StopTimer timer; Candidate candidate; solve(candidate, maxWeight_, items_.size() - 1); convertToSolution(candidate); solution_.usec = timer.getTime(); } private: void solve(Candidate& current, unsigned reminderWeight, const unsigned itemIndex) { ++iterations_; const Item& item(items_[itemIndex]); if(const bool firstColumn = !itemIndex) { const unsigned maxQty = std::min(item.qty, reminderWeight/item.w); current.v = item.v * maxQty; current.n = maxQty; current.visited = true; } else { const unsigned nextItemIndex = itemIndex - 1; { Candidate& nextItem = cachedItem(reminderWeight, nextItemIndex); if(!nextItem.visited) solve(nextItem, reminderWeight, nextItemIndex); current.visited = true; current.v = nextItem.v; current.n = 0; } if(reminderWeight >= item.w) { for (unsigned numberOfItems = 1; numberOfItems <= item.qty; ++numberOfItems) { reminderWeight -= item.w; Candidate& nextItem = cachedItem(reminderWeight, nextItemIndex); if(!nextItem.visited) solve(nextItem, reminderWeight, nextItemIndex); const unsigned checkValue = nextItem.v + numberOfItems * item.v; if ( checkValue > current.v) { current.v = checkValue; current.n = numberOfItems; } if(!(reminderWeight >= item.w)) break; } } } } void convertToSolution(const Candidate& candidate) { solution_.iterations = iterations_; solution_.v = candidate.v; solution_.n.resize(items_.size()); const Candidate* iter = &candidate; unsigned weight = maxWeight_, itemIndex = items_.size() - 1; while(true) { const unsigned currentWeight = iter->n * items_[itemIndex].w; solution_.n[itemIndex] = iter->n; weight -= currentWeight; if(!itemIndex--) break; iter = &cachedItem(weight, itemIndex); } solution_.w = maxWeight_ - weight; } Candidate& cachedItem(unsigned weight, unsigned itemIndex) { return cache_[weight * maxColumnIndex_ + itemIndex]; } const Items& items_; const unsigned maxWeight_; const unsigned maxColumnIndex_; Solution& solution_; Cache cache_; unsigned long long iterations_; }; Solution solution_; }; void populateDataset(KnapsackTask& task) { typedef KnapsackTask::Item Item; task.setMaxWeight( 400 ); task.add(Item("map",9,150,1)); task.add(Item("compass",13,35,1)); task.add(Item("water",153,200,2)); task.add(Item("sandwich",50,60,2)); task.add(Item("glucose",15,60,2)); task.add(Item("tin",68,45,3)); task.add(Item("banana",27,60,3)); task.add(Item("apple",39,40,3)); task.add(Item("cheese",23,30,1)); task.add(Item("beer",52,10,3)); task.add(Item("suntancream",11,70,1)); task.add(Item("camera",32,30,1)); task.add(Item("T-shirt",24,15,2)); task.add(Item("trousers",48,10,2)); task.add(Item("umbrella",73,40,1)); task.add(Item("w-trousers",42,70,1)); task.add(Item("w-overclothes",43,75,1)); task.add(Item("note-case",22,80,1)); task.add(Item("sunglasses",7,20,1)); task.add(Item("towel",18,12,2)); task.add(Item("socks",4,50,1)); task.add(Item("book",30,10,2)); } int main() { KnapsackTask task; populateDataset(task); BoundedKnapsackRecursiveSolver solver; solver.solve(task); const KnapsackTask::Solution& solution = solver.getSolution(); cout << "Iterations to solve: " << solution.iterations << endl; cout << "Time to solve: " << solution.usec << " usec" << endl; cout << "Solution:" << endl; for (unsigned i = 0; i < solution.n.size(); ++i) { if (const bool itemIsNotInKnapsack = !solution.n[i]) continue; cout << " " << solution.n[i] << ' ' << task.getItems()[i].name << " ( item weight = " << task.getItems()[i].w << " )" << endl; } cout << "Weight: " << solution.w << " Value: " << solution.v << endl; return 0; }
c884
#include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <vector> #include <time.h> using namespace std; const unsigned int LEN = 4; class CowsAndBulls_Player { public: CowsAndBulls_Player() { fillPool(); } void play() { secret = createSecret(); guess(); } private: void guess() { pair<int, int> res; int cc = 1; cout << endl << " SECRET: " << secret << endl << "==============" << endl; cout << "+-----------+---------+--------+\n| GUESS | BULLS | COWS |\n+-----------+---------+--------+\n"; while( true ) { string gs = gimmeANumber(); if( gs.empty() ) { cout << endl << "Something went wrong with the scoring..." << endl << "Cannot find an answer!" << endl; return; } if( scoreIt( gs, res ) ) { cout << endl << "I found the secret number!" << endl << "It is: " << gs << endl; return; } cout << "| " << gs << " | " << setw( 3 ) << res.first << " | " << setw( 3 ) << res.second << " |\n+-----------+---------+--------+\n"; clearPool( gs, res ); } } void clearPool( string gs, pair<int, int>& r ) { vector<string>::iterator pi = pool.begin(); while( pi != pool.end() ) { if( removeIt( gs, ( *pi ), r ) ) pi = pool.erase( pi ); else pi++; } } string gimmeANumber() { if( pool.empty() ) return ""; return pool[rand() % pool.size()]; } void fillPool() { for( int x = 1234; x < 9877; x++ ) { ostringstream oss; oss << x; if( check( oss.str() ) ) pool.push_back( oss.str() ); } } bool check( string s ) { for( string::iterator si = s.begin(); si != s.end(); si++ ) { if( ( *si ) == '0' ) return false; if( count( s.begin(), s.end(), ( *si ) ) > 1 ) return false; } return true; } bool removeIt( string gs, string ts, pair<int, int>& res ) { pair<int, int> tp; getScore( gs, ts, tp ); return tp != res; } bool scoreIt( string gs, pair<int, int>& res ) { getScore( gs, secret, res ); return res.first == LEN; } void getScore( string gs, string st, pair<int, int>& pr ) { pr.first = pr.second = 0; for( unsigned int ui = 0; ui < LEN; ui++ ) { if( gs[ui] == st[ui] ) pr.first++; else { for( unsigned int vi = 0; vi < LEN; vi++ ) if( gs[ui] == st[vi] ) pr.second++; } } } string createSecret() { string n = "123456789", rs = ""; while( rs.length() < LEN ) { int r = rand() % n.length(); rs += n[r]; n.erase( r, 1 ); } return rs; } string secret; vector<string> pool; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); CowsAndBulls_Player cb; cb.play(); cout << endl << endl; return system( "pause" ); }
c885
#include <iostream> #include <vector> using entry = std::pair<int, const char*>; void print(const std::vector<entry>& entries, std::ostream& out = std::cout) { bool first = true; for(const auto& e: entries) { if(!first) out << ", "; first = false; out << e.first << " " << e.second; } out << '\n'; } std::vector<entry> convert(int seconds) { static const entry time_table[] = { {7*24*60*60, "wk"}, {24*60*60, "d"}, {60*60, "hr"}, {60, "min"}, {1, "sec"} }; std::vector<entry> result; for(const auto& e: time_table) { int time = seconds / e.first; if(time != 0) result.emplace_back(time, e.second); seconds %= e.first; } return result; } int main() { std::cout << " 7259 sec is "; print(convert( 7259)); std::cout << " 86400 sec is "; print(convert( 86400)); std::cout << "6000000 sec is "; print(convert(6000000)); }
c886
#include <iostream> #include <algorithm> #include <vector> int pShuffle( int t ) { std::vector<int> v, o, r; for( int x = 0; x < t; x++ ) { o.push_back( x + 1 ); } r = o; int t2 = t / 2 - 1, c = 1; while( true ) { v = r; r.clear(); for( int x = t2; x > -1; x-- ) { r.push_back( v[x + t2 + 1] ); r.push_back( v[x] ); } std::reverse( r.begin(), r.end() ); if( std::equal( o.begin(), o.end(), r.begin() ) ) return c; c++; } } int main() { int s[] = { 8, 24, 52, 100, 1020, 1024, 10000 }; for( int x = 0; x < 7; x++ ) { std::cout << "Cards count: " << s[x] << ", shuffles required: "; std::cout << pShuffle( s[x] ) << ".\n"; } return 0; }
c887
#include <algorithm> #include <iostream> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; void SimpleConsolidate(vector<unordered_set<char>>& sets) { for(auto last = sets.rbegin(); last != sets.rend(); ++last) for(auto other = last + 1; other != sets.rend(); ++other) { bool hasIntersection = any_of(last->begin(), last->end(), [&](auto val) { return other->contains(val); }); if(hasIntersection) { other->merge(*last); sets.pop_back(); break; } } } struct Node { char Value; Node* Parent = nullptr; }; Node* FindTop(Node& node) { auto top = &node; while (top != top->Parent) top = top->Parent; for(auto element = &node; element->Parent != top; ) { auto parent = element->Parent; element->Parent = top; element = parent; } return top; } vector<unordered_set<char>> FastConsolidate(const vector<unordered_set<char>>& sets) { unordered_map<char, Node> elements; for(auto& set : sets) { Node* top = nullptr; for(auto val : set) { auto itr = elements.find(val); if(itr == elements.end()) { auto& ref = elements[val] = Node{val, nullptr}; if(!top) top = &ref; ref.Parent = top; } else { auto newTop = FindTop(itr->second); if(top) { top->Parent = newTop; itr->second.Parent = newTop; } else { top = newTop; } } } } unordered_map<char, unordered_set<char>> groupedByTop; for(auto& e : elements) { auto& element = e.second; groupedByTop[FindTop(element)->Value].insert(element.Value); } vector<unordered_set<char>> ret; for(auto& itr : groupedByTop) { ret.push_back(move(itr.second)); } return ret; } void PrintSets(const vector<unordered_set<char>>& sets) { for(const auto& set : sets) { cout << "{ "; for(auto value : set){cout << value << " ";} cout << "} "; } cout << "\n"; } int main() { const unordered_set<char> AB{'A', 'B'}, CD{'C', 'D'}, DB{'D', 'B'}, HIJ{'H', 'I', 'K'}, FGH{'F', 'G', 'H'}; vector <unordered_set<char>> AB_CD {AB, CD}; vector <unordered_set<char>> AB_DB {AB, DB}; vector <unordered_set<char>> AB_CD_DB {AB, CD, DB}; vector <unordered_set<char>> HIJ_AB_CD_DB_FGH {HIJ, AB, CD, DB, FGH}; PrintSets(FastConsolidate(AB_CD)); PrintSets(FastConsolidate(AB_DB)); PrintSets(FastConsolidate(AB_CD_DB)); PrintSets(FastConsolidate(HIJ_AB_CD_DB_FGH)); SimpleConsolidate(AB_CD); SimpleConsolidate(AB_DB); SimpleConsolidate(AB_CD_DB); SimpleConsolidate(HIJ_AB_CD_DB_FGH); PrintSets(AB_CD); PrintSets(AB_DB); PrintSets(AB_CD_DB); PrintSets(HIJ_AB_CD_DB_FGH); }
c888
#include <concepts> #include <iostream> void PrintMatrix(std::predicate<int, int, int> auto f, int size) { for(int y = 0; y < size; y++) { for(int x = 0; x < size; x++) { std::cout << " " << f(x, y, size); } std::cout << "\n"; } std::cout << "\n"; } int main() { auto fourSides = [](int x, int y, int size) { return x == 0 || (y == 0) || (x == size - 1) || (y == size - 1); }; PrintMatrix(fourSides, 8); PrintMatrix(fourSides, 9); }
c889
#include <windows.h> #include <string> #include <math.h> using namespace std; const int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20, MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20; const float PI = 3.1415926536f; class vector2 { public: vector2() { x = y = 0; } vector2( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { float _x = static_cast<float>( x ), _y = static_cast<float>( y ), s = sinf( angle_r ), c = cosf( angle_r ), a = _x * c - _y * s, b = _x * s + _y * c; x = static_cast<int>( a ); y = static_cast<int>( b ); } int x, y; }; 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( 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; } 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 clock { public: clock() { _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear( 100 ); _bmp.setPenWidth( 2 ); _ang = DegToRadian( 6 ); } void setNow() { GetLocalTime( &_sysTime ); draw(); } float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: void drawTicks( HDC dc ) { vector2 line; _bmp.setPenWidth( 1 ); for( int x = 0; x < 60; x++ ) { line.set( 0, 50 ); line.rotate( static_cast<float>( x + 30 ) * _ang ); MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL ); LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) ); } _bmp.setPenWidth( 3 ); for( int x = 0; x < 60; x += 5 ) { line.set( 0, 50 ); line.rotate( static_cast<float>( x + 30 ) * _ang ); MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL ); LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) ); } } void drawHands( HDC dc ) { float hp = DegToRadian( ( 30.0f * static_cast<float>( _sysTime.wMinute ) ) / 60.0f ); int h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5; _bmp.setPenWidth( 3 ); _bmp.setPenColor( RGB( 0, 0, 255 ) ); drawHand( dc, HOUR_LEN, ( _ang * static_cast<float>( 30 + h ) ) + hp ); _bmp.setPenColor( RGB( 0, 128, 0 ) ); drawHand( dc, MIN_LEN, _ang * static_cast<float>( 30 + _sysTime.wMinute ) ); _bmp.setPenWidth( 2 ); _bmp.setPenColor( RGB( 255, 0, 0 ) ); drawHand( dc, SEC_LEN, _ang * static_cast<float>( 30 + _sysTime.wSecond ) ); } void drawHand( HDC dc, int len, float ang ) { vector2 line; line.set( 0, len ); line.rotate( ang ); MoveToEx( dc, CENTER, CENTER, NULL ); LineTo( dc, line.x + CENTER, line.y + CENTER ); } void draw() { HDC dc = _bmp.getDC(); _bmp.setBrushColor( RGB( 250, 250, 250 ) ); Ellipse( dc, 0, 0, BMP_SIZE, BMP_SIZE ); _bmp.setBrushColor( RGB( 230, 230, 230 ) ); Ellipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 ); drawTicks( dc ); drawHands( dc ); _bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 ); Ellipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 ); _wdc = GetDC( _hwnd ); BitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, _wdc ); } myBitmap _bmp; HWND _hwnd; HDC _wdc; SYSTEMTIME _sysTime; float _ang; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); SetTimer( _hwnd, MY_TIMER, 1000, NULL ); _clock.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_MY_CLOCK_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _clock.setNow(); } void wnd::doTimer() { _clock.setNow(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_PAINT: { PAINTSTRUCT ps; HDC dc = BeginPaint( hWnd, &ps ); _inst->doPaint( dc ); EndPaint( hWnd, &ps ); return 0; } case WM_TIMER: _inst->doTimer(); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_CLOCK_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_CLOCK_", ".: Clock -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; clock _clock; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); }
c890
#include <cstdlib> #include <algorithm> #include <iostream> using namespace std; class cupboard { public: cupboard() { for (int i = 0; i < 100; i++) drawers[i] = i; random_shuffle(drawers, drawers + 100); } bool playRandom(); bool playOptimal(); private: int drawers[100]; }; bool cupboard::playRandom() { bool openedDrawers[100] = { 0 }; for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { bool prisonerSuccess = false; for (int i = 0; i < 100 / 2; i++) { int drawerNum = rand() % 100; if (!openedDrawers[drawerNum]) { openedDrawers[drawerNum] = true; break; } if (drawers[drawerNum] == prisonerNum) { prisonerSuccess = true; break; } } if (!prisonerSuccess) return false; } return true; } bool cupboard::playOptimal() { for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { bool prisonerSuccess = false; int checkDrawerNum = prisonerNum; for (int i = 0; i < 100 / 2; i++) { if (drawers[checkDrawerNum] == prisonerNum) { prisonerSuccess = true; break; } else checkDrawerNum = drawers[checkDrawerNum]; } if (!prisonerSuccess) return false; } return true; } double simulate(char strategy) { int numberOfSuccesses = 0; for (int i = 0; i < 10000; i++) { cupboard d; if ((strategy == 'R' && d.playRandom()) || (strategy == 'O' && d.playOptimal())) numberOfSuccesses++; } return numberOfSuccesses * 100.0 / 10000; } int main() { cout << "Random strategy: " << simulate('R') << " %" << endl; cout << "Optimal strategy: " << simulate('O') << " %" << endl; system("PAUSE"); return 0; }
c891
#include <cstdlib> #include <cstdio> int main() { puts(getenv("HOME")); return 0; }
c892
#include <iterator> #include <algorithm> #include <functional> template<typename RandomAccessIterator, typename Order> void mergesort(RandomAccessIterator first, RandomAccessIterator last, Order order) { if (last - first > 1) { RandomAccessIterator middle = first + (last - first) / 2; mergesort(first, middle, order); mergesort(middle, last, order); std::inplace_merge(first, middle, last, order); } } template<typename RandomAccessIterator> void mergesort(RandomAccessIterator first, RandomAccessIterator last) { mergesort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>()); }
c893
struct Point { int x; int y; };
c894
#include <fstream> #include <iostream> #include <iterator> #include <vector> class subleq { public: void load_and_run( std::string file ) { std::ifstream f( file.c_str(), std::ios_base::in ); std::istream_iterator<int> i_v, i_f( f ); std::copy( i_f, i_v, std::back_inserter( memory ) ); f.close(); run(); } private: void run() { int pc = 0, next, a, b, c; char z; do { next = pc + 3; a = memory[pc]; b = memory[pc + 1]; c = memory[pc + 2]; if( a == -1 ) { std::cin >> z; memory[b] = static_cast<int>( z ); } else if( b == -1 ) { std::cout << static_cast<char>( memory[a] ); } else { memory[b] -= memory[a]; if( memory[b] <= 0 ) next = c; } pc = next; } while( pc >= 0 ); } std::vector<int> memory; }; int main( int argc, char* argv[] ) { subleq s; if( argc > 1 ) { s.load_and_run( argv[1] ); } else { std::cout << "usage: subleq <filename>\n"; } return 0; }
c895
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "jsmith", "x", 1001, 1000, {"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash" }, { "jdoe", "x", 1002, 1000, {"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jdoe", "/bin/bash" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
c896
#include <chrono> #include <iostream> #include <format> #include <semaphore> #include <thread> using namespace std::literals; void Worker(std::counting_semaphore<>& semaphore, int id) { semaphore.acquire(); std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); std::this_thread::sleep_for(2s); std::cout << std::format("Thread {} done.\n", id); semaphore.release(); } int main() { const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() ); std::counting_semaphore<> semaphore{numOfThreads / 2}; std::vector<std::jthread> tasks; for (int id = 0; id < numOfThreads; ++id) tasks.emplace_back(Worker, std::ref(semaphore), id); return 0; }
c897
MyClass::method(someParameter); myInstance.method(someParameter); MyPointer->method(someParameter);
c898
#include <iomanip> #include <iostream> #include <sstream> using namespace std; enum CipherMode {ENCRYPT, DECRYPT}; uint32_t randRsl[256]; uint32_t randCnt; uint32_t mm[256]; uint32_t aa = 0, bb = 0, cc = 0; void isaac() { ++cc; bb += cc; for (uint32_t i = 0; i < 256; ++i) { uint32_t x, y; x = mm[i]; switch (i % 4) { case 0: aa = aa ^ (aa << 13); break; case 1: aa = aa ^ (aa >> 6); break; case 2: aa = aa ^ (aa << 2); break; case 3: aa = aa ^ (aa >> 16); break; } aa = mm[(i + 128) % 256] + aa; y = mm[(x >> 2) % 256] + aa + bb; mm[i] = y; bb = mm[(y >> 10) % 256] + x; randRsl[i] = bb; } randCnt = 0; } void mix(uint32_t a[]) { a[0] = a[0] ^ a[1] << 11; a[3] += a[0]; a[1] += a[2]; a[1] = a[1] ^ a[2] >> 2; a[4] += a[1]; a[2] += a[3]; a[2] = a[2] ^ a[3] << 8; a[5] += a[2]; a[3] += a[4]; a[3] = a[3] ^ a[4] >> 16; a[6] += a[3]; a[4] += a[5]; a[4] = a[4] ^ a[5] << 10; a[7] += a[4]; a[5] += a[6]; a[5] = a[5] ^ a[6] >> 4; a[0] += a[5]; a[6] += a[7]; a[6] = a[6] ^ a[7] << 8; a[1] += a[6]; a[7] += a[0]; a[7] = a[7] ^ a[0] >> 9; a[2] += a[7]; a[0] += a[1]; } void randInit(bool flag) { uint32_t a[8]; aa = bb = cc = 0; a[0] = 2654435769UL; for (uint32_t j = 1; j < 8; ++j) a[j] = a[0]; for (uint32_t i = 0; i < 4; ++i) mix(a); for (uint32_t i = 0; i < 256; i += 8) { if (flag) for (uint32_t j = 0; j < 8; ++j) a[j] += randRsl[i + j]; mix(a); for (uint32_t j = 0; j < 8; ++j) mm[i + j] = a[j]; } if (flag) { for (uint32_t i = 0; i < 256; i += 8) { for (uint32_t j = 0; j < 8; ++j) a[j] += mm[i + j]; mix(a); for (uint32_t j = 0; j < 8; ++j) mm[i + j] = a[j]; } } isaac(); randCnt = 0; } void seedIsaac(string seed, bool flag) { uint32_t seedLength = seed.length(); for (uint32_t i = 0; i < 256; i++) mm[i] = 0; for (uint32_t i = 0; i < 256; i++) randRsl[i] = i > seedLength ? 0 : seed[i]; randInit(flag); } uint32_t getRandom32Bit() { uint32_t result = randRsl[randCnt]; ++randCnt; if (randCnt > 255) { isaac(); randCnt = 0; } return result; } char getRandomChar() { return getRandom32Bit() % 95 + 32; } string ascii2hex(string source) { uint32_t sourceLength = source.length(); stringstream ss; for (uint32_t i = 0; i < sourceLength; i++) ss << setfill ('0') << setw(2) << hex << (int) source[i]; return ss.str(); } string vernam(string msg) { uint32_t msgLength = msg.length(); string destination = msg; for (uint32_t i = 0; i < msgLength; i++) destination[i] = getRandomChar() ^ msg[i]; return destination; } char caesar(CipherMode m, char ch, char shift, char modulo, char start) { int n; if (m == DECRYPT) shift = -shift; n = (ch - start) + shift; n %= modulo; if (n < 0) n += modulo; return start + n; } string vigenere(string msg, CipherMode m) { uint32_t msgLength = msg.length(); string destination = msg; for (uint32_t i = 0; i < msgLength; ++i) destination[i] = caesar(m, msg[i], getRandomChar(), 95, ' '); return destination; } int main() { string msg = "a Top Secret secret"; string key = "this is my secret key"; string xorCipherText, modCipherText, xorPlainText, modPlainText; seedIsaac(key, true); xorCipherText = vernam(msg); modCipherText = vigenere(msg, ENCRYPT); seedIsaac(key, true); xorPlainText = vernam(xorCipherText); modPlainText = vigenere(modCipherText, DECRYPT); cout << "Message: " << msg << endl; cout << "Key  : " << key << endl; cout << "XOR  : " << ascii2hex(xorCipherText) << endl; cout << "MOD  : " << ascii2hex(modCipherText) << endl; cout << "XOR dcr: " << xorPlainText << endl; cout << "MOD dcr: " << modPlainText << endl; }
c899
#include <concepts> #include <iostream> void PrintMatrix(std::predicate<int, int, int> auto f, int size) { for(int y = 0; y < size; y++) { for(int x = 0; x < size; x++) { std::cout << " " << f(x, y, size); } std::cout << "\n"; } std::cout << "\n"; } int main() { auto mosaic = [](int x, int y, [[maybe_unused]]int size) { return (x + y) % 2 == 0; }; PrintMatrix(mosaic, 8); PrintMatrix(mosaic, 9); }
c900
#include <string> #include <iostream> #include <algorithm> #include <boost/lambda/lambda.hpp> #include <boost/lambda/casts.hpp> #include <ctime> #include <cstdlib> using namespace boost::lambda ; struct MyRandomizer { char operator( )( ) { return static_cast<char>( rand( ) % 256 ) ; } } ; std::string deleteControls ( std::string startstring ) { std::string noControls( " " ) ; std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noControls.begin( ) , ll_static_cast<int>( _1 ) < 32 && ll_static_cast<int>( _1 ) == 127 ) ; return noControls ; } std::string deleteExtended( std::string startstring ) { std::string noExtended ( " " ) ; std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noExtended.begin( ) , ll_static_cast<int>( _1 ) > 127 || ll_static_cast<int>( _1 ) < 32 ) ; return noExtended ; } int main( ) { std::string my_extended_string ; for ( int i = 0 ; i < 40 ; i++ ) my_extended_string.append( " " ) ; srand( time( 0 ) ) ; std::generate_n( my_extended_string.begin( ) , 40 , MyRandomizer( ) ) ; std::string no_controls( deleteControls( my_extended_string ) ) ; std::string no_extended ( deleteExtended( my_extended_string ) ) ; std::cout << "string with all characters: " << my_extended_string << std::endl ; std::cout << "string without control characters: " << no_controls << std::endl ; std::cout << "string without extended characters: " << no_extended << std::endl ; return 0 ; }
c901
#include <algorithm> #include <iomanip> #include <iostream> #include <fstream> #include <string> #include <vector> class Vector { private: double px, py, pz; public: Vector() : px(0.0), py(0.0), pz(0.0) { } Vector(double x, double y, double z) : px(x), py(y), pz(z) { } double mod() const { return sqrt(px*px + py * py + pz * pz); } Vector operator+(const Vector& rhs) const { return Vector(px + rhs.px, py + rhs.py, pz + rhs.pz); } Vector operator-(const Vector& rhs) const { return Vector(px - rhs.px, py - rhs.py, pz - rhs.pz); } Vector operator*(double s) const { return Vector(px*s, py*s, pz*s); } bool operator==(const Vector& rhs) const { return px == rhs.px && py == rhs.py && pz == rhs.pz; } friend std::istream& operator>>(std::istream&, Vector&); friend std::ostream& operator<<(std::ostream&, Vector&); }; std::istream& operator>>(std::istream& in, Vector& v) { return in >> v.px >> v.py >> v.pz; } std::ostream& operator<<(std::ostream& out, Vector& v) { auto precision = out.precision(); auto width = out.width(); out << std::fixed << std::setw(width) << std::setprecision(precision) << v.px << " "; out << std::fixed << std::setw(width) << std::setprecision(precision) << v.py << " "; out << std::fixed << std::setw(width) << std::setprecision(precision) << v.pz; return out; } const Vector ORIGIN{ 0.0, 0.0, 0.0 }; class NBody { private: double gc; int bodies; int timeSteps; std::vector<double> masses; std::vector<Vector> positions; std::vector<Vector> velocities; std::vector<Vector> accelerations; void resolveCollisions() { for (int i = 0; i < bodies; ++i) { for (int j = i + 1; j < bodies; ++j) { if (positions[i] == positions[j]) { std::swap(velocities[i], velocities[j]); } } } } void computeAccelerations() { for (int i = 0; i < bodies; ++i) { accelerations[i] = ORIGIN; for (int j = 0; j < bodies; ++j) { if (i != j) { double temp = gc * masses[j] / pow((positions[i] - positions[j]).mod(), 3); accelerations[i] = accelerations[i] + (positions[j] - positions[i]) * temp; } } } } void computeVelocities() { for (int i = 0; i < bodies; ++i) { velocities[i] = velocities[i] + accelerations[i]; } } void computePositions() { for (int i = 0; i < bodies; ++i) { positions[i] = positions[i] + velocities[i] + accelerations[i] * 0.5; } } public: NBody(std::string& fileName) { using namespace std; ifstream ifs(fileName); if (!ifs.is_open()) { throw runtime_error("Could not open file."); } ifs >> gc >> bodies >> timeSteps; masses.resize(bodies); positions.resize(bodies); fill(positions.begin(), positions.end(), ORIGIN); velocities.resize(bodies); fill(velocities.begin(), velocities.end(), ORIGIN); accelerations.resize(bodies); fill(accelerations.begin(), accelerations.end(), ORIGIN); for (int i = 0; i < bodies; ++i) { ifs >> masses[i] >> positions[i] >> velocities[i]; } cout << "Contents of " << fileName << '\n'; cout << gc << ' ' << bodies << ' ' << timeSteps << '\n'; for (int i = 0; i < bodies; ++i) { cout << masses[i] << '\n'; cout << positions[i] << '\n'; cout << velocities[i] << '\n'; } cout << "\nBody  : x y z | vx vy vz\n"; } int getTimeSteps() { return timeSteps; } void simulate() { computeAccelerations(); computePositions(); computeVelocities(); resolveCollisions(); } friend std::ostream& operator<<(std::ostream&, NBody&); }; std::ostream& operator<<(std::ostream& out, NBody& nb) { for (int i = 0; i < nb.bodies; ++i) { out << "Body " << i + 1 << " : "; out << std::setprecision(6) << std::setw(9) << nb.positions[i]; out << " | "; out << std::setprecision(6) << std::setw(9) << nb.velocities[i]; out << '\n'; } return out; } int main() { std::string fileName = "nbody.txt"; NBody nb(fileName); for (int i = 0; i < nb.getTimeSteps(); ++i) { std::cout << "\nCycle " << i + 1 << '\n'; nb.simulate(); std::cout << nb; } return 0; }
c904
#include <algorithm> #include <iostream> #include <vector> class SubMatrix { const std::vector<std::vector<double>> *source; std::vector<double> replaceColumn; const SubMatrix *prev; size_t sz; int colIndex = -1; public: SubMatrix(const std::vector<std::vector<double>> &src, const std::vector<double> &rc) : source(&src), replaceColumn(rc), prev(nullptr), colIndex(-1) { sz = replaceColumn.size(); } SubMatrix(const SubMatrix &p) : source(nullptr), prev(&p), colIndex(-1) { sz = p.size() - 1; } SubMatrix(const SubMatrix &p, int deletedColumnIndex) : source(nullptr), prev(&p), colIndex(deletedColumnIndex) { sz = p.size() - 1; } int columnIndex() const { return colIndex; } void columnIndex(int index) { colIndex = index; } size_t size() const { return sz; } double index(int row, int col) const { if (source != nullptr) { if (col == colIndex) { return replaceColumn[row]; } else { return (*source)[row][col]; } } else { if (col < colIndex) { return prev->index(row + 1, col); } else { return prev->index(row + 1, col + 1); } } } double det() const { if (sz == 1) { return index(0, 0); } if (sz == 2) { return index(0, 0) * index(1, 1) - index(0, 1) * index(1, 0); } SubMatrix m(*this); double det = 0.0; int sign = 1; for (size_t c = 0; c < sz; ++c) { m.columnIndex(c); double d = m.det(); det += index(0, c) * d * sign; sign = -sign; } return det; } }; std::vector<double> solve(SubMatrix &matrix) { double det = matrix.det(); if (det == 0.0) { throw std::runtime_error("The determinant is zero."); } std::vector<double> answer(matrix.size()); for (int i = 0; i < matrix.size(); ++i) { matrix.columnIndex(i); answer[i] = matrix.det() / det; } return answer; } std::vector<double> solveCramer(const std::vector<std::vector<double>> &equations) { int size = equations.size(); if (std::any_of( equations.cbegin(), equations.cend(), [size](const std::vector<double> &a) { return a.size() != size + 1; } )) { throw std::runtime_error("Each equation must have the expected size."); } std::vector<std::vector<double>> matrix(size); std::vector<double> column(size); for (int r = 0; r < size; ++r) { column[r] = equations[r][size]; matrix[r].resize(size); for (int c = 0; c < size; ++c) { matrix[r][c] = equations[r][c]; } } SubMatrix sm(matrix, column); return solve(sm); } 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++; } while (it != end) { os << ", " << *it++; } return os << ']'; } int main() { std::vector<std::vector<double>> equations = { { 2, -1, 5, 1, -3}, { 3, 2, 2, -6, -32}, { 1, 3, 3, -1, -47}, { 5, -2, -3, 3, 49}, }; auto solution = solveCramer(equations); std::cout << solution << '\n'; return 0; }
c905
#include <ctime> #include <string> #include <iostream> #include <algorithm> class cycle{ public: template <class T> void cy( T* a, int len ) { int i, j; show( "original: ", a, len ); std::srand( unsigned( time( 0 ) ) ); for( int i = len - 1; i > 0; i-- ) { do { j = std::rand() % i; } while( j >= i ); std::swap( a[i], a[j] ); } show( " cycled: ", a, len ); std::cout << "\n"; } private: template <class T> void show( std::string s, T* a, int len ) { std::cout << s; for( int i = 0; i < len; i++ ) { std::cout << a[i] << " "; } std::cout << "\n"; } }; int main( int argc, char* argv[] ) { std::string d0[] = { "" }, d1[] = { "10" }, d2[] = { "10", "20" }; int d3[] = { 10, 20, 30 }, d4[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 }; cycle c; c.cy( d0, sizeof( d0 ) / sizeof( d0[0] ) ); c.cy( d1, sizeof( d1 ) / sizeof( d1[0] ) ); c.cy( d2, sizeof( d2 ) / sizeof( d2[0] ) ); c.cy( d3, sizeof( d3 ) / sizeof( d3[0] ) ); c.cy( d4, sizeof( d4 ) / sizeof( d4[0] ) ); return 0; }
c906
#include <iostream> #include <ostream> template<typename T> T f(const T& x) { return (T) pow(x, 100) + x + 1; } class ModularInteger { private: int value; int modulus; void validateOp(const ModularInteger& rhs) const { if (modulus != rhs.modulus) { throw std::runtime_error("Left-hand modulus does not match right-hand modulus."); } } public: ModularInteger(int v, int m) { modulus = m; value = v % m; } int getValue() const { return value; } int getModulus() const { return modulus; } ModularInteger operator+(const ModularInteger& rhs) const { validateOp(rhs); return ModularInteger(value + rhs.value, modulus); } ModularInteger operator+(int rhs) const { return ModularInteger(value + rhs, modulus); } ModularInteger operator*(const ModularInteger& rhs) const { validateOp(rhs); return ModularInteger(value * rhs.value, modulus); } friend std::ostream& operator<<(std::ostream&, const ModularInteger&); }; std::ostream& operator<<(std::ostream& os, const ModularInteger& self) { return os << "ModularInteger(" << self.value << ", " << self.modulus << ")"; } ModularInteger pow(const ModularInteger& lhs, int pow) { if (pow < 0) { throw std::runtime_error("Power must not be negative."); } ModularInteger base(1, lhs.getModulus()); while (pow-- > 0) { base = base * lhs; } return base; } int main() { using namespace std; ModularInteger input(10, 13); auto output = f(input); cout << "f(" << input << ") = " << output << endl; return 0; }
c907
#include <iostream> #include <string> #include <boost/date_time/gregorian/gregorian.hpp> bool is_palindrome(const std::string& str) { for (size_t i = 0, j = str.size(); i + 1 < j; ++i, --j) { if (str[i] != str[j - 1]) return false; } return true; } int main() { using boost::gregorian::date; using boost::gregorian::day_clock; using boost::gregorian::date_duration; date today(day_clock::local_day()); date_duration day(1); int count = 15; std::cout << "Next " << count << " palindrome dates:\n"; for (; count > 0; today += day) { if (is_palindrome(to_iso_string(today))) { std::cout << to_iso_extended_string(today) << '\n'; --count; } } return 0; }
c908
#include <iostream> class Acc { public: Acc(int init) : _type(intType) , _intVal(init) {} Acc(float init) : _type(floatType) , _floatVal(init) {} int operator()(int x) { if( _type == intType ) { _intVal += x; return _intVal; } else { _floatVal += x; return static_cast<int>(_floatVal); } } float operator()(float x) { if( _type == intType ) { _floatVal = _intVal + x; _type = floatType; return _floatVal; } else { _floatVal += x; return _floatVal; } } private: enum {floatType, intType} _type; float _floatVal; int _intVal; }; int main() { Acc a(1); a(5); Acc(3); std::cout << a(2.3f); return 0; }
c909
#include <string> #include <iostream> #include <cstdlib> #include <math.h> #include <chrono> #include <iomanip> using namespace std; const int maxBase = 16; int base, bmo, tc; const string chars = "0123456789ABCDEF"; unsigned long long full; string toStr(const unsigned long long ull) { unsigned long long u = ull; string res = ""; while (u > 0) { lldiv_t result1 = lldiv(u, base); res = chars[(int)result1.rem] + res; u = (unsigned long long)result1.quot; } return res; } unsigned long long to10(string s) { unsigned long long res = 0; for (char i : s) res = res * base + chars.find(i); return res; } bool allIn(const unsigned long long ull) { unsigned long long u, found; u = ull; found = 0; while (u > 0) { lldiv_t result1 = lldiv(u, base); found |= (unsigned long long)1 << result1.rem; u = result1.quot; } return found == full; } string fixup(int n) { string res = chars.substr(0, base); if (n > 0) res = res.insert(n, chars.substr(n, 1)); return "10" + res.substr(2); } void doOne() { bmo = base - 1; tc = 0; unsigned long long sq, rt, dn, d; int id = 0, dr = (base & 1) == 1 ? base >> 1 : 0, inc = 1, sdr[maxBase] = { 0 }; full = ((unsigned long long)1 << base) - 1; int rc = 0; for (int i = 0; i < bmo; i++) { sdr[i] = (i * i) % bmo; if (sdr[i] == dr) rc++; if (sdr[i] == 0) sdr[i] += bmo; } if (dr > 0) { id = base; for (int i = 1; i <= dr; i++) if (sdr[i] >= dr) if (id > sdr[i]) id = sdr[i]; id -= dr; } sq = to10(fixup(id)); rt = (unsigned long long)sqrt(sq) + 1; sq = rt * rt; dn = (rt << 1) + 1; d = 1; if (base > 3 && rc > 0) { while (sq % bmo != dr) { rt += 1; sq += dn; dn += 2; } inc = bmo / rc; if (inc > 1) { dn += rt * (inc - 2) - 1; d = inc * inc; } dn += dn + d; } d <<= 1; do { if (allIn(sq)) break; sq += dn; dn += d; tc++; } while (true); rt += tc * inc; cout << setw(4) << base << setw(3) << inc << " " << setw(2) << (id > 0 ? chars.substr(id, 1) : " ") << setw(10) << toStr(rt) << " " << setw(20) << left << toStr(sq) << right << setw(12) << tc << endl; } int main() { cout << "base inc id root sqr test count" << endl; auto st = chrono::system_clock::now(); for (base = 2; base <= maxBase; base++) doOne(); chrono::duration<double> et = chrono::system_clock::now() - st; cout << "\nComputation time was " << et.count() * 1000 << " milliseconds" << endl; return 0; }
c910
#include <algorithm> #include <iostream> #include <numeric> #include <vector> std::vector<int> divisors(int n) { std::vector<int> divs = { 1 }; std::vector<int> divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.push_back(i); if (i != j) { divs2.push_back(j); } } } std::copy(divs.cbegin(), divs.cend(), std::back_inserter(divs2)); return divs2; } bool abundant(int n, const std::vector<int> &divs) { return std::accumulate(divs.cbegin(), divs.cend(), 0) > n; } template<typename IT> bool semiperfect(int n, const IT &it, const IT &end) { if (it != end) { auto h = *it; auto t = std::next(it); if (n < h) { return semiperfect(n, t, end); } else { return n == h || semiperfect(n - h, t, end) || semiperfect(n, t, end); } } else { return false; } } template<typename C> bool semiperfect(int n, const C &c) { return semiperfect(n, std::cbegin(c), std::cend(c)); } std::vector<bool> sieve(int limit) { std::vector<bool> w(limit); for (int i = 2; i < limit; i += 2) { if (w[i]) continue; auto divs = divisors(i); if (!abundant(i, divs)) { w[i] = true; } else if (semiperfect(i, divs)) { for (int j = i; j < limit; j += i) { w[j] = true; } } } return w; } int main() { auto w = sieve(17000); int count = 0; int max = 25; std::cout << "The first 25 weird numbers:"; for (int n = 2; count < max; n += 2) { if (!w[n]) { std::cout << n << ' '; count++; } } std::cout << '\n'; return 0; }
c911
#include <iostream> using namespace std; class mRND { public: void seed( unsigned int s ) { _seed = s; } protected: mRND() : _seed( 0 ), _a( 0 ), _c( 0 ), _m( 2147483648 ) {} int rnd() { return( _seed = ( _a * _seed + _c ) % _m ); } int _a, _c; unsigned int _m, _seed; }; class MS_RND : public mRND { public: MS_RND() { _a = 214013; _c = 2531011; } int rnd() { return mRND::rnd() >> 16; } }; class BSD_RND : public mRND { public: BSD_RND() { _a = 1103515245; _c = 12345; } int rnd() { return mRND::rnd(); } }; int main( int argc, char* argv[] ) { BSD_RND bsd_rnd; MS_RND ms_rnd; cout << "MS RAND:" << endl << "========" << endl; for( int x = 0; x < 10; x++ ) cout << ms_rnd.rnd() << endl; cout << endl << "BSD RAND:" << endl << "=========" << endl; for( int x = 0; x < 10; x++ ) cout << bsd_rnd.rnd() << endl; cout << endl << endl; system( "pause" ); return 0; }
c912
#include <iostream> #include <iomanip> int main() { std::cout << std::setfill('0') << std::setw(9) << std::fixed << std::setprecision(3) << 7.125 << std::endl; return 0; }
c913
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <sstream> #include <vector> template <typename T> size_t indexOf(const std::vector<T> &v, const T &k) { auto it = std::find(v.cbegin(), v.cend(), k); if (it != v.cend()) { return it - v.cbegin(); } return -1; } int main() { std::vector<size_t> cubes; auto dump = [&cubes](const std::string &title, const std::map<int, size_t> &items) { std::cout << title; for (auto &item : items) { std::cout << "\n" << std::setw(4) << item.first << " " << std::setw(10) << item.second; for (auto x : cubes) { auto y = item.second - x; if (y < x) { break; } if (std::count(cubes.begin(), cubes.end(), y)) { std::cout << " = " << std::setw(4) << indexOf(cubes, y) << "^3 + " << std::setw(3) << indexOf(cubes, x) << "^3"; } } } }; std::vector<size_t> sums; for (size_t i = 0; i < 1190; i++) { auto cube = i * i * i; cubes.push_back(cube); for (auto j : cubes) { sums.push_back(cube + j); } } std::sort(sums.begin(), sums.end()); auto nm1 = sums[0]; auto n = sums[1]; int idx = 0; std::map<int, size_t> task; std::map<int, size_t> trips; auto it = sums.cbegin(); auto end = sums.cend(); it++; it++; while (it != end) { auto np1 = *it; if (nm1 == np1) { trips.emplace(idx, n); } if (nm1 != n && n == np1) { if (++idx <= 25 || idx >= 2000 == idx <= 2006) { task.emplace(idx, n); } } nm1 = n; n = np1; it++; } dump("First 25 Taxicab Numbers, the 2000th, plus the next half-dozen:", task); std::stringstream ss; ss << "\n\nFound " << trips.size() << " triple Taxicabs under 2007:"; dump(ss.str(), trips); return 0; }
c914
#include <iostream> #include <iomanip> using namespace std; class converter { public: converter() : KTC( 273.15f ), KTDel( 3.0f / 2.0f ), KTF( 9.0f / 5.0f ), KTNew( 33.0f / 100.0f ), KTRank( 9.0f / 5.0f ), KTRe( 4.0f / 5.0f ), KTRom( 21.0f / 40.0f ) {} void convert( float kelvin ) { float cel = kelvin - KTC, del = ( 373.15f - kelvin ) * KTDel, fah = kelvin * KTF - 459.67f, net = cel * KTNew, rnk = kelvin * KTRank, rea = cel * KTRe, rom = cel * KTRom + 7.5f; cout << endl << left << "TEMPERATURES:" << endl << "===============" << endl << setw( 13 ) << "CELSIUS:" << cel << endl << setw( 13 ) << "DELISLE:" << del << endl << setw( 13 ) << "FAHRENHEIT:" << fah << endl << setw( 13 ) << "KELVIN:" << kelvin << endl << setw( 13 ) << "NEWTON:" << net << endl << setw( 13 ) << "RANKINE:" << rnk << endl << setw( 13 ) << "REAUMUR:" << rea << endl << setw( 13 ) << "ROMER:" << rom << endl << endl << endl; } private: const float KTRank, KTC, KTF, KTRe, KTDel, KTNew, KTRom; }; int main( int argc, char* argv[] ) { converter con; float k; while( true ) { cout << "Enter the temperature in Kelvin to convert: "; cin >> k; con.convert( k ); system( "pause" ); system( "cls" ); } return 0; }
c916
#include <iomanip> #include <iostream> using namespace std; string replaceFirst(string &s, const string &target, const string &replace) { auto pos = s.find(target); if (pos == string::npos) return s; return s.replace(pos, target.length(), replace); } int main() { string x = "hello world"; x = ""; x = "ab\0"; cout << x << '\n'; cout << x.length() << '\n'; if (x == "hello") { cout << "equal\n"; } else { cout << "not equal\n"; } if (x < "bc") { cout << "x is lexigraphically less than 'bc'\n"; } auto y = x; cout << boolalpha << (x == y) << '\n'; cout << boolalpha << (&x == &y) << '\n'; string empty = ""; if (empty.empty()) { cout << "String is empty\n"; } x = "helloworld"; x += (char)83; cout << x << '\n'; auto slice = x.substr(5, 5); cout << slice << '\n'; auto greeting = replaceFirst(x, "worldS", ""); cout << greeting << '\n'; auto join = greeting + ' ' + slice; cout << join << '\n'; return 0; }
c917
#include <string> #include <iostream> using namespace std; string Suffix(int num) { switch (num % 10) { case 1 : if(num % 100 != 11) return "st"; break; case 2 : if(num % 100 != 12) return "nd"; break; case 3 : if(num % 100 != 13) return "rd"; } return "th"; } int main() { cout << "Set [0,25]:" << endl; for (int i = 0; i < 26; i++) cout << i << Suffix(i) << " "; cout << endl; cout << "Set [250,265]:" << endl; for (int i = 250; i < 266; i++) cout << i << Suffix(i) << " "; cout << endl; cout << "Set [1000,1025]:" << endl; for (int i = 1000; i < 1026; i++) cout << i << Suffix(i) << " "; cout << endl; return 0; }
c918
#include <algorithm> #include <cstddef> #include <cassert> template<typename MatrixType> struct matrix_traits { typedef typename MatrixType::index_type index_type; typedef typename MatrixType::value_type value_type; static index_type min_row(MatrixType const& A) { return A.min_row(); } static index_type max_row(MatrixType const& A) { return A.max_row(); } static index_type min_column(MatrixType const& A) { return A.min_column(); } static index_type max_column(MatrixType const& A) { return A.max_column(); } static value_type& element(MatrixType& A, index_type i, index_type k) { return A(i,k); } static value_type element(MatrixType const& A, index_type i, index_type k) { return A(i,k); } }; template<typename T, std::size_t rows, std::size_t columns> struct matrix_traits<T[rows][columns]> { typedef std::size_t index_type; typedef T value_type; static index_type min_row(T const (&)[rows][columns]) { return 0; } static index_type max_row(T const (&)[rows][columns]) { return rows-1; } static index_type min_column(T const (&)[rows][columns]) { return 0; } static index_type max_column(T const (&)[rows][columns]) { return columns-1; } static value_type& element(T (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } static value_type element(T const (&A)[rows][columns], index_type i, index_type k) { return A[i][k]; } }; template<typename MatrixType> void swap_rows(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) std::swap(mt.element(A, i, col), mt.element(A, k, col)); } template<typename MatrixType> void divide_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(v != 0); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) /= v; } template<typename MatrixType> void add_multiple_row(MatrixType& A, typename matrix_traits<MatrixType>::index_type i, typename matrix_traits<MatrixType>::index_type k, typename matrix_traits<MatrixType>::value_type v) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; assert(mt.min_row(A) <= i); assert(i <= mt.max_row(A)); assert(mt.min_row(A) <= k); assert(k <= mt.max_row(A)); for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col) mt.element(A, i, col) += v * mt.element(A, k, col); } template<typename MatrixType> void to_reduced_row_echelon_form(MatrixType& A) { matrix_traits<MatrixType> mt; typedef typename matrix_traits<MatrixType>::index_type index_type; index_type lead = mt.min_row(A); for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) { if (lead > mt.max_column(A)) return; index_type i = row; while (mt.element(A, i, lead) == 0) { ++i; if (i > mt.max_row(A)) { i = row; ++lead; if (lead > mt.max_column(A)) return; } } swap_rows(A, i, row); divide_row(A, row, mt.element(A, row, lead)); for (i = mt.min_row(A); i <= mt.max_row(A); ++i) { if (i != row) add_multiple_row(A, i, row, -mt.element(A, i, lead)); } } } #include <iostream> int main() { double M[3][4] = { { 1, 2, -1, -4 }, { 2, 3, -1, -11 }, { -2, 0, -3, 22 } }; to_reduced_row_echelon_form(M); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) std::cout << M[i][j] << '\t'; std::cout << "\n"; } return EXIT_SUCCESS; }
c919
#include <algorithm> #include <chrono> #include <iostream> #include <vector> int ulam(int n) { std::vector<int> ulams{1, 2}; std::vector<int> sieve{1, 1}; for (int u = 2; ulams.size() < n; ) { sieve.resize(u + ulams[ulams.size() - 2], 0); for (int i = 0; i < ulams.size() - 1; ++i) ++sieve[u + ulams[i] - 1]; auto it = std::find(sieve.begin() + u, sieve.end(), 1); if (it == sieve.end()) return -1; u = (it - sieve.begin()) + 1; ulams.push_back(u); } return ulams[n - 1]; } int main() { auto start = std::chrono::high_resolution_clock::now(); for (int n = 1; n <= 100000; n *= 10) std::cout << "Ulam(" << n << ") = " << ulam(n) << '\n'; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "Elapsed time: " << duration.count() << " seconds\n"; }
c920
#include <iostream> #include <string> #include <map> #include <algorithm> using namespace std; class StraddlingCheckerboard { map<char, string> table; char first[10], second[10], third[10]; int rowU, rowV; public: StraddlingCheckerboard(const string &alphabet, int u, int v) { rowU = min(u, v); rowV = max(u, v); for(int i = 0, j = 0; i < 10; ++i) { if(i != u && i != v) { first[i] = alphabet[j]; table[alphabet[j]] = '0' + i; ++j; } second[i] = alphabet[i+8]; table[alphabet[i+8]] = '0' + rowU; table[alphabet[i+8]] += '0' + i; third[i] = alphabet[i+18]; table[alphabet[i+18]] = '0' + rowV; table[alphabet[i+18]] += '0' + i; } } string encode(const string &plain) { string out; for(int i = 0; i < plain.size(); ++i) { char c = plain[i]; if(c >= 'a' && c <= 'z') c += 'A' - 'a'; if(c >= 'A' && c <= 'Z') out += table[c]; else if(c >= '0' && c <= '9') { out += table['/']; out += c; } } return out; } string decode(const string &cipher) { string out; int state = 0; for(int i = 0; i < cipher.size(); ++i) { int n = cipher[i] - '0'; char next = 0; if(state == 1) next = second[n]; else if(state == 2) next = third[n]; else if(state == 3) next = cipher[i]; else if(n == rowU) state = 1; else if(n == rowV) state = 2; else next = first[n]; if(next == '/') state = 3; else if(next != 0) { state = 0; out += next; } } return out; } };
c921
#include <functional> #include <cmath> #include <iostream> template <class Fun1, class Fun2> class compose_functor : public std::unary_function<typename Fun2::argument_type, typename Fun1::result_type> { protected: Fun1 f; Fun2 g; public: compose_functor(const Fun1& _f, const Fun2& _g) : f(_f), g(_g) { } typename Fun1::result_type operator()(const typename Fun2::argument_type& x) const { return f(g(x)); } }; template <class Fun1, class Fun2> inline compose_functor<Fun1, Fun2> compose(const Fun1& f, const Fun2& g) { return compose_functor<Fun1,Fun2>(f, g); } int main() { std::cout << compose(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl; return 0; }
c922
#include<cstdio> int main(){char n[]=R"(#include<cstdio> int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);}
c923
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; integer denominator; }; integer mod(const integer& x, const integer& y) { return ((x % y) + y) % y; } size_t count_digits(const integer& i) { std::ostringstream os; os << i; return os.str().length(); } std::string to_string(const integer& i) { const int max_digits = 20; std::ostringstream os; os << i; std::string s = os.str(); if (s.length() > max_digits) { s = s.substr(0, max_digits/2) + "..." + s.substr(s.length()-max_digits/2); } return s; } std::ostream& operator<<(std::ostream& out, const fraction& f) { return out << to_string(f.numerator) << '/' << to_string(f.denominator); } void egyptian(const fraction& f, std::vector<fraction>& result) { result.clear(); integer x = f.numerator, y = f.denominator; while (x > 0) { integer z = (y + x - 1)/x; result.emplace_back(1, z); x = mod(-y, x); y = y * z; } } void print_egyptian(const std::vector<fraction>& result) { if (result.empty()) return; auto i = result.begin(); std::cout << *i++; for (; i != result.end(); ++i) std::cout << " + " << *i; std::cout << '\n'; } void print_egyptian(const fraction& f) { std::cout << "Egyptian fraction for " << f << ": "; integer x = f.numerator, y = f.denominator; if (x > y) { std::cout << "[" << x/y << "] "; x = x % y; } std::vector<fraction> result; egyptian(fraction(x, y), result); print_egyptian(result); std::cout << '\n'; } void show_max_terms_and_max_denominator(const integer& limit) { size_t max_terms = 0; std::optional<fraction> max_terms_fraction, max_denominator_fraction; std::vector<fraction> max_terms_result; integer max_denominator = 0; std::vector<fraction> max_denominator_result; std::vector<fraction> result; for (integer b = 2; b < limit; ++b) { for (integer a = 1; a < b; ++a) { fraction f(a, b); egyptian(f, result); if (result.size() > max_terms) { max_terms = result.size(); max_terms_result = result; max_terms_fraction = f; } const integer& denominator = result.back().denominator; if (denominator > max_denominator) { max_denominator = denominator; max_denominator_result = result; max_denominator_fraction = f; } } } std::cout << "Proper fractions with most terms and largest denominator, limit = " << limit << ":\n\n"; std::cout << "Most terms (" << max_terms << "): " << max_terms_fraction.value() << " = "; print_egyptian(max_terms_result); std::cout << "\nLargest denominator (" << count_digits(max_denominator_result.back().denominator) << " digits): " << max_denominator_fraction.value() << " = "; print_egyptian(max_denominator_result); } int main() { print_egyptian(fraction(43, 48)); print_egyptian(fraction(5, 121)); print_egyptian(fraction(2014, 59)); show_max_terms_and_max_denominator(100); show_max_terms_and_max_denominator(1000); return 0; }
c924
#include "boost/filesystem.hpp" #include <string> #include <iostream> void testfile(std::string name) { boost::filesystem::path file(name); if (exists(file)) { if (is_directory(file)) std::cout << name << " is a directory.\n"; else std::cout << name << " is a non-directory file.\n"; } else std::cout << name << " does not exist.\n"; } int main() { testfile("input.txt"); testfile("docs"); testfile("/input.txt"); testfile("/docs"); }
c925
#include <iostream> #include <queue> #include <map> #include <climits> #include <iterator> #include <algorithm> const int UniqueSymbols = 1 << CHAR_BIT; const char* SampleString = "this is an example for huffman encoding"; typedef std::vector<bool> HuffCode; typedef std::map<char, HuffCode> HuffCodeMap; class INode { public: const int f; virtual ~INode() {} protected: INode(int f) : f(f) {} }; class InternalNode : public INode { public: INode *const left; INode *const right; InternalNode(INode* c0, INode* c1) : INode(c0->f + c1->f), left(c0), right(c1) {} ~InternalNode() { delete left; delete right; } }; class LeafNode : public INode { public: const char c; LeafNode(int f, char c) : INode(f), c(c) {} }; struct NodeCmp { bool operator()(const INode* lhs, const INode* rhs) const { return lhs->f > rhs->f; } }; INode* BuildTree(const int (&frequencies)[UniqueSymbols]) { std::priority_queue<INode*, std::vector<INode*>, NodeCmp> trees; for (int i = 0; i < UniqueSymbols; ++i) { if(frequencies[i] != 0) trees.push(new LeafNode(frequencies[i], (char)i)); } while (trees.size() > 1) { INode* childR = trees.top(); trees.pop(); INode* childL = trees.top(); trees.pop(); INode* parent = new InternalNode(childR, childL); trees.push(parent); } return trees.top(); } void GenerateCodes(const INode* node, const HuffCode& prefix, HuffCodeMap& outCodes) { if (const LeafNode* lf = dynamic_cast<const LeafNode*>(node)) { outCodes[lf->c] = prefix; } else if (const InternalNode* in = dynamic_cast<const InternalNode*>(node)) { HuffCode leftPrefix = prefix; leftPrefix.push_back(false); GenerateCodes(in->left, leftPrefix, outCodes); HuffCode rightPrefix = prefix; rightPrefix.push_back(true); GenerateCodes(in->right, rightPrefix, outCodes); } } int main() { int frequencies[UniqueSymbols] = {0}; const char* ptr = SampleString; while (*ptr != '\0') ++frequencies[*ptr++]; INode* root = BuildTree(frequencies); HuffCodeMap codes; GenerateCodes(root, HuffCode(), codes); delete root; for (HuffCodeMap::const_iterator it = codes.begin(); it != codes.end(); ++it) { std::cout << it->first << " "; std::copy(it->second.begin(), it->second.end(), std::ostream_iterator<bool>(std::cout)); std::cout << std::endl; } return 0; }
c926
#include <string> #include <chrono> #include <cmath> #include <locale> using namespace std; using namespace chrono; unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * pow(10, modf(++res * lf, &ip))) == l) n--; return res; } unsigned int gi(int ld, int n) { string Ls = to_string(ld); unsigned int res = 0, count = 0; unsigned long long f = 1; for (int i = 1; i <= 18 - Ls.length(); i++) f *= 10; const unsigned long long ten18 = 1e18; unsigned long long probe = 1; do { probe <<= 1; res++; if (probe >= ten18) { do { if (probe >= ten18) probe /= 10; if (probe / f == ld) if (++count >= n) { count--; break; } probe <<= 1; res++; } while (1); } string ps = to_string(probe); if (ps.substr(0, min(Ls.length(), ps.length())) == Ls) if (++count >= n) break; } while (1); return res; } unsigned int pa(int ld, int n) { const double L_float64 = pow(2, 64); const unsigned long long Log10_2_64 = (unsigned long long)(L_float64 * log(2) / log(10)); double Log10Num; unsigned long long LmtUpper, LmtLower, Frac64; int res = 0, dgts = 1, cnt; for (int i = ld; i >= 10; i /= 10) dgts *= 10; Log10Num = log((ld + 1.0) / dgts) / log(10); if (Log10Num >= 0.5) { LmtUpper = (ld + 1.0) / dgts < 10.0 ? (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2) : 0; Log10Num = log((double)ld / dgts) / log(10); LmtLower = (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2); } else { LmtUpper = (unsigned long long)(Log10Num * L_float64); LmtLower = (unsigned long long)(log((double)ld / dgts) / log(10) * L_float64); } cnt = 0; Frac64 = 0; if (LmtUpper != 0) { do { res++; Frac64 += Log10_2_64; if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper)) if (++cnt >= n) break; } while (1); } else { do { res++; Frac64 += Log10_2_64; if (Frac64 >= LmtLower) if (++cnt >= n) break; } while (1); }; return res; } int params[] = { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 }; void doOne(string name, unsigned int (*func)(int a, int b)) { printf("%s version:\n", name.c_str()); auto start = steady_clock::now(); for (int i = 0; i < size(params); i += 2) printf("p(%3d, %6d) = %'11u\n", params[i], params[i + 1], func(params[i], params[i + 1])); printf("Took %f seconds\n\n", duration<double>(steady_clock::now() - start).count()); } int main() { setlocale(LC_ALL, ""); doOne("java simple", js); doOne("go integer", gi); doOne("pascal alternative", pa); }
c927
#include <iostream> #include <cstdlib> if (object == 0) { std::cout << "object is null"; }
c928
#include <iostream> #include "xtensor/xarray.hpp" #include "xtensor/xio.hpp" #include "xtensor-io/ximage.hpp" xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim) { xt::xarray<int>::shape_type shape = { x_dim, y_dim }; xt::xarray<int> grid(shape); grid(x_dim/2, y_dim/2) = 64000; return grid; } int print_grid(xt::xarray<int>& grid) { xt::dump_image("grid.jpg", grid); return 0; } bool iterate_grid(xt::xarray<int>& grid, const unsigned long& x_dim, const unsigned long& y_dim) { bool changed = false; for (unsigned long i=0; i < x_dim; ++i) { for (unsigned long j=0; j < y_dim; ++j) { if ( grid(i, j) >= 4 ) { grid(i, j) -= 4; changed = true; try { grid.at(i-1, j) += 1; grid.at(i+1, j) += 1; grid.at(i, j-1) += 1; grid.at(i, j+1) += 1; } catch (const std::out_of_range& oor) { } } } } return changed; } int main(int argc, char* argv[]) { const unsigned long x_dim { 200 }; const unsigned long y_dim { 200 }; xt::xarray<int> grid = init_grid(x_dim, y_dim); bool changed { true }; iterate_grid(grid, x_dim, y_dim); while (changed == true) { changed = iterate_grid(grid, x_dim, y_dim); } print_grid(grid); return 0; }
c929
template <typename T> struct Node { Node* next; Node* prev; T data; };
c930
#include <algorithm> #include <iostream> #include <ostream> #include <vector> #include <tuple> typedef std::tuple<int, int> point; std::ostream& print(std::ostream& os, const point& p) { return os << "(" << std::get<0>(p) << ", " << std::get<1>(p) << ")"; } std::ostream& print(std::ostream& os, const std::vector<point>& v) { auto it = v.cbegin(); auto end = v.cend(); os << "["; if (it != end) { print(os, *it); it = std::next(it); } while (it != end) { os << ", "; print(os, *it); it = std::next(it); } return os << "]"; } bool ccw(const point& a, const point& b, const point& c) { return ((std::get<0>(b) - std::get<0>(a)) * (std::get<1>(c) - std::get<1>(a))) > ((std::get<1>(b) - std::get<1>(a)) * (std::get<0>(c) - std::get<0>(a))); } std::vector<point> convexHull(std::vector<point> p) { if (p.size() == 0) return std::vector<point>(); std::sort(p.begin(), p.end(), [](point& a, point& b){ if (std::get<0>(a) < std::get<0>(b)) return true; return false; }); std::vector<point> h; for (const auto& pt : p) { while (h.size() >= 2 && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) { h.pop_back(); } h.push_back(pt); } auto t = h.size() + 1; for (auto it = p.crbegin(); it != p.crend(); it = std::next(it)) { auto pt = *it; while (h.size() >= t && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) { h.pop_back(); } h.push_back(pt); } h.pop_back(); return h; } int main() { using namespace std; vector<point> points = { make_pair(16, 3), make_pair(12, 17), make_pair(0, 6), make_pair(-4, -6), make_pair(16, 6), make_pair(16, -7), make_pair(16, -3), make_pair(17, -4), make_pair(5, 19), make_pair(19, -8), make_pair(3, 16), make_pair(12, 13), make_pair(3, -4), make_pair(17, 5), make_pair(-3, 15), make_pair(-3, -9), make_pair(0, 11), make_pair(-9, -3), make_pair(-4, -2), make_pair(12, 10) }; auto hull = convexHull(points); auto it = hull.cbegin(); auto end = hull.cend(); cout << "Convex Hull: "; print(cout, hull); cout << endl; return 0; }
c931
#include <iostream> #include <string> #include <fstream> class cipher { public: bool work( std::string e, std::string f, std::string k ) { if( e.length() < 1 ) return false; fileBuffer = readFile( f ); if( "" == fileBuffer ) return false; keyBuffer = readFile( k ); if( "" == keyBuffer ) return false; outName = f; outName.insert( outName.find_first_of( "." ), "_out" ); switch( e[0] ) { case 'e': return encode(); case 'd': return decode(); } return false; } private: bool encode() { size_t idx, len = keyBuffer.length() >> 1; for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) { idx = keyBuffer.find_first_of( *i ); if( idx < len ) outBuffer.append( 1, keyBuffer.at( idx + len ) ); else outBuffer.append( 1, *i ); } return saveOutput(); } bool decode() { size_t idx, l = keyBuffer.length(), len = l >> 1; for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) { idx = keyBuffer.find_last_of( *i ); if( idx >= len && idx < l ) outBuffer.append( 1, keyBuffer.at( idx - len ) ); else outBuffer.append( 1, *i ); } return saveOutput(); } bool saveOutput() { std::ofstream o( outName.c_str() ); o.write( outBuffer.c_str(), outBuffer.size() ); o.close(); return true; } std::string readFile( std::string fl ) { std::string buffer = ""; std::ifstream f( fl.c_str(), std::ios_base::in ); if( f.good() ) { buffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() ); f.close(); } return buffer; } std::string fileBuffer, keyBuffer, outBuffer, outName; }; int main( int argc, char* argv[] ) { if( argc < 4 ) { std::cout << "<d or e>\tDecrypt or Encrypt\n<filename>\tInput file, the output file will have" "'_out' added to it.\n<key>\t\tfile with the key to encode/decode\n\n"; } else { cipher c; if( c.work( argv[1], argv[2], argv[3] ) ) std::cout << "\nFile successfully saved!\n\n"; else std::cout << "Something went wrong!\n\n"; } return 0; }
c932
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permutation(str.begin(), str.end())) return 0; return integer(str); } int main() { for (integer n : {0, 9, 12, 21, 12453, 738440, 45072010, 95322020}) std::cout << n << " -> " << next_highest(n) << '\n'; integer big("9589776899767587796600"); std::cout << big << " -> " << next_highest(big) << '\n'; return 0; }
c933
#include <map> #include <set> bool happy(int number) { static std::map<int, bool> cache; std::set<int> cycle; while (number != 1 && !cycle.count(number)) { if (cache.count(number)) { number = cache[number] ? 1 : 0; break; } cycle.insert(number); int newnumber = 0; while (number > 0) { int digit = number % 10; newnumber += digit * digit; number /= 10; } number = newnumber; } bool happiness = number == 1; for (std::set<int>::const_iterator it = cycle.begin(); it != cycle.end(); it++) cache[*it] = happiness; return happiness; } #include <iostream> int main() { for (int i = 1; i < 50; i++) if (happy(i)) std::cout << i << std::endl; return 0; }
c934
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_stirling1 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_stirling1::get(int n, int k) { if (k == 0) return n == 0 ? 1 : 0; if (k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = get(n - 1, k - 1) + (n - 1) * get(n - 1, k); cache_.emplace(p, s); return s; } void print_stirling_numbers(unsigned_stirling1& s1, int n) { std::cout << "Unsigned Stirling numbers of the first kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 10) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 10) << s1.get(i, j); std::cout << '\n'; } } int main() { unsigned_stirling1 s1; print_stirling_numbers(s1, 12); std::cout << "Maximum value of S1(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s1.get(100, k)); std::cout << max << '\n'; return 0; }
c935
#include <string> #include <iostream> #include <iterator> #include <fstream> #include <boost/regex.hpp> int main( ) { std::ifstream codeFile( "samplecode.txt" ) ; if ( codeFile ) { boost::regex commentre( "/\\*.*?\\*/" ) ; std::string my_erase( "" ) ; std::string stripped ; std::string code( (std::istreambuf_iterator<char>( codeFile ) ) , std::istreambuf_iterator<char>( ) ) ; codeFile.close( ) ; stripped = boost::regex_replace( code , commentre , my_erase ) ; std::cout << "Code unstripped:\n" << stripped << std::endl ; return 0 ; } else { std::cout << "Could not find code file!" << std::endl ; return 1 ; } }
c937
#include <cassert> int main() { int a; assert(a == 42); }
c938
#include <iomanip> #include <iostream> int factorial_mod(int n, int p) { int f = 1; for (; n > 0 && f != 0; --n) f = (f * n) % p; return f; } bool is_prime(int p) { return p > 1 && factorial_mod(p - 1, p) == p - 1; } int main() { std::cout << " n | prime?\n------------\n"; std::cout << std::boolalpha; for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}) std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n'; std::cout << "\nFirst 120 primes by Wilson's theorem:\n"; int n = 0, p = 1; for (; n < 120; ++p) { if (is_prime(p)) std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' '); } std::cout << "\n1000th through 1015th primes:\n"; for (int i = 0; n < 1015; ++p) { if (is_prime(p)) { if (++n >= 1000) std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' '); } } }
c939
#include <iostream> #include <random> #include <vector> int main( ) { std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ; std::random_device seed ; std::mt19937 engine( seed( ) ) ; std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ; std::cout << "random element picked : " << numbers[ choose( engine ) ] << " !\n" ; return 0 ; }
c940
#include <QByteArray> #include <iostream> int main( ) { QByteArray text ( "http: QByteArray encoded( text.toPercentEncoding( ) ) ; std::cout << encoded.data( ) << '\n' ; return 0 ; }
c941
#include <gmpxx.h> #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; } int main() { std::cout << "First 100 deceptive numbers:\n"; mpz_class repunit = 11; for (int n = 3, count = 0; count != 100; n += 2) { if (n % 3 != 0 && n % 5 != 0 && !is_prime(n) && mpz_divisible_ui_p(repunit.get_mpz_t(), n)) std::cout << std::setw(6) << n << (++count % 10 == 0 ? '\n' : ' '); repunit *= 100; repunit += 11; } }
c942
#include <iomanip> #include <iostream> #include <map> #include <sstream> bool isHumble(int i) { if (i <= 1) return true; if (i % 2 == 0) return isHumble(i / 2); if (i % 3 == 0) return isHumble(i / 3); if (i % 5 == 0) return isHumble(i / 5); if (i % 7 == 0) return isHumble(i / 7); return false; } auto toString(int n) { std::stringstream ss; ss << n; return ss.str(); } int main() { auto limit = SHRT_MAX; std::map<int, int> humble; auto count = 0; auto num = 1; while (count < limit) { if (isHumble(num)) { auto str = toString(num); auto len = str.length(); auto it = humble.find(len); if (it != humble.end()) { it->second++; } else { humble[len] = 1; } if (count < 50) std::cout << num << ' '; count++; } num++; } std::cout << "\n\n"; std::cout << "Of the first " << count << " humble numbers:\n"; num = 1; while (num < humble.size() - 1) { auto it = humble.find(num); if (it != humble.end()) { auto c = *it; std::cout << std::setw(5) << c.second << " have " << std::setw(2) << num << " digits\n"; num++; } else { break; } } return 0; }
c943
#include <cmath> #include <iostream> #include <string> #include <iomanip> #include <vector> class ulamSpiral { public: void create( unsigned n, unsigned startWith = 1 ) { _lst.clear(); if( !( n & 1 ) ) n++; _mx = n; unsigned v = n * n; _wd = static_cast<unsigned>( log10( static_cast<long double>( v ) ) ) + 1; for( unsigned u = 0; u < v; u++ ) _lst.push_back( -1 ); arrange( startWith ); } void display( char c ) { if( !c ) displayNumbers(); else displaySymbol( c ); } private: bool isPrime( unsigned u ) { if( u < 4 ) return u > 1; if( !( u % 2 ) || !( u % 3 ) ) return false; unsigned q = static_cast<unsigned>( sqrt( static_cast<long double>( u ) ) ), c = 5; while( c <= q ) { if( !( u % c ) || !( u % ( c + 2 ) ) ) return false; c += 6; } return true; } void arrange( unsigned s ) { unsigned stp = 1, n = 1, posX = _mx >> 1, posY = posX, stC = 0; int dx = 1, dy = 0; while( posX < _mx && posY < _mx ) { _lst.at( posX + posY * _mx ) = isPrime( s ) ? s : 0; s++; if( dx ) { posX += dx; if( ++stC == stp ) { dy = -dx; dx = stC = 0; } } else { posY += dy; if( ++stC == stp ) { dx = dy; dy = stC = 0; stp++; } } } } void displayNumbers() { unsigned ct = 0; for( std::vector<unsigned>::iterator i = _lst.begin(); i != _lst.end(); i++ ) { if( *i ) std::cout << std::setw( _wd ) << *i << " "; else std::cout << std::string( _wd, '*' ) << " "; if( ++ct >= _mx ) { std::cout << "\n"; ct = 0; } } std::cout << "\n\n"; } void displaySymbol( char c ) { unsigned ct = 0; for( std::vector<unsigned>::iterator i = _lst.begin(); i != _lst.end(); i++ ) { if( *i ) std::cout << c; else std::cout << " "; if( ++ct >= _mx ) { std::cout << "\n"; ct = 0; } } std::cout << "\n\n"; } std::vector<unsigned> _lst; unsigned _mx, _wd; }; int main( int argc, char* argv[] ) { ulamSpiral ulam; ulam.create( 9 ); ulam.display( 0 ); ulam.create( 35 ); ulam.display( '#' ); return 0; }
c944
#include <iostream> int main() { std::cout << static_cast<char>(163); return 0; }
c945
using System; class Program { static int l; static int[] gp(int n) { var c = new bool[n]; var r = new int[(int)(1.28 * n)]; l = 0; r[l++] = 2; r[l++] = 3; int j, d, lim = (int)Math.Sqrt(n); for (int i = 9; i < n; i += 6) c[i] = true; for (j = 5, d = 4; j < lim; j += (d = 6 - d)) if (!c[j]) { r[l++] = j; for (int k = j * j, ki = j << 1; k < n; k += ki) c[k] = true; } for ( ; j < n; j += (d = 6 - d)) if (!c[j]) r[l++] = j; return r; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); var res = gp(15485864); sw.Stop(); double gpt = sw.Elapsed.TotalMilliseconds, tt; var s = new string[19]; int si = 0; s[si++] = String.Format("primes gen time: {0} ms", gpt); sw.Restart(); s[si++] = " Nth Primorial"; double y = 0; int x = 1, i = 0, lmt = 10; s[si++] = String.Format("{0,7} {1}", 0, x); while (true) { if (i < 9) s[si++] = String.Format("{0,7} {1}", i + 1, x *= res[i]); if (i == 8) s[si++] = " Nth Digits Time"; y += Math.Log10(res[i]); if (++i == lmt) { s[si++] = String.Format("{0,7} {1,-7} {2,7} ms", lmt, 1 + (int)y, sw.Elapsed.TotalMilliseconds); if ((lmt *= 10) > (int)1e6) break; } } sw.Stop(); Console.WriteLine("{0}\n Tabulation: {1} ms", string.Join("\n", s), tt = sw.Elapsed.TotalMilliseconds); Console.Write(" Total:{0} ms", gpt + tt); } }
c0
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_size = 5; const int diff = 6; const int array_size = max + diff; const int max_groups = 5; const int max_unsexy = 10; prime_sieve sieve(array_size); std::array<int, max_group_size> group_count{0}; vector<group_buffer> groups(max_group_size, group_buffer(max_groups)); int unsexy_count = 0; circular_buffer<int> unsexy_primes(max_unsexy); vector<int> group; for (int p = 2; p < max; ++p) { if (!sieve.is_prime(p)) continue; if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) { ++unsexy_count; unsexy_primes.push_back(p); } else { group.clear(); group.push_back(p); for (int group_size = 1; group_size < max_group_size; group_size++) { int next_p = p + group_size * diff; if (next_p >= max || !sieve.is_prime(next_p)) break; group.push_back(next_p); ++group_count[group_size]; groups[group_size].push_back(group); } } } for (int size = 1; size < max_group_size; ++size) { cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n'; cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":"; for (const vector<int>& group : groups[size]) { cout << " ("; for (size_t i = 0; i < group.size(); ++i) { if (i > 0) cout << ' '; cout << group[i]; } cout << ")"; } cout << "\n\n"; } cout << "number of unsexy primes is " << unsexy_count << '\n'; cout << "last " << unsexy_primes.size() << " unsexy primes:"; for (int prime : unsexy_primes) cout << ' ' << prime; cout << '\n'; return 0; }
c1
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
c2
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
c3
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }
c4
int a[5]; a[0] = 1; int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; #include <string> std::string strings[4];
c5
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
c6
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
c7
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
c9
#include <iostream> #include <algorithm> #include <vector> #include <sstream> #include <iterator> using namespace std; class myTuple { public: void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; } bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; } string second() { return t.second; } private: pair<pair<int, int>, string> t; }; class discordian { public: discordian() { myTuple t; t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t ); t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t ); t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t ); t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t ); t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t ); t.set( 8, 12, "Afflux" ); holyday.push_back( t ); seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" ); seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" ); wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" ); wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" ); } void convert( int d, int m, int y ) { if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { cout << "\nThis is not a date!"; return; } vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); int dd = d, day, wday, sea, yr = y + 1166; for( int x = 1; x < m; x++ ) dd += getMaxDay( x, 1 ); day = dd % 73; if( !day ) day = 73; wday = dd % 5; sea = ( dd - 1 ) / 73; if( d == 29 && m == 2 && isLeap( y ) ) { cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr; return; } cout << wdays[wday] << " " << seasons[sea] << " " << day; if( day > 10 && day < 14 ) cout << "th"; else switch( day % 10) { case 1: cout << "st"; break; case 2: cout << "nd"; break; case 3: cout << "rd"; break; default: cout << "th"; } cout << ", Year of Our Lady of Discord " << yr; if( f != holyday.end() ) cout << " - " << ( *f ).second(); } private: int getMaxDay( int m, int y ) { int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; } bool isLeap( int y ) { bool l = false; if( !( y % 4 ) ) { if( y % 100 ) l = true; else if( !( y % 400 ) ) l = true; } return l; } vector<myTuple> holyday; vector<string> seasons, wdays; }; int main( int argc, char* argv[] ) { string date; discordian disc; while( true ) { cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break; if( date.length() == 10 ) { istringstream iss( date ); vector<string> vc; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) ); disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); cout << "\n\n\n"; } else cout << "\nIs this a date?!\n\n"; } return 0; }
c10
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
c11
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
c12
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
c13
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
c14
#include <iostream> #include <vector> #include <stack> #include <iterator> #include <algorithm> #include <cassert> template <class E> struct pile_less { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() < pile2.top(); } }; template <class E> struct pile_greater { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() > pile2.top(); } }; template <class Iterator> void patience_sort(Iterator first, Iterator last) { typedef typename std::iterator_traits<Iterator>::value_type E; typedef std::stack<E> Pile; std::vector<Pile> piles; for (Iterator it = first; it != last; it++) { E& x = *it; Pile newPile; newPile.push(x); typename std::vector<Pile>::iterator i = std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>()); if (i != piles.end()) i->push(x); else piles.push_back(newPile); } std::make_heap(piles.begin(), piles.end(), pile_greater<E>()); for (Iterator it = first; it != last; it++) { std::pop_heap(piles.begin(), piles.end(), pile_greater<E>()); Pile &smallPile = piles.back(); *it = smallPile.top(); smallPile.pop(); if (smallPile.empty()) piles.pop_back(); else std::push_heap(piles.begin(), piles.end(), pile_greater<E>()); } assert(piles.empty()); } int main() { int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1}; patience_sort(a, a+sizeof(a)/sizeof(*a)); std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; return 0; }
c15
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
c16
#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() { const unsigned int limit = 100; std::cout << "The first " << limit << " tau numbers are:\n"; unsigned int count = 0; for (unsigned int n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { std::cout << std::setw(6) << n; ++count; if (count % 10 == 0) std::cout << '\n'; } } }
c17
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
c18
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; } int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\n"; }