{"title": "100 prisoners", "language": "C++", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "#include // for rand\n#include // for random_shuffle\n#include // for output\n\nusing namespace std;\n\nclass cupboard {\npublic:\n cupboard() {\n for (int i = 0; i < 100; i++)\n drawers[i] = i;\n random_shuffle(drawers, drawers + 100);\n }\n\n bool playRandom();\n bool playOptimal();\n\nprivate:\n int drawers[100];\n};\n\nbool cupboard::playRandom() {\n bool openedDrawers[100] = { 0 };\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { // loops through prisoners numbered 0 through 99\n bool prisonerSuccess = false;\n for (int i = 0; i < 100 / 2; i++) { // loops through 50 draws for each prisoner\n int drawerNum = rand() % 100;\n if (!openedDrawers[drawerNum]) {\n openedDrawers[drawerNum] = true;\n break;\n }\n if (drawers[drawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n }\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\nbool cupboard::playOptimal() {\n for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) {\n bool prisonerSuccess = false;\n int checkDrawerNum = prisonerNum;\n for (int i = 0; i < 100 / 2; i++) {\n if (drawers[checkDrawerNum] == prisonerNum) {\n prisonerSuccess = true;\n break;\n } else\n checkDrawerNum = drawers[checkDrawerNum];\n }\n if (!prisonerSuccess)\n return false;\n }\n return true;\n}\n\ndouble simulate(char strategy) {\n int numberOfSuccesses = 0;\n for (int i = 0; i < 10000; i++) {\n cupboard d;\n if ((strategy == 'R' && d.playRandom()) || (strategy == 'O' && d.playOptimal())) // will run playRandom or playOptimal but not both because of short-circuit evaluation\n numberOfSuccesses++;\n }\n\n return numberOfSuccesses * 100.0 / 10000;\n}\n\nint main() {\n cout << \"Random strategy: \" << simulate('R') << \" %\" << endl;\n cout << \"Optimal strategy: \" << simulate('O') << \" %\" << endl;\n system(\"PAUSE\"); // for Windows\n return 0;\n}"} {"title": "15 puzzle game", "language": "C++", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \nclass p15 {\npublic :\n void play() {\n bool p = true;\n std::string a;\n while( p ) {\n createBrd();\n while( !isDone() ) { drawBrd();getMove(); }\n drawBrd();\n std::cout << \"\\n\\nCongratulations!\\nPlay again (Y/N)?\";\n std::cin >> a; if( a != \"Y\" && a != \"y\" ) break;\n }\n }\nprivate:\n void createBrd() {\n int i = 1; std::vector v;\n for( ; i < 16; i++ ) { brd[i - 1] = i; }\n brd[15] = 0; x = y = 3;\n for( i = 0; i < 1000; i++ ) {\n getCandidates( v );\n move( v[rand() % v.size()] );\n v.clear();\n }\n }\n void move( int d ) {\n int t = x + y * 4;\n switch( d ) {\n case 1: y--; break;\n case 2: x++; break;\n case 4: y++; break;\n case 8: x--;\n }\n brd[t] = brd[x + y * 4];\n brd[x + y * 4] = 0;\n }\n void getCandidates( std::vector& v ) {\n if( x < 3 ) v.push_back( 2 ); if( x > 0 ) v.push_back( 8 );\n if( y < 3 ) v.push_back( 4 ); if( y > 0 ) v.push_back( 1 );\n }\n void drawBrd() {\n int r; std::cout << \"\\n\\n\";\n for( int y = 0; y < 4; y++ ) {\n std::cout << \"+----+----+----+----+\\n\";\n for( int x = 0; x < 4; x++ ) {\n r = brd[x + y * 4];\n std::cout << \"| \";\n if( r < 10 ) std::cout << \" \";\n if( !r ) std::cout << \" \";\n else std::cout << r << \" \";\n }\n std::cout << \"|\\n\";\n }\n std::cout << \"+----+----+----+----+\\n\";\n }\n void getMove() {\n std::vector v; getCandidates( v );\n std::vector p; getTiles( p, v ); unsigned int i;\n while( true ) {\n std::cout << \"\\nPossible moves: \";\n for( i = 0; i < p.size(); i++ ) std::cout << p[i] << \" \";\n int z; std::cin >> z;\n for( i = 0; i < p.size(); i++ )\n if( z == p[i] ) { move( v[i] ); return; }\n }\n }\n void getTiles( std::vector& p, std::vector& v ) {\n for( unsigned int t = 0; t < v.size(); t++ ) {\n int xx = x, yy = y;\n switch( v[t] ) {\n case 1: yy--; break;\n case 2: xx++; break;\n case 4: yy++; break;\n case 8: xx--;\n }\n p.push_back( brd[xx + yy * 4] );\n }\n }\n bool isDone() {\n for( int i = 0; i < 15; i++ ) {\n if( brd[i] != i + 1 ) return false;\n }\n return true;\n }\n int brd[16], x, y;\n};\nint main( int argc, char* argv[] ) {\n srand( ( unsigned )time( 0 ) );\n p15 p; p.play(); return 0;\n}\n"} {"title": "21 game", "language": "C++", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "/**\n * Game 21 - an example in C++ language for Rosseta Code.\n *\n * This version is an example of MVP architecture. The user input, as well as\n * the AI opponent, is handled by separate passive subclasses of abstract class\n * named Controller. It can be noticed that the architecture support OCP,\n * for an example the AI module can be \"easily\" replaced by another AI etc.\n *\n * BTW, it would be better to place each class in its own file. But it would\n * be less convinient for Rosseta Code, where \"one solution\" mean \"one file\".\n */\n\n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace std;\n\n#define _(STR) STR\n\n\nclass Model\n{\nprotected:\n\n int oldTotal;\n int newTotal;\n int lastMove;\n\npublic:\n\n static const int GOAL = 21;\n static const int NUMBER_OF_PLAYERS = 2;\n\n Model()\n {\n newTotal = 0;\n oldTotal = 0;\n lastMove = 0;\n }\n\n void update(int move)\n {\n oldTotal = newTotal;\n newTotal = oldTotal + move;\n lastMove = move;\n }\n\n int getOldTotal()\n {\n return oldTotal;\n }\n\n int getNewTotal()\n {\n return newTotal;\n }\n\n int getLastMove()\n {\n return lastMove;\n }\n\n bool isEndGame()\n {\n return newTotal == GOAL;\n }\n};\n\n\nclass View\n{\npublic:\n\n void update(string comment, Model* model)\n {\n cout << setw(8) << comment << \": \"\n << model->getNewTotal()\n << \" = \"\n << model->getOldTotal()\n << \" + \"\n << model->getLastMove() << endl\n << endl;\n }\n\n void newGame(string player)\n {\n cout << _(\"----NEW GAME----\") << endl\n << endl\n << _(\"The running total is currently zero.\") << endl\n << endl\n << _(\"The first move is \") << player << _(\" move.\") << endl\n << endl;\n }\n\n void endGame(string name)\n {\n cout << endl << _(\"The winner is \") << name << _(\".\") << endl\n << endl\n << endl;\n }\n};\n\n\nclass Controller\n{\npublic:\n\n virtual string getName() = 0;\n virtual int getMove(Model* model) = 0;\n};\n\n\nclass AI : public Controller\n{\npublic:\n\n string getName()\n {\n return _(\"AI\");\n }\n\n int getMove(Model* model)\n {\n int n = model->getNewTotal();\n for (int i = 1; i <= 3; i++)\n if (n + i == Model::GOAL)\n return i;\n for (int i = 1; i <= 3; i++)\n if ((n + i - 1) % 4 == 0)\n return i;\n return 1 + rand() % 3;\n }\n};\n\n\nclass Human : public Controller\n{\npublic:\n\n string getName()\n {\n return _(\"human\");\n }\n\n int getMove(Model* model)\n {\n int n = model->getNewTotal();\n int value;\n while (true) {\n if (n == Model::GOAL - 1)\n cout << _(\"enter 1 to play (or enter 0 to exit game): \");\n else if (n == Model::GOAL - 2)\n cout << _(\"enter 1 or 2 to play (or enter 0 to exit game): \");\n else\n cout << _(\"enter 1 or 2 or 3 to play (or enter 0 to exit game): \");\n cin >> value;\n if (!cin.fail()) {\n if (value == 0)\n exit(0);\n else if (value >= 1 && value <= 3 && n + value <= Model::GOAL)\n {\n cout << endl;\n return value;\n }\n }\n cout << _(\"Your answer is not a valid choice.\") << endl;\n cin.clear();\n cin.ignore((streamsize)numeric_limits::max, '\\n');\n }\n }\n};\n\n\nclass Presenter\n{\nprotected:\n\n Model* model;\n View* view;\n Controller** controllers;\n\npublic:\n\n Presenter(Model* model, View* view, Controller** controllers)\n {\n this->model = model;\n this->view = view;\n this->controllers = controllers;\n }\n\n void run()\n {\n int player = rand() % Model::NUMBER_OF_PLAYERS;\n view->newGame(controllers[player]->getName());\n\n while (true)\n {\n Controller* controller = controllers[player];\n model->update(controller->getMove(model));\n view->update(controller->getName(), model);\n if (model->isEndGame())\n {\n view->endGame(controllers[player]->getName());\n break;\n }\n player = (player + 1) % Model::NUMBER_OF_PLAYERS;\n }\n }\n};\n\n\nint main(int argc, char* argv)\n{\n srand(time(NULL));\n\n while (true)\n {\n Model* model = new Model();\n View* view = new View();\n Controller* controllers[Model::NUMBER_OF_PLAYERS];\n controllers[0] = new Human();\n for (int i = 1; i < Model::NUMBER_OF_PLAYERS; i++)\n controllers[i] = new AI();\n Presenter* presenter = new Presenter(model, view, controllers);\n\n presenter->run();\n\n delete model;\n delete view;\n delete controllers[0];\n delete controllers[1];\n delete presenter;\n }\n return EXIT_SUCCESS; // dead code\n}\n"} {"title": "24 game", "language": "C++11", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nclass RPNParse\n{\npublic:\n stack stk;\n multiset digits;\n\n void op(function f)\n {\n if(stk.size() < 2)\n throw \"Improperly written expression\";\n int b = stk.top(); stk.pop();\n int a = stk.top(); stk.pop();\n stk.push(f(a, b));\n }\n\n void parse(char c)\n {\n if(c >= '0' && c <= '9')\n {\n stk.push(c - '0');\n digits.insert(c - '0');\n }\n else if(c == '+')\n op([](double a, double b) {return a+b;});\n else if(c == '-')\n op([](double a, double b) {return a-b;});\n else if(c == '*')\n op([](double a, double b) {return a*b;});\n else if(c == '/')\n op([](double a, double b) {return a/b;});\n }\n\n void parse(string s)\n {\n for(int i = 0; i < s.size(); ++i)\n parse(s[i]);\n }\n\n double getResult()\n {\n if(stk.size() != 1)\n throw \"Improperly written expression\";\n return stk.top();\n }\n};\n\nint main()\n{\n random_device seed;\n mt19937 engine(seed());\n uniform_int_distribution<> distribution(1, 9);\n auto rnd = bind(distribution, engine);\n\n multiset digits;\n cout << \"Make 24 with the digits: \";\n for(int i = 0; i < 4; ++i)\n {\n int n = rnd();\n cout << \" \" << n;\n digits.insert(n);\n }\n cout << endl;\n\n RPNParse parser;\n\n try\n {\n string input;\n getline(cin, input);\n parser.parse(input);\n\n if(digits != parser.digits)\n cout << \"Error: Not using the given digits\" << endl;\n else\n {\n double r = parser.getResult();\n cout << \"Result: \" << r << endl;\n\n if(r > 23.999 && r < 24.001)\n cout << \"Good job!\" << endl;\n else\n cout << \"Try again.\" << endl;\n }\n }\n catch(char* e)\n {\n cout << \"Error: \" << e << endl;\n }\n return 0;\n}"} {"title": "4-rings or 4-squares puzzle", "language": "C++", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "//C++14/17\n#include //std::for_each\n#include //std::cout\n#include //std::iota\n#include //std::vector, save solutions\n#include //std::list, for fast erase\n\nusing std::begin, std::end, std::for_each;\n\n//Generates all the valid solutions for the problem in the specified range [from, to)\nstd::list> combinations(int from, int to)\n{\n if (from > to)\n return {}; //Return nothing if limits are invalid\n\n auto pool = std::vector(to - from);//Here we'll save our values\n std::iota(begin(pool), end(pool), from);//Populates pool\n\n auto solutions = std::list>{}; //List for the solutions\n\n //Brute-force calculation of valid values...\n for (auto a : pool)\n for (auto b : pool)\n for (auto c : pool)\n for (auto d : pool)\n for (auto e : pool)\n for (auto f : pool)\n for (auto g : pool)\n if ( a == c + d\n && b + c == e + f\n && d + e == g )\n solutions.push_back({a, b, c, d, e, f, g});\n return solutions;\n}\n\n//Filter the list generated from \"combinations\" and return only lists with no repetitions\nstd::list> filter_unique(int from, int to)\n{\n //Helper lambda to check repetitions:\n //If the count is > 1 for an element, there must be a repetition inside the range\n auto has_non_unique_values = [](const auto & range, auto target)\n {\n return std::count( begin(range), end(range), target) > 1;\n };\n\n //Generates all the solutions...\n auto results = combinations(from, to);\n\n //For each solution, find duplicates inside\n for (auto subrange = cbegin(results); subrange != cend(results); ++subrange)\n {\n bool repetition = false;\n\n //If some element is repeated, repetition becomes true \n for (auto x : *subrange)\n repetition |= has_non_unique_values(*subrange, x);\n\n if (repetition) //If repetition is true, remove the current subrange from the list\n {\n results.erase(subrange); //Deletes subrange from solutions\n --subrange; //Rewind to the last subrange analysed\n }\n }\n\n return results; //Finally return remaining results\n}\n\ntemplate //Template for the sake of simplicity\ninline void print_range(const Container & c)\n{\n for (const auto & subrange : c)\n {\n std::cout << \"[\";\n for (auto elem : subrange)\n std::cout << elem << ' ';\n std::cout << \"\\b]\\n\";\n }\n}\n\n\nint main()\n{\n std::cout << \"Unique-numbers combinations in range 1-7:\\n\";\n auto solution1 = filter_unique(1, 8);\n print_range(solution1);\n std::cout << \"\\nUnique-numbers combinations in range 3-9:\\n\";\n auto solution2 = filter_unique(3,10);\n print_range(solution2);\n std::cout << \"\\nNumber of combinations in range 0-9: \" \n << combinations(0, 10).size() << \".\" << std::endl;\n\n return 0;\n}\n"} {"title": "9 billion names of God the integer", "language": "C++", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "// Calculate hypotenuse n of OTT assuming only nothingness, unity, and hyp[n-1] if n>1\n// Nigel Galloway, May 6th., 2013\n#include \nint N{123456};\nmpz_class hyp[N-3];\nconst mpz_class G(const int n,const int g){return g>n?0:(g==1 or n-g<2)?1:hyp[n-g-2];};\nvoid G_hyp(const int n){for(int i=0;i\nusing namespace std;\nint main()\n{\n ifstream in(\"input.txt\");\n ofstream out(\"output.txt\");\n int a, b;\n in >> a >> b;\n out << a + b << endl;\n return 0;\n}"} {"title": "ABC problem", "language": "C++11", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ntypedef std::pair item_t;\ntypedef std::vector list_t;\n\nbool can_make_word(const std::string& w, const list_t& vals) {\n std::set used;\n while (used.size() < w.size()) {\n const char c = toupper(w[used.size()]);\n uint32_t x = used.size();\n for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) {\n if (used.find(i) == used.end()) {\n if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) {\n used.insert(i);\n break;\n }\n }\n }\n if (x == used.size()) break;\n }\n return used.size() == w.size();\n}\n\nint main() {\n list_t vals{ {'B','O'}, {'X','K'}, {'D','Q'}, {'C','P'}, {'N','A'}, {'G','T'}, {'R','E'}, {'T','G'}, {'Q','D'}, {'F','S'}, {'J','W'}, {'H','U'}, {'V','I'}, {'A','N'}, {'O','B'}, {'E','R'}, {'F','S'}, {'L','Y'}, {'P','C'}, {'Z','M'} };\n std::vector words{\"A\",\"BARK\",\"BOOK\",\"TREAT\",\"COMMON\",\"SQUAD\",\"CONFUSE\"};\n for (const std::string& w : words) {\n std::cout << w << \": \" << std::boolalpha << can_make_word(w,vals) << \".\\n\";\n }\n}"} {"title": "ASCII art diagram converter", "language": "C++", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\nstruct FieldDetails {string_view Name; int NumBits;};\n\n// parses the ASCII diagram and returns the field name, bit sizes, and the\n// total byte size\ntemplate consteval auto ParseDiagram()\n{ \n // trim the ASCII diagram text\n constexpr string_view rawArt(T);\n constexpr auto firstBar = rawArt.find(\"|\");\n constexpr auto lastBar = rawArt.find_last_of(\"|\");\n constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);\n static_assert(firstBar < lastBar, \"ASCII Table has no fields\");\n \n // make an array for all of the fields\n constexpr auto numFields = \n count(rawArt.begin(), rawArt.end(), '|') -\n count(rawArt.begin(), rawArt.end(), '\\n') / 2; \n array fields;\n \n // parse the diagram\n bool isValidDiagram = true;\n int startDiagramIndex = 0;\n int totalBits = 0;\n for(int i = 0; i < numFields; )\n {\n auto beginningBar = art.find(\"|\", startDiagramIndex);\n auto endingBar = art.find(\"|\", beginningBar + 1);\n auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);\n if(field.find(\"-\") == field.npos) \n {\n int numBits = (field.size() + 1) / 3;\n auto nameStart = field.find_first_not_of(\" \");\n auto nameEnd = field.find_last_not_of(\" \");\n if (nameStart > nameEnd || nameStart == string_view::npos) \n {\n // the table cannot be parsed\n isValidDiagram = false;\n field = \"\"sv;\n }\n else\n {\n field = field.substr(nameStart, 1 + nameEnd - nameStart);\n }\n fields[i++] = FieldDetails {field, numBits};\n totalBits += numBits;\n }\n startDiagramIndex = endingBar;\n }\n \n int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;\n return make_pair(fields, numRawBytes);\n}\n\n// encode the values of the fields into a raw data array\ntemplate auto Encode(auto inputValues)\n{\n constexpr auto parsedDiagram = ParseDiagram();\n static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n array data;\n\n int startBit = 0;\n int i = 0;\n for(auto value : inputValues)\n {\n const auto &field = parsedDiagram.first[i++];\n int remainingValueBits = field.NumBits;\n while(remainingValueBits > 0)\n {\n // pack the bits from an input field into the data array\n auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n int unusedBits = 8 - fieldStartBit;\n int numBitsToEncode = min({unusedBits, 8, field.NumBits});\n int divisor = 1 << (remainingValueBits - numBitsToEncode);\n unsigned char bitsToEncode = value / divisor;\n data[fieldStartByte] <<= numBitsToEncode;\n data[fieldStartByte] |= bitsToEncode;\n value %= divisor;\n startBit += numBitsToEncode;\n remainingValueBits -= numBitsToEncode;\n }\n }\n \n return data;\n}\n\n// decode the raw data into the format of the ASCII diagram\ntemplate void Decode(auto data)\n{\n cout << \"Name Bit Pattern\\n\";\n cout << \"======= ================\\n\";\n constexpr auto parsedDiagram = ParseDiagram();\n static_assert(parsedDiagram.second > 0, \"Invalid ASCII talble\");\n\n int startBit = 0;\n for(const auto& field : parsedDiagram.first)\n {\n // unpack the bits from the data into a single field\n auto [fieldStartByte, fieldStartBit] = div(startBit, 8);\n unsigned char firstByte = data[fieldStartByte];\n firstByte <<= fieldStartBit;\n firstByte >>= fieldStartBit;\n int64_t value = firstByte;\n auto endBit = startBit + field.NumBits;\n auto [fieldEndByte, fieldEndBit] = div(endBit, 8);\n fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));\n for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)\n {\n value <<= 8;\n value += data[index];\n }\n value >>= fieldEndBit;\n startBit = endBit;\n \n cout << field.Name << \n string_view(\" \", (7 - field.Name.size())) << \" \" << \n string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) << \"\\n\";\n }\n \n}\n\nint main(void) \n{\n static constexpr char art[] = R\"(\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)\";\n \n // using the table above, encode the data below\n auto rawData = Encode (initializer_list {\n 30791,\n 0, 15, 0, 1, 1, 1, 3, 15,\n 21654,\n 57646,\n 7153,\n 27044\n });\n \n cout << \"Raw encoded data in hex:\\n\";\n for (auto v : rawData) printf(\"%.2X\", v);\n cout << \"\\n\\n\";\n \n cout << \"Decoded raw data:\\n\";\n Decode(rawData);\n}"} {"title": "AVL tree", "language": "C++ from D", "task": "{{wikipedia|AVL tree}}\n\n\n\nIn computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\n\n;Task:\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\n;Related task\n[[Red_black_tree_sort]]\n\n", "solution": "#include \n#include \n\n/* AVL node */\ntemplate \nclass AVLnode {\npublic:\n T key;\n int balance;\n AVLnode *left, *right, *parent;\n\n AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n left(NULL), right(NULL) {}\n\n ~AVLnode() {\n delete left;\n delete right;\n }\n};\n\n/* AVL tree */\ntemplate \nclass AVLtree {\npublic:\n AVLtree(void);\n ~AVLtree(void);\n bool insert(T key);\n void deleteKey(const T key);\n void printBalance();\n\nprivate:\n AVLnode *root;\n\n AVLnode* rotateLeft ( AVLnode *a );\n AVLnode* rotateRight ( AVLnode *a );\n AVLnode* rotateLeftThenRight ( AVLnode *n );\n AVLnode* rotateRightThenLeft ( AVLnode *n );\n void rebalance ( AVLnode *n );\n int height ( AVLnode *n );\n void setBalance ( AVLnode *n );\n void printBalance ( AVLnode *n );\n};\n\n/* AVL class definition */\ntemplate \nvoid AVLtree::rebalance(AVLnode *n) {\n setBalance(n);\n\n if (n->balance == -2) {\n if (height(n->left->left) >= height(n->left->right))\n n = rotateRight(n);\n else\n n = rotateLeftThenRight(n);\n }\n else if (n->balance == 2) {\n if (height(n->right->right) >= height(n->right->left))\n n = rotateLeft(n);\n else\n n = rotateRightThenLeft(n);\n }\n\n if (n->parent != NULL) {\n rebalance(n->parent);\n }\n else {\n root = n;\n }\n}\n\ntemplate \nAVLnode* AVLtree::rotateLeft(AVLnode *a) {\n AVLnode *b = a->right;\n b->parent = a->parent;\n a->right = b->left;\n\n if (a->right != NULL)\n a->right->parent = a;\n\n b->left = a;\n a->parent = b;\n\n if (b->parent != NULL) {\n if (b->parent->right == a) {\n b->parent->right = b;\n }\n else {\n b->parent->left = b;\n }\n }\n\n setBalance(a);\n setBalance(b);\n return b;\n}\n\ntemplate \nAVLnode* AVLtree::rotateRight(AVLnode *a) {\n AVLnode *b = a->left;\n b->parent = a->parent;\n a->left = b->right;\n\n if (a->left != NULL)\n a->left->parent = a;\n\n b->right = a;\n a->parent = b;\n\n if (b->parent != NULL) {\n if (b->parent->right == a) {\n b->parent->right = b;\n }\n else {\n b->parent->left = b;\n }\n }\n\n setBalance(a);\n setBalance(b);\n return b;\n}\n\ntemplate \nAVLnode* AVLtree::rotateLeftThenRight(AVLnode *n) {\n n->left = rotateLeft(n->left);\n return rotateRight(n);\n}\n\ntemplate \nAVLnode* AVLtree::rotateRightThenLeft(AVLnode *n) {\n n->right = rotateRight(n->right);\n return rotateLeft(n);\n}\n\ntemplate \nint AVLtree::height(AVLnode *n) {\n if (n == NULL)\n return -1;\n return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate \nvoid AVLtree::setBalance(AVLnode *n) {\n n->balance = height(n->right) - height(n->left);\n}\n\ntemplate \nvoid AVLtree::printBalance(AVLnode *n) {\n if (n != NULL) {\n printBalance(n->left);\n std::cout << n->balance << \" \";\n printBalance(n->right);\n }\n}\n\ntemplate \nAVLtree::AVLtree(void) : root(NULL) {}\n\ntemplate \nAVLtree::~AVLtree(void) {\n delete root;\n}\n\ntemplate \nbool AVLtree::insert(T key) {\n if (root == NULL) {\n root = new AVLnode(key, NULL);\n }\n else {\n AVLnode\n *n = root,\n *parent;\n\n while (true) {\n if (n->key == key)\n return false;\n\n parent = n;\n\n bool goLeft = n->key > key;\n n = goLeft ? n->left : n->right;\n\n if (n == NULL) {\n if (goLeft) {\n parent->left = new AVLnode(key, parent);\n }\n else {\n parent->right = new AVLnode(key, parent);\n }\n\n rebalance(parent);\n break;\n }\n }\n }\n\n return true;\n}\n\ntemplate \nvoid AVLtree::deleteKey(const T delKey) {\n if (root == NULL)\n return;\n\n AVLnode\n *n = root,\n *parent = root,\n *delNode = NULL,\n *child = root;\n\n while (child != NULL) {\n parent = n;\n n = child;\n child = delKey >= n->key ? n->right : n->left;\n if (delKey == n->key)\n delNode = n;\n }\n\n if (delNode != NULL) {\n delNode->key = n->key;\n\n child = n->left != NULL ? n->left : n->right;\n\n if (root->key == delKey) {\n root = child;\n }\n else {\n if (parent->left == n) {\n parent->left = child;\n }\n else {\n parent->right = child;\n }\n\n rebalance(parent);\n }\n }\n}\n\ntemplate \nvoid AVLtree::printBalance() {\n printBalance(root);\n std::cout << std::endl;\n}\n\nint main(void)\n{\n AVLtree t;\n\n std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n for (int i = 1; i <= 10; ++i)\n t.insert(i);\n\n std::cout << \"Printing balance: \";\n t.printBalance();\n}\n"} {"title": "Abbreviations, automatic", "language": "C++ from C#", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mercores Joves Venres Sabado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::vector split(const std::string& str, char delimiter) {\n std::vector tokens;\n std::string token;\n std::istringstream tokenStream(str);\n while (std::getline(tokenStream, token, delimiter)) {\n tokens.push_back(token);\n }\n return tokens;\n}\n\nint main() {\n using namespace std;\n string line;\n int i = 0;\n\n ifstream in(\"days_of_week.txt\");\n if (in.is_open()) {\n while (getline(in, line)) {\n i++;\n if (line.empty()) {\n continue;\n }\n\n auto days = split(line, ' ');\n if (days.size() != 7) {\n throw std::runtime_error(\"There aren't 7 days in line \" + i);\n }\n\n map temp;\n for (auto& day : days) {\n if (temp.find(day) != temp.end()) {\n cerr << \" \u221e \" << line << '\\n';\n continue;\n }\n temp[day] = 1;\n }\n\n int len = 1;\n while (true) {\n temp.clear();\n for (auto& day : days) {\n string key = day.substr(0, len);\n if (temp.find(key) != temp.end()) {\n break;\n }\n temp[key] = 1;\n }\n if (temp.size() == 7) {\n cout << setw(2) << len << \" \" << line << '\\n';\n break;\n }\n len++;\n }\n }\n }\n\n return 0;\n}"} {"title": "Abbreviations, easy", "language": "C++", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \"\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \"\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \"\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \"\n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \"\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \"\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\";\n\nclass command {\npublic:\n command(const std::string&, size_t);\n const std::string& cmd() const { return cmd_; }\n size_t min_length() const { return min_len_; }\n bool match(const std::string&) const;\nprivate:\n std::string cmd_;\n size_t min_len_;\n};\n\n// cmd is assumed to be all uppercase\ncommand::command(const std::string& cmd, size_t min_len)\n : cmd_(cmd), min_len_(min_len) {}\n\n// str is assumed to be all uppercase\nbool command::match(const std::string& str) const {\n size_t olen = str.length();\n return olen >= min_len_ && olen <= cmd_.length()\n && cmd_.compare(0, olen, str) == 0;\n}\n\n// convert string to uppercase\nvoid uppercase(std::string& str) {\n std::transform(str.begin(), str.end(), str.begin(),\n [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nsize_t get_min_length(const std::string& str) {\n size_t len = 0, n = str.length();\n while (len < n && std::isupper(static_cast(str[len])))\n ++len;\n return len;\n}\n\nclass command_list {\npublic:\n explicit command_list(const char*);\n const command* find_command(const std::string&) const;\nprivate:\n std::vector commands_;\n};\n\ncommand_list::command_list(const char* table) {\n std::vector commands;\n std::istringstream is(table);\n std::string word;\n while (is >> word) {\n // count leading uppercase characters\n size_t len = get_min_length(word);\n // then convert to uppercase\n uppercase(word);\n commands_.push_back(command(word, len));\n }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n auto iter = std::find_if(commands_.begin(), commands_.end(),\n [&word](const command& cmd) { return cmd.match(word); });\n return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n std::string output;\n std::istringstream is(input);\n std::string word;\n while (is >> word) {\n if (!output.empty())\n output += ' ';\n uppercase(word);\n const command* cmd_ptr = commands.find_command(word);\n if (cmd_ptr)\n output += cmd_ptr->cmd();\n else\n output += \"*error*\";\n }\n return output;\n}\n\nint main() {\n command_list commands(command_table);\n std::string input(\"riG rePEAT copies put mo rest types fup. 6 poweRin\");\n std::string output(test(commands, input));\n std::cout << \" input: \" << input << '\\n';\n std::cout << \"output: \" << output << '\\n';\n return 0;\n}"} {"title": "Abbreviations, simple", "language": "C++", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nconst char* command_table =\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \"\n \"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \"\n \"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \"\n \"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \"\n \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \"\n \"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \"\n \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \"\n \"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\";\n\nclass command {\npublic:\n command(const std::string&, size_t);\n const std::string& cmd() const { return cmd_; }\n size_t min_length() const { return min_len_; }\n bool match(const std::string&) const;\nprivate:\n std::string cmd_;\n size_t min_len_;\n};\n\n// cmd is assumed to be all uppercase\ncommand::command(const std::string& cmd, size_t min_len)\n : cmd_(cmd), min_len_(min_len) {}\n\n// str is assumed to be all uppercase\nbool command::match(const std::string& str) const {\n size_t olen = str.length();\n return olen >= min_len_ && olen <= cmd_.length()\n && cmd_.compare(0, olen, str) == 0;\n}\n\nbool parse_integer(const std::string& word, int& value) {\n try {\n size_t pos;\n int i = std::stoi(word, &pos, 10);\n if (pos < word.length())\n return false;\n value = i;\n return true;\n } catch (const std::exception& ex) {\n return false;\n }\n}\n\n// convert string to uppercase\nvoid uppercase(std::string& str) {\n std::transform(str.begin(), str.end(), str.begin(),\n [](unsigned char c) -> unsigned char { return std::toupper(c); });\n}\n\nclass command_list {\npublic:\n explicit command_list(const char*);\n const command* find_command(const std::string&) const;\nprivate:\n std::vector commands_;\n};\n\ncommand_list::command_list(const char* table) {\n std::istringstream is(table);\n std::string word;\n std::vector words;\n while (is >> word) {\n uppercase(word);\n words.push_back(word);\n }\n for (size_t i = 0, n = words.size(); i < n; ++i) {\n word = words[i];\n // if there's an integer following this word, it specifies the minimum\n // length for the command, otherwise the minimum length is the length\n // of the command string\n int len = word.length();\n if (i + 1 < n && parse_integer(words[i + 1], len))\n ++i;\n commands_.push_back(command(word, len));\n }\n}\n\nconst command* command_list::find_command(const std::string& word) const {\n auto iter = std::find_if(commands_.begin(), commands_.end(),\n [&word](const command& cmd) { return cmd.match(word); });\n return (iter != commands_.end()) ? &*iter : nullptr;\n}\n\nstd::string test(const command_list& commands, const std::string& input) {\n std::string output;\n std::istringstream is(input);\n std::string word;\n while (is >> word) {\n if (!output.empty())\n output += ' ';\n uppercase(word);\n const command* cmd_ptr = commands.find_command(word);\n if (cmd_ptr)\n output += cmd_ptr->cmd();\n else\n output += \"*error*\";\n }\n return output;\n}\n\nint main() {\n command_list commands(command_table);\n std::string input(\"riG rePEAT copies put mo rest types fup. 6 poweRin\");\n std::string output(test(commands, input));\n std::cout << \" input: \" << input << '\\n';\n std::cout << \"output: \" << output << '\\n';\n return 0;\n}"} {"title": "Abelian sandpile model/Identity", "language": "C++", "task": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that \ncontain a number from 0 to 3 inclusive. (The numbers are said to represent \ngrains of sand in each area of the sandpile).\n\nE.g. s1 =\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n\nand s2 =\n\n 2 1 3\n 1 0 1\n 0 1 0\n \n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then \nthose areas cause the whole sandpile to become \"unstable\" and the sandpile \nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of \nsand to each of its four horizontal or vertical neighbours. Grains are lost \nat the edge of the grid, but otherwise increase the number in neighbouring \ncells by one, whilst decreasing the count in the toppled cell by four in each \ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n\nThe final result is the stable sandpile on the right. \n\n'''Note:''' The order in which cells are toppled does not affect the final result.\n\n;Task:\n* Create a class or datastructure and functions to represent and operate on sandpiles. \n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:\n\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n\n* Show that s3 + s3_id == s3\n* Show that s3_id + s3_id == s3_id\n\n\nShow confirming output here, with your examples.\n\n\n;References:\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian_sandpile_model\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconstexpr size_t sp_rows = 3;\nconstexpr size_t sp_columns = 3;\nconstexpr size_t sp_cells = sp_rows * sp_columns;\nconstexpr int sp_limit = 4;\n\nclass abelian_sandpile {\n friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);\n\npublic:\n abelian_sandpile();\n explicit abelian_sandpile(std::initializer_list init);\n void stabilize();\n bool is_stable() const;\n void topple();\n abelian_sandpile& operator+=(const abelian_sandpile&);\n bool operator==(const abelian_sandpile&);\n\nprivate:\n int& cell_value(size_t row, size_t column) {\n return cells_[cell_index(row, column)];\n }\n static size_t cell_index(size_t row, size_t column) {\n return row * sp_columns + column;\n }\n static size_t row_index(size_t cell_index) {\n return cell_index/sp_columns;\n }\n static size_t column_index(size_t cell_index) {\n return cell_index % sp_columns;\n }\n\n std::array cells_;\n};\n\nabelian_sandpile::abelian_sandpile() {\n cells_.fill(0);\n}\n\nabelian_sandpile::abelian_sandpile(std::initializer_list init) {\n assert(init.size() == sp_cells);\n std::copy(init.begin(), init.end(), cells_.begin());\n}\n\nabelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {\n for (size_t i = 0; i < sp_cells; ++i)\n cells_[i] += other.cells_[i];\n stabilize();\n return *this;\n}\n\nbool abelian_sandpile::operator==(const abelian_sandpile& other) {\n return cells_ == other.cells_;\n}\n\nbool abelian_sandpile::is_stable() const {\n return std::none_of(cells_.begin(), cells_.end(),\n [](int a) { return a >= sp_limit; });\n}\n\nvoid abelian_sandpile::topple() {\n for (size_t i = 0; i < sp_cells; ++i) {\n if (cells_[i] >= sp_limit) {\n cells_[i] -= sp_limit;\n size_t row = row_index(i);\n size_t column = column_index(i);\n if (row > 0)\n ++cell_value(row - 1, column);\n if (row + 1 < sp_rows)\n ++cell_value(row + 1, column);\n if (column > 0)\n ++cell_value(row, column - 1);\n if (column + 1 < sp_columns)\n ++cell_value(row, column + 1);\n break;\n }\n }\n}\n\nvoid abelian_sandpile::stabilize() {\n while (!is_stable())\n topple();\n}\n\nabelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {\n abelian_sandpile c(a);\n c += b;\n return c;\n}\n\nstd::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {\n for (size_t i = 0; i < sp_cells; ++i) {\n if (i > 0)\n out << (as.column_index(i) == 0 ? '\\n' : ' ');\n out << as.cells_[i];\n }\n return out << '\\n';\n}\n\nint main() {\n std::cout << std::boolalpha;\n\n std::cout << \"Avalanche:\\n\";\n abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};\n while (!sp.is_stable()) {\n std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n sp.topple();\n }\n std::cout << sp << \"stable? \" << sp.is_stable() << \"\\n\\n\";\n\n std::cout << \"Commutativity:\\n\";\n abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};\n abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};\n abelian_sandpile sum1(s1 + s2);\n abelian_sandpile sum2(s2 + s1);\n std::cout << \"s1 + s2 equals s2 + s1? \" << (sum1 == sum2) << \"\\n\\n\";\n std::cout << \"s1 + s2 = \\n\" << sum1;\n std::cout << \"\\ns2 + s1 = \\n\" << sum2;\n std::cout << '\\n';\n\n std::cout << \"Identity:\\n\";\n abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};\n abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};\n abelian_sandpile sum3(s3 + s3_id);\n abelian_sandpile sum4(s3_id + s3_id);\n std::cout << \"s3 + s3_id equals s3? \" << (sum3 == s3) << '\\n';\n std::cout << \"s3_id + s3_id equals s3_id? \" << (sum4 == s3_id) << \"\\n\\n\";\n std::cout << \"s3 + s3_id = \\n\" << sum3;\n std::cout << \"\\ns3_id + s3_id = \\n\" << sum4;\n\n return 0;\n}"} {"title": "Abundant odd numbers", "language": "C++ from Go", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::vector divisors(int n) {\n std::vector divs{ 1 };\n std::vector divs2;\n\n for (int i = 2; i*i <= n; i++) {\n if (n%i == 0) {\n int j = n / i;\n divs.push_back(i);\n if (i != j) {\n divs2.push_back(j);\n }\n }\n }\n std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));\n\n return divs;\n}\n\nint sum(const std::vector& divs) {\n return std::accumulate(divs.cbegin(), divs.cend(), 0);\n}\n\nstd::string sumStr(const std::vector& divs) {\n auto it = divs.cbegin();\n auto end = divs.cend();\n std::stringstream ss;\n\n if (it != end) {\n ss << *it;\n it = std::next(it);\n }\n while (it != end) {\n ss << \" + \" << *it;\n it = std::next(it);\n }\n\n return ss.str();\n}\n\nint abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {\n int count = countFrom;\n int n = searchFrom;\n for (; count < countTo; n += 2) {\n auto divs = divisors(n);\n int tot = sum(divs);\n if (tot > n) {\n count++;\n if (printOne && count < countTo) {\n continue;\n }\n auto s = sumStr(divs);\n if (printOne) {\n printf(\"%d < %s = %d\\n\", n, s.c_str(), tot);\n } else {\n printf(\"%2d. %5d < %s = %d\\n\", count, n, s.c_str(), tot);\n }\n }\n }\n return n;\n}\n\nint main() {\n using namespace std;\n\n const int max = 25;\n cout << \"The first \" << max << \" abundant odd numbers are:\\n\";\n int n = abundantOdd(1, 0, 25, false);\n\n cout << \"\\nThe one thousandth abundant odd number is:\\n\";\n abundantOdd(n, 25, 1000, true);\n\n cout << \"\\nThe first abundant odd number above one billion is:\\n\";\n abundantOdd(1e9 + 1, 0, 1, true);\n\n return 0;\n}"} {"title": "Accumulator factory", "language": "C++", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "#include \n\nclass Acc\n{\npublic:\n Acc(int init)\n : _type(intType)\n , _intVal(init)\n {}\n\n Acc(float init)\n : _type(floatType)\n , _floatVal(init)\n {}\n\n int operator()(int x)\n {\n if( _type == intType )\n {\n _intVal += x;\n return _intVal;\n }\n else\n {\n _floatVal += x;\n return static_cast(_floatVal);\n }\n }\n\n float operator()(float x)\n {\n if( _type == intType )\n {\n _floatVal = _intVal + x;\n _type = floatType;\n return _floatVal;\n }\n else\n {\n _floatVal += x;\n return _floatVal;\n }\n }\nprivate:\n enum {floatType, intType} _type;\n float _floatVal;\n int _intVal;\n};\n\nint main()\n{\n Acc a(1);\n a(5);\n Acc(3);\n std::cout << a(2.3f);\n return 0;\n}"} {"title": "Accumulator factory", "language": "C++11", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "// still inside struct Accumulator_\n\t// various operator() implementations provide a de facto multimethod\n\tAccumulator_& operator()(int more)\n\t{\n\t\tif (auto i = CoerceInt(*val_))\n\t\t\tSet(+i + more);\n\t\telse if (auto d = CoerceDouble(*val_))\n\t\t\tSet(+d + more);\n\t\telse\n\t\t\tTHROW(\"Accumulate(int) failed\");\n\t\treturn *this;\n\t}\n\tAccumulator_& operator()(double more)\n\t{\n\t\tif (auto d = CoerceDouble(*val_))\n\t\t\tSet(+d + more);\n\t\telse\n\t\t\tTHROW(\"Accumulate(double) failed\");\n\t\treturn *this;\n\t}\n\tAccumulator_& operator()(const String_& more)\n\t{\n\t\tif (auto s = CoerceString(*val_))\n\t\t\tSet(+s + more);\n\t\telse\n\t\t\tTHROW(\"Accumulate(string) failed\");\n\t\treturn *this;\n\t}\n};\n"} {"title": "Aliquot sequence classifications", "language": "C++", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "#include \n#include \n#include \n\nusing integer = uint64_t;\n\n// See https://en.wikipedia.org/wiki/Divisor_function\ninteger divisor_sum(integer n) {\n integer total = 1, power = 2;\n // Deal with powers of 2 first\n for (; n % 2 == 0; power *= 2, n /= 2)\n total += power;\n // Odd prime factors up to the square root\n for (integer p = 3; p * p <= n; p += 2) {\n integer sum = 1;\n for (power = p; n % p == 0; power *= p, n /= p)\n sum += power;\n total *= sum;\n }\n // If n > 1 then it's prime\n if (n > 1)\n total *= n + 1;\n return total;\n}\n\n// See https://en.wikipedia.org/wiki/Aliquot_sequence\nvoid classify_aliquot_sequence(integer n) {\n constexpr int limit = 16;\n integer terms[limit];\n terms[0] = n;\n std::string classification(\"non-terminating\");\n int length = 1;\n for (int i = 1; i < limit; ++i) {\n ++length;\n terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];\n if (terms[i] == n) {\n classification =\n (i == 1 ? \"perfect\" : (i == 2 ? \"amicable\" : \"sociable\"));\n break;\n }\n int j = 1;\n for (; j < i; ++j) {\n if (terms[i] == terms[i - j])\n break;\n }\n if (j < i) {\n classification = (j == 1 ? \"aspiring\" : \"cyclic\");\n break;\n }\n if (terms[i] == 0) {\n classification = \"terminating\";\n break;\n }\n }\n std::cout << n << \": \" << classification << \", sequence: \" << terms[0];\n for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)\n std::cout << ' ' << terms[i];\n std::cout << '\\n';\n}\n\nint main() {\n for (integer i = 1; i <= 10; ++i)\n classify_aliquot_sequence(i);\n for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,\n 1064, 1488})\n classify_aliquot_sequence(i);\n classify_aliquot_sequence(15355717786080);\n classify_aliquot_sequence(153557177860800);\n return 0;\n}"} {"title": "Amb", "language": "C++", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace hana = boost::hana;\n\n// Define the Amb function. The first parameter is the constraint to be\n// enforced followed by the potential values.\nconstexpr auto Amb(auto constraint, auto&& ...params)\n{\n // create the set of all possible solutions\n auto possibleSolutions = hana::cartesian_product(hana::tuple(params...));\n\n // find one that matches the constraint\n auto foldOperation = [constraint](auto a, auto b)\n {\n bool meetsConstraint = constraint(a);\n return meetsConstraint ? a : b;\n };\n\n return hana::fold_right(possibleSolutions, foldOperation);\n}\n\nvoid AlgebraExample()\n{\n // use a tuple to hold the possible values of each variable\n constexpr hana::tuple x{1, 2, 3};\n constexpr hana::tuple y{7, 6, 4, 5};\n\n // the constraint enforcing x * y == 8\n constexpr auto constraint = [](auto t)\n {\n return t[hana::size_c<0>] * t[hana::size_c<1>] == 8;\n };\n\n // find the solution using the Amb function\n auto result = Amb(constraint, x, y);\n\n cout << \"\\nx = \" << hana::experimental::print(x);\n cout << \"\\ny = \" << hana::experimental::print(y);\n cout << \"\\nx * y == 8: \" << hana::experimental::print(result);\n}\n\nvoid StringExample()\n{\n // the word lists to choose from\n constexpr hana::tuple words1 {\"the\"sv, \"that\"sv, \"a\"sv};\n constexpr hana::tuple words2 {\"frog\"sv, \"elephant\"sv, \"thing\"sv};\n constexpr hana::tuple words3 {\"walked\"sv, \"treaded\"sv, \"grows\"sv};\n constexpr hana::tuple words4 {\"slowly\"sv, \"quickly\"sv};\n\n // the constraint that the first letter of a word is the same as the last\n // letter of the previous word\n constexpr auto constraint = [](const auto t)\n {\n auto adjacent = hana::zip(hana::drop_back(t), hana::drop_front(t));\n return hana::all_of(adjacent, [](auto t)\n {\n return t[hana::size_c<0>].back() == t[hana::size_c<1>].front();\n });\n };\n\n\n // find the solution using the Amb function\n auto wordResult = Amb(constraint, words1, words2, words3, words4);\n\n cout << \"\\n\\nWords 1: \" << hana::experimental::print(words1);\n cout << \"\\nWords 2: \" << hana::experimental::print(words2);\n cout << \"\\nWords 3: \" << hana::experimental::print(words3);\n cout << \"\\nWords 4: \" << hana::experimental::print(words4);\n cout << \"\\nSolution: \" << hana::experimental::print(wordResult) << \"\\n\";\n}\n\nint main()\n{\n AlgebraExample();\n StringExample();\n}\n"} {"title": "Anagrams/Deranged anagrams", "language": "C++", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nbool is_deranged(const std::string& left, const std::string& right)\n{\n return (left.size() == right.size()) &&\n (std::inner_product(left.begin(), left.end(), right.begin(), 0, std::plus(), std::equal_to()) == 0);\n}\n\nint main()\n{\n std::ifstream input(\"unixdict.txt\");\n if (!input) {\n std::cerr << \"can't open input file\\n\";\n return EXIT_FAILURE;\n }\n\n typedef std::set WordList;\n typedef std::map AnagraMap;\n AnagraMap anagrams;\n\n std::pair result;\n size_t longest = 0;\n\n for (std::string value; input >> value; /**/) {\n std::string key(value);\n std::sort(key.begin(), key.end());\n\n if (longest < value.length()) { // is it a long candidate?\n if (0 < anagrams.count(key)) { // is it an anagram?\n for (const auto& prior : anagrams[key]) {\n if (is_deranged(prior, value)) { // are they deranged?\n result = std::make_pair(prior, value);\n longest = value.length();\n }\n }\n }\n }\n anagrams[key].insert(value);\n }\n\n std::cout << result.first << ' ' << result.second << '\\n';\n return EXIT_SUCCESS;\n}"} {"title": "Angle difference between two bearings", "language": "C++", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "#include \n#include \nusing namespace std;\n\ndouble getDifference(double b1, double b2) {\n\tdouble r = fmod(b2 - b1, 360.0);\n\tif (r < -180.0)\n\t\tr += 360.0;\n\tif (r >= 180.0)\n\t\tr -= 360.0;\n\treturn r;\n}\n\nint main()\n{\n\tcout << \"Input in -180 to +180 range\" << endl;\n\tcout << getDifference(20.0, 45.0) << endl;\n\tcout << getDifference(-45.0, 45.0) << endl;\n\tcout << getDifference(-85.0, 90.0) << endl;\n\tcout << getDifference(-95.0, 90.0) << endl;\n\tcout << getDifference(-45.0, 125.0) << endl;\n\tcout << getDifference(-45.0, 145.0) << endl;\n\tcout << getDifference(-45.0, 125.0) << endl;\n\tcout << getDifference(-45.0, 145.0) << endl;\n\tcout << getDifference(29.4803, -88.6381) << endl;\n\tcout << getDifference(-78.3251, -159.036) << endl;\n\t\n\tcout << \"Input in wider range\" << endl;\n\tcout << getDifference(-70099.74233810938, 29840.67437876723) << endl;\n\tcout << getDifference(-165313.6666297357, 33693.9894517456) << endl;\n\tcout << getDifference(1174.8380510598456, -154146.66490124757) << endl;\n\tcout << getDifference(60175.77306795546, 42213.07192354373) << endl;\n\n\treturn 0;\n}"} {"title": "Anti-primes", "language": "C++ from C", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "#include \n\nint countDivisors(int n) {\n if (n < 2) return 1;\n int count = 2; // 1 and n\n for (int i = 2; i <= n/2; ++i) {\n if (n%i == 0) ++count;\n }\n return count;\n}\n\nint main() {\n int maxDiv = 0, count = 0;\n std::cout << \"The first 20 anti-primes are:\" << std::endl;\n for (int n = 1; count < 20; ++n) {\n int d = countDivisors(n);\n if (d > maxDiv) {\n std::cout << n << \" \";\n maxDiv = d;\n count++;\n }\n }\n std::cout << std::endl;\n return 0;\n}"} {"title": "Apply a digital filter (direct form II transposed)", "language": "C++", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "#include \n#include \nusing namespace std;\n\nvoid Filter(const vector &b, const vector &a, const vector &in, vector &out)\n{\n\n\tout.resize(0);\n\tout.resize(in.size());\n\n\tfor(int i=0; i < in.size(); i++)\n\t{\n\t\tfloat tmp = 0.;\n\t\tint j=0;\n\t\tout[i] = 0.f;\n\t\tfor(j=0; j < b.size(); j++)\n\t\t{\n\t\t\tif(i - j < 0) continue;\n\t\t\ttmp += b[j] * in[i-j];\n\t\t}\n\n\t\tfor(j=1; j < a.size(); j++)\n\t\t{\n\t\t\tif(i - j < 0) continue;\n\t\t\ttmp -= a[j]*out[i-j];\n\t\t}\n\t\t\n\t\ttmp /= a[0];\n\t\tout[i] = tmp;\n\t}\n}\n\nint main()\n{\n\tvector sig = {-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973,-1.00700480494,\\\n\t\t-0.404707073677,0.800482325044,0.743500089861,1.01090520172,0.741527555207,\\\n\t\t0.277841675195,0.400833448236,-0.2085993586,-0.172842103641,-0.134316096293,\\\n\t\t0.0259303398477,0.490105989562,0.549391221511,0.9047198589};\n\n\t//Constants for a Butterworth filter (order 3, low pass)\n\tvector a = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17};\n\tvector b = {0.16666667, 0.5, 0.5, 0.16666667};\n\t\n\tvector result;\n\tFilter(b, a, sig, result);\n\n\tfor(size_t i=0;i\n#include \n#include \n\nbool approxEquals(double a, double b, double e) {\n return fabs(a - b) < e;\n}\n\nvoid test(double a, double b) {\n constexpr double epsilon = 1e-18;\n std::cout << std::setprecision(21) << a;\n std::cout << \", \";\n std::cout << std::setprecision(21) << b;\n std::cout << \" => \";\n std::cout << approxEquals(a, b, epsilon) << '\\n';\n}\n\nint main() {\n test(100000000000000.01, 100000000000000.011);\n test(100.01, 100.011);\n test(10000000000000.001 / 10000.0, 1000000000.0000001000);\n test(0.001, 0.0010000001);\n test(0.000000000000000000000101, 0.0);\n test(sqrt(2.0) * sqrt(2.0), 2.0);\n test(-sqrt(2.0) * sqrt(2.0), -2.0);\n test(3.14159265358979323846, 3.14159265358979324);\n return 0;\n}"} {"title": "Archimedean spiral", "language": "C++", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "#include \n#include \n#include \n \nconst int BMP_SIZE = 600;\n \nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass spiral {\npublic:\n spiral() {\n bmp.create( BMP_SIZE, BMP_SIZE );\n }\n void draw( int c, int s ) {\n double a = .2, b = .3, r, x, y;\n int w = BMP_SIZE >> 1;\n HDC dc = bmp.getDC();\n for( double d = 0; d < c * 6.28318530718; d += .002 ) {\n r = a + b * d; x = r * cos( d ); y = r * sin( d );\n SetPixel( dc, ( int )( s * x + w ), ( int )( s * y + w ), 255 );\n }\n // saves the bitmap\n bmp.saveBitmap( \"./spiral.bmp\" );\n }\nprivate:\n myBitmap bmp;\n};\nint main(int argc, char* argv[]) {\n spiral s; s.draw( 16, 8 ); return 0;\n}\n"} {"title": "Arena storage pool", "language": "C++", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "#include \n#include \n#include \n\n// This class basically provides a global stack of pools; it is not thread-safe, and pools must be destructed in reverse order of construction\n// (you definitely want something better in production use :-))\nclass Pool\n{\npublic:\n Pool(std::size_type sz);\n ~Pool();\n static Pool& current() { return *cur; }\n void* allocate(std::size_type sz, std::size_t alignment);\nprivate:\n char* memory; // char* instead of void* enables pointer arithmetic\n char* free;\n char* end;\n Pool* prev;\n static Pool* cur;\n\n // prohibit copying\n Pool(Pool const&); // not implemented\n Pool& operator=(Pool const&); // not implemented\n};\n\nPool* pool::cur = 0;\n\nPool::Pool(std::size_type size):\n memory(static_cast(::operator new(size))),\n free(memory),\n end(memory + size))\n{\n prev = cur;\n cur = this;\n}\n\nPool::~Pool()\n{\n ::operator delete(memory);\n cur = prev;\n}\n\nvoid* Pool::allocate(std::size_t size, std::size_t alignment)\n{\n char* start = free;\n\n // align the pointer\n std::size_t extra = (start - memory) % aligment;\n if (extra != 0)\n {\n extra = alignment - extra;\n }\n\n // test if we can still allocate that much memory\n if (end - free < size + extra)\n throw std::bad_alloc();\n\n // the free memory now starts after the newly allocated object\n free = start + size + extra;\n return start;\n}\n\n// this is just a simple C-like struct, except that it uses a specific allocation/deallocation function.\nstruct X\n{\n int member;\n void* operator new(std::size_t);\n void operator delete(void*) {} // don't deallocate memory for single objects\n};\n\nvoid* X::operator new(std::size_t size)\n{\n // unfortunately C++ doesn't offer a portable way to find out alignment\n // however, using the size as alignment is always safe (although usually wasteful)\n return Pool::current().allocate(size, size);\n}\n\n// Example program\nint main()\n{\n Pool my_pool(3*sizeof(X));\n X* p1 = new X; // uses the allocator function defined above\n X* p2 = new X;\n X* p3 = new X;\n delete p3; // doesn't really deallocate the memory because operator delete has an empty body\n\n try\n {\n X* p4 = new X; // should fail\n assert(false);\n }\n catch(...)\n {\n }\n\n X* p5 = new X[10]; // uses global array allocation routine because we didn't provide operator new[] and operator delete[]\n delete[] p5; // global array deallocation\n\n Pool* my_second_pool(1000); // a large pool\n X* p6 = new X; // allocate a new object from that pool\n X* p7 = new X;\n delete my_second_pool // also deallocates the memory for p6 and p7\n\n} // Here my_pool goes out of scope, deallocating the memory for p1, p2 and p3"} {"title": "Arithmetic-geometric mean", "language": "C++", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "#include\nusing namespace std;\n#define _cin\tios_base::sync_with_stdio(0);\tcin.tie(0);\n#define rep(a, b)\tfor(ll i =a;i<=b;++i)\n\ndouble agm(double a, double g)\t\t//ARITHMETIC GEOMETRIC MEAN\n{\tdouble epsilon = 1.0E-16,a1,g1;\n\tif(a*g<0.0)\n\t{\tcout<<\"Couldn't find arithmetic-geometric mean of these numbers\\n\";\n\t\texit(1);\n\t}\n\twhile(fabs(a-g)>epsilon)\n\t{\ta1 = (a+g)/2.0;\n\t\tg1 = sqrt(a*g);\n\t\ta = a1;\n\t\tg = g1;\n\t}\n\treturn a;\n}\n\nint main()\n{\t_cin; //fast input-output\n\tdouble x, y;\n\tcout<<\"Enter X and Y: \";\t//Enter two numbers\n\tcin>>x>>y;\n\tcout<<\"\\nThe Arithmetic-Geometric Mean of \"<\n\nvoid divisor_count_and_sum(unsigned int n,\n\t\t\t unsigned int& divisor_count,\n\t\t\t unsigned int& divisor_sum)\n{\n divisor_count = 0;\n divisor_sum = 0;\n for (unsigned int i = 1;; i++)\n {\n unsigned int j = n / i;\n if (j < i)\n break;\n if (i * j != n)\n continue;\n divisor_sum += i;\n divisor_count += 1;\n if (i != j)\n {\n divisor_sum += j;\n divisor_count += 1;\n }\n }\n}\n\nint main()\n{\n unsigned int arithmetic_count = 0;\n unsigned int composite_count = 0;\n\n for (unsigned int n = 1; arithmetic_count <= 1000000; n++)\n {\n unsigned int divisor_count;\n unsigned int divisor_sum;\n divisor_count_and_sum(n, divisor_count, divisor_sum);\n unsigned int mean = divisor_sum / divisor_count;\n if (mean * divisor_count != divisor_sum)\n continue;\n arithmetic_count++;\n if (divisor_count > 2)\n composite_count++;\n if (arithmetic_count <= 100)\n {\n // would prefer to use and in C++20\n std::printf(\"%3u \", n);\n if (arithmetic_count % 10 == 0)\n\tstd::printf(\"\\n\");\n }\n if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||\n\t(arithmetic_count == 100000) || (arithmetic_count == 1000000))\n {\n std::printf(\"\\n%uth arithmetic number is %u\\n\", arithmetic_count, n);\n std::printf(\"Number of composite arithmetic numbers <= %u: %u\\n\", n, composite_count);\n }\n }\n return 0;\n}"} {"title": "Array length", "language": "C++", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "std::vector fruitV({ \"apples\", \"oranges\" });\n std::list fruitL({ \"apples\", \"oranges\" });\n std::deque fruitD({ \"apples\", \"oranges\" });\n std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;"} {"title": "Ascending primes", "language": "C++ from C", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "/*\n * Ascending primes\n *\n * Generate and show all primes with strictly ascending decimal digits.\n *\n *\n * Solution\n *\n * We only consider positive numbers in the range 1 to 123456789. We would\n * get 7027260 primes, because there are so many primes smaller than 123456789\n * (see also Wolfram Alpha).On the other hand, there are only 511 distinct\n * nonzero positive integers having their digits arranged in ascending order.\n * Therefore, it is better to start with numbers that have properly arranged\n * digitsand then check if they are prime numbers.The method of generating\n * a sequence of such numbers is not indifferent.We want this sequence to be\n * monotonically increasing, because then additional sorting of results will\n * be unnecessary. It turns out that by using a queue we can easily get the\n * desired effect. Additionally, the algorithm then does not use recursion\n * (although the program probably does not have to comply with the MISRA\n * standard). The problem to be solved is the queue size, the a priori\n * assumption that 1000 is good enough, but a bit magical.\n */\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\nqueue suspected;\nvector primes;\n\n\nbool isPrime(unsigned n)\n{\n if (n == 2)\n {\n return true;\n }\n if (n == 1 || n % 2 == 0)\n {\n return false;\n }\n unsigned root = sqrt(n);\n for (unsigned k = 3; k <= root; k += 2)\n {\n if (n % k == 0)\n {\n return false;\n }\n }\n return true;\n}\n\n\nint main(int argc, char argv[])\n{\n for (unsigned k = 1; k <= 9; k++)\n {\n suspected.push(k);\n }\n\n while (!suspected.empty())\n {\n int n = suspected.front();\n suspected.pop();\n\n if (isPrime(n))\n {\n primes.push_back(n);\n }\n\n // The value of n % 10 gives the least significient digit of n\n //\n for (unsigned k = n % 10 + 1; k <= 9; k++)\n {\n suspected.push(n * 10 + k);\n }\n }\n\n copy(primes.begin(), primes.end(), ostream_iterator(cout, \" \"));\n\n return EXIT_SUCCESS;\n}"} {"title": "Associative array/Merging", "language": "C++", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "#include \n#include \n#include \n\ntemplate\nmap_type merge(const map_type& original, const map_type& update) {\n map_type result(update);\n result.insert(original.begin(), original.end());\n return result;\n}\n\nint main() {\n typedef std::map map;\n map original{\n {\"name\", \"Rocket Skates\"},\n {\"price\", \"12.75\"},\n {\"color\", \"yellow\"}\n };\n map update{\n {\"price\", \"15.25\"},\n {\"color\", \"red\"},\n {\"year\", \"1974\"}\n };\n map merged(merge(original, update));\n for (auto&& i : merged)\n std::cout << \"key: \" << i.first << \", value: \" << i.second << '\\n';\n return 0;\n}"} {"title": "Attractive numbers", "language": "C++ from C", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "#include \n#include \n\n#define MAX 120\n\nusing namespace std;\n\nbool is_prime(int n) { \n if (n < 2) return false;\n if (!(n % 2)) return n == 2;\n if (!(n % 3)) return n == 3;\n int d = 5;\n while (d *d <= n) {\n if (!(n % d)) return false;\n d += 2;\n if (!(n % d)) return false;\n d += 4;\n }\n return true;\n}\n\nint count_prime_factors(int n) { \n if (n == 1) return 0;\n if (is_prime(n)) return 1;\n int count = 0, f = 2;\n while (true) {\n if (!(n % f)) {\n count++;\n n /= f;\n if (n == 1) return count;\n if (is_prime(n)) f = n;\n } \n else if (f >= 3) f += 2;\n else f = 3;\n }\n}\n\nint main() {\n cout << \"The attractive numbers up to and including \" << MAX << \" are:\" << endl;\n for (int i = 1, count = 0; i <= MAX; ++i) {\n int n = count_prime_factors(i);\n if (is_prime(n)) {\n cout << setw(4) << i;\n if (!(++count % 20)) cout << endl;\n }\n }\n cout << endl;\n return 0;\n}"} {"title": "Average loop length", "language": "C++", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "#include \n#include \n#include \n#include \n\n#define MAX_N 20\n#define TIMES 1000000\n\n/**\n * Used to generate a uniform random distribution\n */\nstatic std::random_device rd; //Will be used to obtain a seed for the random number engine\nstatic std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\nstatic std::uniform_int_distribution<> dis;\n\nint randint(int n) {\n int r, rmax = RAND_MAX / n * n;\n dis=std::uniform_int_distribution(0,rmax) ;\n r = dis(gen);\n return r / (RAND_MAX / n);\n}\n\nunsigned long long factorial(size_t n) {\n //Factorial using dynamic programming to memoize the values.\n static std::vectorfactorials{1,1,2};\n\tfor (;factorials.size() <= n;)\n\t factorials.push_back(((unsigned long long) factorials.back())*factorials.size());\n\treturn factorials[n];\n}\n\nlong double expected(size_t n) {\n long double sum = 0;\n for (size_t i = 1; i <= n; i++)\n sum += factorial(n) / pow(n, i) / factorial(n - i);\n return sum;\n}\n\nint test(int n, int times) {\n int i, count = 0;\n for (i = 0; i < times; i++) {\n unsigned int x = 1, bits = 0;\n while (!(bits & x)) {\n count++;\n bits |= x;\n x = static_cast(1 << randint(n));\n }\n }\n return count;\n}\n\nint main() {\n puts(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\");\n\n int n;\n for (n = 1; n <= MAX_N; n++) {\n int cnt = test(n, TIMES);\n long double avg = (double)cnt / TIMES;\n long double theory = expected(static_cast(n));\n long double diff = (avg / theory - 1) * 100;\n printf(\"%2d %8.4f %8.4f %6.3f%%\\n\", n, static_cast(avg), static_cast(theory), static_cast(diff));\n }\n return 0;\n}\n"} {"title": "Averages/Mean angle", "language": "C++ from C#", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include \n#include \n\n#define _USE_MATH_DEFINES\n#include \n\ntemplate\ndouble meanAngle(const C& c) {\n auto it = std::cbegin(c);\n auto end = std::cend(c);\n\n double x = 0.0;\n double y = 0.0;\n double len = 0.0;\n while (it != end) {\n x += cos(*it * M_PI / 180);\n y += sin(*it * M_PI / 180);\n len++;\n\n it = std::next(it);\n }\n\n return atan2(y, x) * 180 / M_PI;\n}\n\nvoid printMean(std::initializer_list init) {\n std::cout << std::fixed << std::setprecision(3) << meanAngle(init) << '\\n';\n}\n\nint main() {\n printMean({ 350, 10 });\n printMean({ 90, 180, 270, 360 });\n printMean({ 10, 20, 30 });\n\n return 0;\n}"} {"title": "Averages/Pythagorean means", "language": "C++", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ndouble toInverse ( int i ) {\n return 1.0 / i ;\n}\n\nint main( ) {\n std::vector numbers ;\n for ( int i = 1 ; i < 11 ; i++ ) \n numbers.push_back( i ) ;\n double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ;\n double geometric_mean =\n pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies( ) ), 0.1 ) ;\n std::vector inverses ;\n inverses.resize( numbers.size( ) ) ;\n std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ; \n double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double!\n std::cout << \"The arithmetic mean is \" << arithmetic_mean << \" , the geometric mean \" \n << geometric_mean << \" and the harmonic mean \" << harmonic_mean << \" !\\n\" ;\n return 0 ;\n}"} {"title": "Averages/Root mean square", "language": "C++", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nint main( ) {\n std::vector numbers ;\n for ( int i = 1 ; i < 11 ; i++ )\n numbers.push_back( i ) ;\n double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast( numbers.size() ) );\n std::cout << \"The quadratic mean of the numbers 1 .. \" << numbers.size() << \" is \" << meansquare << \" !\\n\" ;\n return 0 ;\n}"} {"title": "Babbage problem", "language": "C++", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "#include \n\nint main( ) {\n int current = 0 ;\n while ( ( current * current ) % 1000000 != 269696 ) \n current++ ;\n std::cout << \"The square of \" << current << \" is \" << (current * current) << \" !\\n\" ;\n return 0 ;\n}"} {"title": "Balanced brackets", "language": "C++", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "#include \n#include \n#include \n\nstd::string generate(int n, char left = '[', char right = ']')\n{\n std::string str(std::string(n, left) + std::string(n, right));\n std::random_shuffle(str.begin(), str.end());\n return str;\n}\n\nbool balanced(const std::string &str, char left = '[', char right = ']')\n{\n int count = 0;\n for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)\n {\n if (*it == left)\n count++;\n else if (*it == right)\n if (--count < 0) return false;\n }\n return count == 0;\n}\n\nint main()\n{\n srand(time(NULL)); // seed rng\n for (int i = 0; i < 9; ++i)\n {\n std::string s(generate(i));\n std::cout << (balanced(s) ? \" ok: \" : \"bad: \") << s << \"\\n\";\n }\n}"} {"title": "Balanced ternary", "language": "C++", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nclass BalancedTernary {\nprotected:\n\t// Store the value as a reversed string of +, 0 and - characters\n\tstring value;\n\n\t// Helper function to change a balanced ternary character to an integer\n\tint charToInt(char c) const {\n\t\tif (c == '0')\n\t\t\treturn 0;\n\t\treturn 44 - c;\n\t}\n\n\t// Helper function to negate a string of ternary characters\n\tstring negate(string s) const {\n\t\tfor (int i = 0; i < s.length(); ++i) {\n\t\t\tif (s[i] == '+')\n\t\t\t\ts[i] = '-';\n\t\t\telse if (s[i] == '-')\n\t\t\t\ts[i] = '+';\n\t\t}\n\t\treturn s;\n\t}\n\npublic:\n\t// Default constructor\n\tBalancedTernary() {\n\t\tvalue = \"0\";\n\t}\n\n\t// Construct from a string\n\tBalancedTernary(string s) {\n\t\tvalue = string(s.rbegin(), s.rend());\n\t}\n\n\t// Construct from an integer\n\tBalancedTernary(long long n) {\n\t\tif (n == 0) {\n\t\t\tvalue = \"0\";\n\t\t\treturn;\n\t\t}\n\n\t\tbool neg = n < 0;\n\t\tif (neg) \n\t\t\tn = -n;\n\n\t\tvalue = \"\";\n\t\twhile (n != 0) {\n\t\t\tint r = n % 3;\n\t\t\tif (r == 0)\n\t\t\t\tvalue += \"0\";\n\t\t\telse if (r == 1)\n\t\t\t\tvalue += \"+\";\n\t\t\telse {\n\t\t\t\tvalue += \"-\";\n\t\t\t\t++n;\n\t\t\t}\n\n\t\t\tn /= 3;\n\t\t}\n\n\t\tif (neg)\n\t\t\tvalue = negate(value);\n\t}\n\n\t// Copy constructor\n\tBalancedTernary(const BalancedTernary &n) {\n\t\tvalue = n.value;\n\t}\n\n\t// Addition operators\n\tBalancedTernary operator+(BalancedTernary n) const {\n\t\tn += *this;\n\t\treturn n;\n\t}\n\n\tBalancedTernary& operator+=(const BalancedTernary &n) {\n\t\tstatic char *add = \"0+-0+-0\";\n\t\tstatic char *carry = \"--000++\";\n\n\t\tint lastNonZero = 0;\n\t\tchar c = '0';\n\t\tfor (int i = 0; i < value.length() || i < n.value.length(); ++i) {\n\t\t\tchar a = i < value.length() ? value[i] : '0';\n\t\t\tchar b = i < n.value.length() ? n.value[i] : '0';\n\n\t\t\tint sum = charToInt(a) + charToInt(b) + charToInt(c) + 3;\n\t\t\tc = carry[sum];\n\n\t\t\tif (i < value.length())\n\t\t\t\tvalue[i] = add[sum];\n\t\t\telse\n\t\t\t\tvalue += add[sum];\n\n\t\t\tif (add[sum] != '0')\n\t\t\t\tlastNonZero = i;\n\t\t}\n\n\t\tif (c != '0')\n\t\t\tvalue += c;\n\t\telse\n\t\t\tvalue = value.substr(0, lastNonZero + 1); // Chop off leading zeroes\n\n\t\treturn *this;\n\t}\n\n\t// Negation operator\n\tBalancedTernary operator-() const {\n\t\tBalancedTernary result;\n\t\tresult.value = negate(value);\n\t\treturn result;\n\t}\n\n\t// Subtraction operators\n\tBalancedTernary operator-(const BalancedTernary &n) const {\n\t\treturn operator+(-n);\n\t}\n\n\tBalancedTernary& operator-=(const BalancedTernary &n) {\n\t\treturn operator+=(-n);\n\t}\n\n\t// Multiplication operators\n\tBalancedTernary operator*(BalancedTernary n) const {\n\t\tn *= *this;\n\t\treturn n;\n\t}\n\n\tBalancedTernary& operator*=(const BalancedTernary &n) {\n\t\tBalancedTernary pos = *this;\n\t\tBalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly\n\t\tvalue = \"0\";\n\n\t\tfor (int i = 0; i < n.value.length(); ++i) {\n\t\t\tif (n.value[i] == '+')\n\t\t\t\toperator+=(pos);\n\t\t\telse if (n.value[i] == '-')\n\t\t\t\toperator+=(neg);\n\t\t\tpos.value = '0' + pos.value;\n\t\t\tneg.value = '0' + neg.value;\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\t// Stream output operator\n\tfriend ostream& operator<<(ostream &out, const BalancedTernary &n) {\n\t\tout << n.toString();\n\t\treturn out;\n\t}\n\n\t// Convert to string\n\tstring toString() const {\n\t\treturn string(value.rbegin(), value.rend());\n\t}\n\n\t// Convert to integer\n\tlong long toInt() const {\n\t\tlong long result = 0;\n\t\tfor (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3)\n\t\t\tresult += pow * charToInt(value[i]);\n\t\treturn result;\n\t}\n\n\t// Convert to integer if possible\n\tbool tryInt(long long &out) const {\n\t\tlong long result = 0;\n\t\tbool ok = true;\n\n\t\tfor (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) {\n\t\t\tif (value[i] == '+') {\n\t\t\t\tok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows\n\t\t\t\tresult += pow;\n\t\t\t} else if (value[i] == '-') {\n\t\t\t\tok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows\n\t\t\t\tresult -= pow;\n\t\t\t}\n\t\t}\n\n\t\tif (ok)\n\t\t\tout = result;\n\t\treturn ok;\n\t}\n};\n\nint main() {\n\tBalancedTernary a(\"+-0++0+\");\n\tBalancedTernary b(-436);\n\tBalancedTernary c(\"+-++-\");\n\n\tcout << \"a = \" << a << \" = \" << a.toInt() << endl;\n\tcout << \"b = \" << b << \" = \" << b.toInt() << endl;\n\tcout << \"c = \" << c << \" = \" << c.toInt() << endl;\n\n\tBalancedTernary d = a * (b - c);\n\n\tcout << \"a * (b - c) = \" << d << \" = \" << d.toInt() << endl;\n\n\tBalancedTernary e(\"+++++++++++++++++++++++++++++++++++++++++\");\n\n\tlong long n;\n\tif (e.tryInt(n))\n\t\tcout << \"e = \" << e << \" = \" << n << endl;\n\telse\n\t\tcout << \"e = \" << e << \" is too big to fit in a long long\" << endl;\n\n\treturn 0;\n}\n"} {"title": "Barnsley fern", "language": "C++", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "#include \n#include \n#include \n\nconst int BMP_SIZE = 600, ITERATIONS = static_cast( 15e5 );\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass fern {\npublic:\n void draw() {\n bmp.create( BMP_SIZE, BMP_SIZE );\n float x = 0, y = 0; HDC dc = bmp.getDC();\n int hs = BMP_SIZE >> 1;\n for( int f = 0; f < ITERATIONS; f++ ) {\n SetPixel( dc, hs + static_cast( x * 55.f ), \n BMP_SIZE - 15 - static_cast( y * 55.f ), \n RGB( static_cast( rnd() * 80.f ) + 20, \n static_cast( rnd() * 128.f ) + 128, \n static_cast( rnd() * 80.f ) + 30 ) ); \n getXY( x, y );\n }\n bmp.saveBitmap( \"./bf.bmp\" );\n }\nprivate:\n void getXY( float& x, float& y ) {\n float g, xl, yl;\n g = rnd();\n if( g < .01f ) { xl = 0; yl = .16f * y; } \n else if( g < .07f ) {\n xl = .2f * x - .26f * y;\n yl = .23f * x + .22f * y + 1.6f;\n } else if( g < .14f ) {\n xl = -.15f * x + .28f * y;\n yl = .26f * x + .24f * y + .44f;\n } else {\n xl = .85f * x + .04f * y;\n yl = -.04f * x + .85f * y + 1.6f;\n }\n x = xl; y = yl;\n }\n float rnd() {\n return static_cast( rand() ) / static_cast( RAND_MAX );\n }\n myBitmap bmp;\n};\nint main( int argc, char* argv[]) {\n srand( static_cast( time( 0 ) ) );\n fern f; f.draw(); return 0; \n}\n"} {"title": "Base64 decode data", "language": "C++14", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef unsigned char ubyte;\nconst auto BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nstd::vector encode(const std::vector& source) {\n auto it = source.cbegin();\n auto end = source.cend();\n\n std::vector sink;\n while (it != end) {\n auto b1 = *it++;\n int acc;\n\n sink.push_back(BASE64[b1 >> 2]); // first output (first six bits from b1)\n\n acc = (b1 & 0x3) << 4; // last two bits from b1\n if (it != end) {\n auto b2 = *it++;\n acc |= (b2 >> 4); // first four bits from b2\n\n sink.push_back(BASE64[acc]); // second output\n\n acc = (b2 & 0xF) << 2; // last four bits from b2\n if (it != end) {\n auto b3 = *it++;\n acc |= (b3 >> 6); // first two bits from b3\n\n sink.push_back(BASE64[acc]); // third output\n sink.push_back(BASE64[b3 & 0x3F]); // fouth output (final six bits from b3)\n } else {\n sink.push_back(BASE64[acc]); // third output\n sink.push_back('='); // fourth output (1 byte padding)\n }\n } else {\n sink.push_back(BASE64[acc]); // second output\n sink.push_back('='); // third output (first padding byte)\n sink.push_back('='); // fourth output (second padding byte)\n }\n }\n return sink;\n}\n\nint findIndex(ubyte val) {\n if ('A' <= val && val <= 'Z') {\n return val - 'A';\n }\n if ('a' <= val && val <= 'z') {\n return val - 'a' + 26;\n }\n if ('0' <= val && val <= '9') {\n return val - '0' + 52;\n }\n if ('+' == val) {\n return 62;\n }\n if ('/' == val) {\n return 63;\n }\n return -1;\n}\n\nstd::vector decode(const std::vector& source) {\n if (source.size() % 4 != 0) {\n throw new std::runtime_error(\"Error in size to the decode method\");\n }\n\n auto it = source.cbegin();\n auto end = source.cend();\n\n std::vector sink;\n while (it != end) {\n auto b1 = *it++;\n auto b2 = *it++;\n auto b3 = *it++; // might be first padding byte\n auto b4 = *it++; // might be first or second padding byte\n\n auto i1 = findIndex(b1);\n auto i2 = findIndex(b2);\n auto acc = i1 << 2; // six bits came from the first byte\n acc |= i2 >> 4; // two bits came from the first byte\n\n sink.push_back(acc); // output the first byte\n\n if (b3 != '=') {\n auto i3 = findIndex(b3);\n\n acc = (i2 & 0xF) << 4; // four bits came from the second byte\n acc |= i3 >> 2; // four bits came from the second byte\n\n sink.push_back(acc); // output the second byte\n\n if (b4 != '=') {\n auto i4 = findIndex(b4);\n\n acc = (i3 & 0x3) << 6; // two bits came from the third byte\n acc |= i4; // six bits came from the third byte\n\n sink.push_back(acc); // output the third byte\n }\n }\n }\n return sink;\n}\n\nint main() {\n using namespace std;\n\n string data = \"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo\";\n vector datav{ begin(data), end(data) };\n cout << data << \"\\n\\n\" << decode(datav).data() << endl;\n\n return 0;\n}"} {"title": "Benford's law", "language": "C++", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "//to cope with the big numbers , I used the Class Library for Numbers( CLN ) \n//if used prepackaged you can compile writing \"g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace cln ;\n\nclass NextNum {\npublic :\n NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }\n cl_I operator( )( ) {\n cl_I result = first + second ;\n first = second ;\n second = result ;\n return result ;\n }\nprivate :\n cl_I first ;\n cl_I second ;\n} ;\n\nvoid findFrequencies( const std::vector & fibos , std::map &numberfrequencies ) {\n for ( cl_I bignumber : fibos ) {\n std::ostringstream os ;\n fprintdecimal ( os , bignumber ) ;//from header file cln/integer_io.h\n int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;\n auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;\n if ( ! result.second ) \n\t numberfrequencies[ firstdigit ]++ ;\n }\n}\n\nint main( ) {\n std::vector fibonaccis( 1000 ) ;\n fibonaccis[ 0 ] = 0 ;\n fibonaccis[ 1 ] = 1 ;\n cl_I a = 0 ;\n cl_I b = 1 ;\n //since a and b are passed as references to the generator's constructor\n //they are constantly changed !\n std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;\n std::cout << std::endl ;\n std::map frequencies ;\n findFrequencies( fibonaccis , frequencies ) ;\n std::cout << \" found expected\\n\" ;\n for ( int i = 1 ; i < 10 ; i++ ) {\n double found = static_cast( frequencies[ i ] ) / 1000 ;\n double expected = std::log10( 1 + 1 / static_cast( i )) ;\n std::cout << i << \" :\" << std::setw( 16 ) << std::right << found * 100 << \" %\" ;\n std::cout.precision( 3 ) ;\n std::cout << std::setw( 26 ) << std::right << expected * 100 << \" %\\n\" ;\n }\n return 0 ;\n}\n"} {"title": "Best shuffle", "language": "C++ from Java", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\ntemplate \nclass BestShuffle {\npublic:\n BestShuffle() : rd(), g(rd()) {}\n\n S operator()(const S& s1) {\n S s2 = s1;\n shuffle(s2.begin(), s2.end(), g);\n for (unsigned i = 0; i < s2.length(); i++)\n if (s2[i] == s1[i])\n for (unsigned j = 0; j < s2.length(); j++)\n if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) {\n swap(s2[i], s2[j]);\n break;\n }\n ostringstream os;\n os << s1 << endl << s2 << \" [\" << count(s2, s1) << ']';\n return os.str();\n }\n\nprivate:\n static int count(const S& s1, const S& s2) {\n auto count = 0;\n for (unsigned i = 0; i < s1.length(); i++)\n if (s1[i] == s2[i])\n count++;\n return count;\n }\n\n random_device rd;\n mt19937 g;\n};\n\nint main(int argc, char* arguments[]) {\n BestShuffle> bs;\n for (auto i = 1; i < argc; i++)\n cout << bs(basic_string(arguments[i])) << endl;\n return 0;\n}"} {"title": "Bin given limits", "language": "C++", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::vector bins(const std::vector& limits,\n const std::vector& data) {\n std::vector result(limits.size() + 1, 0);\n for (int n : data) {\n auto i = std::upper_bound(limits.begin(), limits.end(), n);\n ++result[i - limits.begin()];\n }\n return result;\n}\n\nvoid print_bins(const std::vector& limits, const std::vector& bins) {\n size_t n = limits.size();\n if (n == 0)\n return;\n assert(n + 1 == bins.size());\n std::cout << \" < \" << std::setw(3) << limits[0] << \": \"\n << std::setw(2) << bins[0] << '\\n';\n for (size_t i = 1; i < n; ++i)\n std::cout << \">= \" << std::setw(3) << limits[i - 1] << \" and < \"\n << std::setw(3) << limits[i] << \": \" << std::setw(2)\n << bins[i] << '\\n';\n std::cout << \">= \" << std::setw(3) << limits[n - 1] << \" : \"\n << std::setw(2) << bins[n] << '\\n';\n}\n\nint main() {\n const std::vector limits1{23, 37, 43, 53, 67, 83};\n const std::vector data1{\n 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,\n 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,\n 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};\n\n std::cout << \"Example 1:\\n\";\n print_bins(limits1, bins(limits1, data1));\n\n const std::vector limits2{14, 18, 249, 312, 389,\n 392, 513, 591, 634, 720};\n const std::vector data2{\n 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,\n 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,\n 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,\n 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,\n 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,\n 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,\n 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,\n 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,\n 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,\n 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,\n 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,\n 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,\n 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,\n 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,\n 101, 684, 727, 749};\n\n std::cout << \"\\nExample 2:\\n\";\n print_bins(limits2, bins(limits2, data2));\n}"} {"title": "Bioinformatics/Sequence mutation", "language": "C++", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nclass sequence_generator {\npublic:\n sequence_generator();\n std::string generate_sequence(size_t length);\n void mutate_sequence(std::string&);\n static void print_sequence(std::ostream&, const std::string&);\n enum class operation { change, erase, insert };\n void set_weight(operation, unsigned int);\nprivate:\n char get_random_base() {\n return bases_[base_dist_(engine_)];\n }\n operation get_random_operation();\n static const std::array bases_;\n std::mt19937 engine_;\n std::uniform_int_distribution base_dist_;\n std::array operation_weight_;\n unsigned int total_weight_;\n};\n\nconst std::array sequence_generator::bases_{ 'A', 'C', 'G', 'T' };\n\nsequence_generator::sequence_generator() : engine_(std::random_device()()),\n base_dist_(0, bases_.size() - 1),\n total_weight_(operation_weight_.size()) {\n operation_weight_.fill(1);\n}\n\nsequence_generator::operation sequence_generator::get_random_operation() {\n std::uniform_int_distribution op_dist(0, total_weight_ - 1);\n unsigned int n = op_dist(engine_), op = 0, weight = 0;\n for (; op < operation_weight_.size(); ++op) {\n weight += operation_weight_[op];\n if (n < weight)\n break;\n }\n return static_cast(op);\n}\n\nvoid sequence_generator::set_weight(operation op, unsigned int weight) {\n total_weight_ -= operation_weight_[static_cast(op)];\n operation_weight_[static_cast(op)] = weight;\n total_weight_ += weight;\n}\n\nstd::string sequence_generator::generate_sequence(size_t length) {\n std::string sequence;\n sequence.reserve(length);\n for (size_t i = 0; i < length; ++i)\n sequence += get_random_base();\n return sequence;\n}\n\nvoid sequence_generator::mutate_sequence(std::string& sequence) {\n std::uniform_int_distribution dist(0, sequence.length() - 1);\n size_t pos = dist(engine_);\n char b;\n switch (get_random_operation()) {\n case operation::change:\n b = get_random_base();\n std::cout << \"Change base at position \" << pos << \" from \"\n << sequence[pos] << \" to \" << b << '\\n';\n sequence[pos] = b;\n break;\n case operation::erase:\n std::cout << \"Erase base \" << sequence[pos] << \" at position \"\n << pos << '\\n';\n sequence.erase(pos, 1);\n break;\n case operation::insert:\n b = get_random_base();\n std::cout << \"Insert base \" << b << \" at position \"\n << pos << '\\n';\n sequence.insert(pos, 1, b);\n break;\n }\n}\n\nvoid sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {\n constexpr size_t base_count = bases_.size();\n std::array count = { 0 };\n for (size_t i = 0, n = sequence.length(); i < n; ++i) {\n if (i % 50 == 0) {\n if (i != 0)\n out << '\\n';\n out << std::setw(3) << i << \": \";\n }\n out << sequence[i];\n for (size_t j = 0; j < base_count; ++j) {\n if (bases_[j] == sequence[i]) {\n ++count[j];\n break;\n }\n }\n }\n out << '\\n';\n out << \"Base counts:\\n\";\n size_t total = 0;\n for (size_t j = 0; j < base_count; ++j) {\n total += count[j];\n out << bases_[j] << \": \" << count[j] << \", \";\n }\n out << \"Total: \" << total << '\\n';\n}\n\nint main() {\n sequence_generator gen;\n gen.set_weight(sequence_generator::operation::change, 2);\n std::string sequence = gen.generate_sequence(250);\n std::cout << \"Initial sequence:\\n\";\n sequence_generator::print_sequence(std::cout, sequence);\n constexpr int count = 10;\n for (int i = 0; i < count; ++i)\n gen.mutate_sequence(sequence);\n std::cout << \"After \" << count << \" mutations:\\n\";\n sequence_generator::print_sequence(std::cout, sequence);\n return 0;\n}"} {"title": "Bioinformatics/base count", "language": "C++", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nconst std::string DEFAULT_DNA = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\"\n \"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\"\n \"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\"\n \"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\"\n \"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\"\n \"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\"\n \"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\"\n \"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\"\n \"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\"\n \"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\";\n\nclass DnaBase {\npublic:\n DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {\n // Map each character to a counter\n for (auto elm : dna) {\n if (count.find(elm) == count.end())\n count[elm] = 0;\n ++count[elm];\n }\n }\n\n void viewGenome() {\n std::cout << \"Sequence:\" << std::endl;\n std::cout << std::endl;\n int limit = genome.size() / displayWidth;\n if (genome.size() % displayWidth != 0)\n ++limit;\n\n for (int i = 0; i < limit; ++i) {\n int beginPos = i * displayWidth;\n std::cout << std::setw(4) << beginPos << \" :\" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;\n }\n std::cout << std::endl;\n std::cout << \"Base Count\" << std::endl;\n std::cout << \"----------\" << std::endl;\n std::cout << std::endl;\n int total = 0;\n for (auto elm : count) {\n std::cout << std::setw(4) << elm.first << \" : \" << elm.second << std::endl;\n total += elm.second;\n }\n std::cout << std::endl;\n std::cout << \"Total: \" << total << std::endl;\n }\n\nprivate:\n std::string genome;\n std::map count;\n int displayWidth;\n};\n\nint main(void) {\n auto d = new DnaBase();\n d->viewGenome();\n delete d;\n return 0;\n}"} {"title": "Brazilian numbers", "language": "C++ from D", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "#include \n\nbool sameDigits(int n, int b) {\n int f = n % b;\n while ((n /= b) > 0) {\n if (n % b != f) {\n return false;\n }\n }\n return true;\n}\n\nbool isBrazilian(int n) {\n if (n < 7) return false;\n if (n % 2 == 0)return true;\n for (int b = 2; b < n - 1; b++) {\n if (sameDigits(n, b)) {\n return true;\n }\n }\n return false;\n}\n\nbool isPrime(int n) {\n if (n < 2)return false;\n if (n % 2 == 0)return n == 2;\n if (n % 3 == 0)return n == 3;\n int d = 5;\n while (d * d <= n) {\n if (n % d == 0)return false;\n d += 2;\n if (n % d == 0)return false;\n d += 4;\n }\n return true;\n}\n\nint main() {\n for (auto kind : { \"\", \"odd \", \"prime \" }) {\n bool quiet = false;\n int BigLim = 99999;\n int limit = 20;\n std::cout << \"First \" << limit << ' ' << kind << \"Brazillian numbers:\\n\";\n int c = 0;\n int n = 7;\n while (c < BigLim) {\n if (isBrazilian(n)) {\n if (!quiet)std::cout << n << ' ';\n if (++c == limit) {\n std::cout << \"\\n\\n\";\n quiet = true;\n }\n }\n if (quiet && kind != \"\") continue;\n if (kind == \"\") {\n n++;\n }\n else if (kind == \"odd \") {\n n += 2;\n }\n else if (kind == \"prime \") {\n while (true) {\n n += 2;\n if (isPrime(n)) break;\n }\n } else {\n throw new std::runtime_error(\"Unexpected\");\n }\n }\n if (kind == \"\") {\n std::cout << \"The \" << BigLim + 1 << \"th Brazillian number is: \" << n << \"\\n\\n\";\n }\n }\n\n return 0;\n}"} {"title": "Break OO privacy", "language": "C++", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": "#include \n\nclass CWidget; // Forward-declare that we have a class named CWidget.\n\nclass CFactory\n{\n friend class CWidget;\nprivate:\n unsigned int m_uiCount;\npublic:\n CFactory();\n ~CFactory();\n CWidget* GetWidget();\n};\n\nclass CWidget\n{\nprivate:\n CFactory& m_parent;\n\nprivate:\n CWidget(); // Disallow the default constructor.\n CWidget(const CWidget&); // Disallow the copy constructor\n CWidget& operator=(const CWidget&); // Disallow the assignment operator.\npublic:\n CWidget(CFactory& parent);\n ~CWidget();\n};\n\n// CFactory constructors and destructors. Very simple things.\nCFactory::CFactory() : m_uiCount(0) {}\nCFactory::~CFactory() {}\n\n// CFactory method which creates CWidgets.\nCWidget* CFactory::GetWidget()\n{\n // Create a new CWidget, tell it we're its parent.\n return new CWidget(*this);\n}\n\n// CWidget constructor\nCWidget::CWidget(CFactory& parent) : m_parent(parent)\n{\n ++m_parent.m_uiCount;\n\n std::cout << \"Widget spawning. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nCWidget::~CWidget()\n{\n --m_parent.m_uiCount;\n\n std::cout << \"Widget dieing. There are now \" << m_parent.m_uiCount << \" Widgets instanciated.\" << std::endl;\n}\n\nint main()\n{\n CFactory factory;\n\n CWidget* pWidget1 = factory.GetWidget();\n CWidget* pWidget2 = factory.GetWidget();\n delete pWidget1;\n\n CWidget* pWidget3 = factory.GetWidget();\n delete pWidget3;\n delete pWidget2;\n}"} {"title": "Burrows\u2013Wheeler transform", "language": "C++ from C#", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "#include \n#include \n#include \n\nconst int STX = 0x02;\nconst int ETX = 0x03;\n\nvoid rotate(std::string &a) {\n char t = a[a.length() - 1];\n for (int i = a.length() - 1; i > 0; i--) {\n a[i] = a[i - 1];\n }\n a[0] = t;\n}\n\nstd::string bwt(const std::string &s) {\n for (char c : s) {\n if (c == STX || c == ETX) {\n throw std::runtime_error(\"Input can't contain STX or ETX\");\n }\n }\n\n std::string ss;\n ss += STX;\n ss += s;\n ss += ETX;\n\n std::vector table;\n for (size_t i = 0; i < ss.length(); i++) {\n table.push_back(ss);\n rotate(ss);\n }\n //table.sort();\n std::sort(table.begin(), table.end());\n\n std::string out;\n for (auto &s : table) {\n out += s[s.length() - 1];\n }\n return out;\n}\n\nstd::string ibwt(const std::string &r) {\n int len = r.length();\n std::vector table(len);\n for (int i = 0; i < len; i++) {\n for (int j = 0; j < len; j++) {\n table[j] = r[j] + table[j];\n }\n std::sort(table.begin(), table.end());\n }\n for (auto &row : table) {\n if (row[row.length() - 1] == ETX) {\n return row.substr(1, row.length() - 2);\n }\n }\n return {};\n}\n\nstd::string makePrintable(const std::string &s) {\n auto ls = s;\n for (auto &c : ls) {\n if (c == STX) {\n c = '^';\n } else if (c == ETX) {\n c = '|';\n }\n }\n return ls;\n}\n\nint main() {\n auto tests = {\n \"banana\",\n \"appellee\",\n \"dogwood\",\n \"TO BE OR NOT TO BE OR WANT TO BE OR NOT?\",\n \"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\",\n \"\\u0002ABC\\u0003\"\n };\n\n for (auto &test : tests) {\n std::cout << makePrintable(test) << \"\\n\";\n std::cout << \" --> \";\n\n std::string t;\n try {\n t = bwt(test);\n std::cout << makePrintable(t) << \"\\n\";\n } catch (std::runtime_error &e) {\n std::cout << \"Error \" << e.what() << \"\\n\";\n }\n\n std::string r = ibwt(t);\n std::cout << \" --> \" << r << \"\\n\\n\";\n }\n\n return 0;\n}"} {"title": "CSV data manipulation", "language": "C++", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass CSV\n{\npublic:\n CSV(void) : m_nCols( 0 ), m_nRows( 0 )\n {}\n\n bool open( const char* filename, char delim = ',' )\n {\n std::ifstream file( filename );\n \n clear();\n if ( file.is_open() )\n {\n open( file, delim );\n return true;\n }\n\n return false;\n }\n\n void open( std::istream& istream, char delim = ',' )\n {\n std::string line;\n\n clear();\n while ( std::getline( istream, line ) )\n {\n unsigned int nCol = 0;\n std::istringstream lineStream(line);\n std::string cell;\n\n while( std::getline( lineStream, cell, delim ) )\n {\n m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );\n nCol++;\n }\n m_nCols = std::max( m_nCols, nCol );\n m_nRows++;\n }\n }\n\n bool save( const char* pFile, char delim = ',' )\n {\n std::ofstream ofile( pFile );\n if ( ofile.is_open() )\n {\n save( ofile );\n return true;\n }\n return false;\n }\n\n void save( std::ostream& ostream, char delim = ',' )\n {\n for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )\n {\n for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )\n {\n ostream << trim( m_oData[std::make_pair( nCol, nRow )] );\n if ( (nCol+1) < m_nCols )\n {\n ostream << delim;\n }\n else\n {\n ostream << std::endl;\n }\n }\n }\n }\n\n void clear()\n {\n m_oData.clear();\n m_nRows = m_nCols = 0;\n }\n\n std::string& operator()( unsigned int nCol, unsigned int nRow )\n {\n m_nCols = std::max( m_nCols, nCol+1 );\n m_nRows = std::max( m_nRows, nRow+1 );\n return m_oData[std::make_pair(nCol, nRow)];\n }\n\n inline unsigned int GetRows() { return m_nRows; }\n inline unsigned int GetCols() { return m_nCols; }\n\nprivate:\n // trim string for empty spaces in begining and at the end\n inline std::string &trim(std::string &s) \n {\n \n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace))));\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n return s;\n }\n\nprivate:\n std::map, std::string> m_oData;\n\n unsigned int m_nCols;\n unsigned int m_nRows;\n};\n\n\nint main()\n{\n CSV oCSV;\n\n oCSV.open( \"test_in.csv\" );\n oCSV( 0, 0 ) = \"Column0\";\n oCSV( 1, 1 ) = \"100\";\n oCSV( 2, 2 ) = \"200\";\n oCSV( 3, 3 ) = \"300\";\n oCSV( 4, 4 ) = \"400\";\n oCSV.save( \"test_out.csv\" );\n return 0;\n}"} {"title": "CSV to HTML translation", "language": "C++", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "#include \n#include \n#include \n\nstd::string csvToHTML( const std::string & ) ;\n\nint main( ) {\n std::string text = \"Character,Speech\\n\" \n \"The multitude,The messiah! Show us the messiah!\\n\" \n\t\t\t \"Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\\n\" \n\t \"The multitude,Who are you?\\n\" \n\t\t \"Brians mother,I'm his mother; that's who!\\n\" \n\t\t \"The multitude,Behold his mother! Behold his mother!\\n\" ;\n std::cout << csvToHTML( text ) ;\n return 0 ;\n}\n\nstd::string csvToHTML( const std::string & csvtext ) {\n //the order of the regexes and the replacements is decisive!\n std::string regexes[ 5 ] = { \"<\" , \">\" , \"^(.+?)\\\\b\" , \",\" , \"\\n\" } ;\n const char* replacements [ 5 ] = { \"<\" , \">\" , \" $1\" , \"\", \"\\n\" } ; \n boost::regex e1( regexes[ 0 ] ) ; \n std::string tabletext = boost::regex_replace( csvtext , e1 ,\n replacements[ 0 ] , boost::match_default | boost::format_all ) ;\n for ( int i = 1 ; i < 5 ; i++ ) {\n e1.assign( regexes[ i ] ) ;\n tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;\n }\n tabletext = std::string( \"\\n\" ) + tabletext ;\n tabletext.append( \"
\\n\" ) ;\n return tabletext ;\n}"} {"title": "Calculating the value of e", "language": "C++ from C", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\nint main() {\n const double EPSILON = 1.0e-15;\n unsigned long long fact = 1;\n double e = 2.0, e0;\n int n = 2;\n do {\n e0 = e;\n fact *= n++;\n e += 1.0 / fact;\n }\n while (fabs(e - e0) >= EPSILON);\n cout << \"e = \" << setprecision(16) << e << endl;\n return 0;\n}"} {"title": "Call a function", "language": "C++", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "#include \nusing namespace std;\n/* passing arguments by reference */\nvoid f(int &y) /* variable is now passed by reference */\n{\ny++;\n}\nint main()\n{\nint x = 0;\ncout<<\"x = \"<\n#include \n#include \n#include \n\n// Class representing an IPv4 address + netmask length\nclass ipv4_cidr {\npublic:\n ipv4_cidr() {}\n ipv4_cidr(std::uint32_t address, unsigned int mask_length)\n : address_(address), mask_length_(mask_length) {}\n std::uint32_t address() const {\n return address_;\n }\n unsigned int mask_length() const {\n return mask_length_;\n }\n friend std::istream& operator>>(std::istream&, ipv4_cidr&);\nprivate:\n std::uint32_t address_ = 0;\n unsigned int mask_length_ = 0;\n};\n\n// Stream extraction operator, also performs canonicalization\nstd::istream& operator>>(std::istream& in, ipv4_cidr& cidr) {\n int a, b, c, d, m;\n char ch;\n if (!(in >> a >> ch) || a < 0 || a > UINT8_MAX || ch != '.'\n || !(in >> b >> ch) || b < 0 || b > UINT8_MAX || ch != '.'\n || !(in >> c >> ch) || c < 0 || c > UINT8_MAX || ch != '.'\n || !(in >> d >> ch) || d < 0 || d > UINT8_MAX || ch != '/'\n || !(in >> m) || m < 1 || m > 32) {\n in.setstate(std::ios_base::failbit);\n return in;\n }\n uint32_t mask = ~((1 << (32 - m)) - 1);\n uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;\n address &= mask;\n cidr.address_ = address;\n cidr.mask_length_ = m;\n return in;\n}\n\n// Stream insertion operator\nstd::ostream& operator<<(std::ostream& out, const ipv4_cidr& cidr) {\n uint32_t address = cidr.address();\n unsigned int d = address & UINT8_MAX;\n address >>= 8;\n unsigned int c = address & UINT8_MAX;\n address >>= 8;\n unsigned int b = address & UINT8_MAX;\n address >>= 8;\n unsigned int a = address & UINT8_MAX;\n out << a << '.' << b << '.' << c << '.' << d << '/'\n << cidr.mask_length();\n return out;\n}\n\nint main(int argc, char** argv) {\n const char* tests[] = {\n \"87.70.141.1/22\",\n \"36.18.154.103/12\",\n \"62.62.197.11/29\",\n \"67.137.119.181/4\",\n \"161.214.74.21/24\",\n \"184.232.176.184/18\"\n };\n for (auto test : tests) {\n std::istringstream in(test);\n ipv4_cidr cidr;\n if (in >> cidr)\n std::cout << std::setw(18) << std::left << test << \" -> \"\n << cidr << '\\n';\n else\n std::cerr << test << \": invalid CIDR\\n\";\n }\n return 0;\n}"} {"title": "Cantor set", "language": "C++ from D", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "#include \n\nconst int WIDTH = 81;\nconst int HEIGHT = 5;\n\nchar lines[WIDTH*HEIGHT];\n\nvoid cantor(int start, int len, int index) {\n\tint seg = len / 3;\n\tif (seg == 0) return;\n\tfor (int i = index; i < HEIGHT; i++) {\n\t\tfor (int j = start + seg; j < start + seg * 2; j++) {\n\t\t\tint pos = i * WIDTH + j;\n\t\t\tlines[pos] = ' ';\n\t\t}\n\t}\n\tcantor(start, seg, index + 1);\n\tcantor(start + 2 * seg, seg, index + 1);\n}\n\nint main() {\n\t// init\n\tfor (int i = 0; i < WIDTH*HEIGHT; i++) {\n\t\tlines[i] = '*';\n\t}\n\n\t// calculate\n\tcantor(0, WIDTH, 1);\n\n\t// print\n\tfor (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) {\n\t\tprintf(\"%.*s\\n\", WIDTH, lines + i);\n\t}\n\n\treturn 0;\n}"} {"title": "Cartesian product of two or more lists", "language": "C++", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "#include \n#include \n#include \n\nvoid print(const std::vector>& v) {\n std::cout << \"{ \";\n for (const auto& p : v) {\n std::cout << \"(\";\n for (const auto& e : p) {\n std::cout << e << \" \";\n }\n std::cout << \") \";\n }\n std::cout << \"}\" << std::endl;\n}\n\nauto product(const std::vector>& lists) {\n std::vector> result;\n if (std::find_if(std::begin(lists), std::end(lists), \n [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {\n return result;\n }\n for (auto& e : lists[0]) {\n result.push_back({ e });\n }\n for (size_t i = 1; i < lists.size(); ++i) {\n std::vector> temp;\n for (auto& e : result) {\n for (auto f : lists[i]) {\n auto e_tmp = e;\n e_tmp.push_back(f);\n temp.push_back(e_tmp);\n }\n }\n result = temp;\n }\n return result;\n}\n\nint main() {\n std::vector> prods[] = {\n { { 1, 2 }, { 3, 4 } },\n { { 3, 4 }, { 1, 2} },\n { { 1, 2 }, { } },\n { { }, { 1, 2 } },\n { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },\n { { 1, 2, 3 }, { 30 }, { 500, 100 } },\n { { 1, 2, 3 }, { }, { 500, 100 } }\n };\n for (const auto& p : prods) {\n print(product(p));\n }\n std::cin.ignore();\n std::cin.get();\n return 0;\n}"} {"title": "Casting out nines", "language": "C++", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "// Casting Out Nines\n//\n// Nigel Galloway. June 24th., 2012\n//\n#include \nint main() {\n\tint Base = 10;\n\tconst int N = 2;\n\tint c1 = 0;\n\tint c2 = 0;\n\tfor (int k=1; k\nint main() {\n const int N = 15;\n int t[N+2] = {0,1};\n for(int i = 1; i<=N; i++){\n for(int j = i; j>1; j--) t[j] = t[j] + t[j-1];\n t[i+1] = t[i];\n for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1];\n std::cout << t[i+1] - t[i] << \" \";\n }\n return 0;\n}"} {"title": "Catamorphism", "language": "C++", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "#include \n#include \n#include \n#include \n\nint main() {\n\tstd::vector nums = { 1, 2, 3, 4, 5 };\n\tauto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus());\n\tauto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {\n\t\treturn a + 2 * b;\n\t});\n\tstd::cout << \"nums_added: \" << nums_added << std::endl;\n\tstd::cout << \"nums_other: \" << nums_other << std::endl;\n}"} {"title": "Chaocipher", "language": "C++ from C#", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "#include \n\nenum class Mode {\n ENCRYPT,\n DECRYPT,\n};\n\nconst std::string L_ALPHABET = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\";\nconst std::string R_ALPHABET = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\";\n\nstd::string exec(std::string text, Mode mode, bool showSteps = false) {\n auto left = L_ALPHABET;\n auto right = R_ALPHABET;\n auto eText = new char[text.size() + 1];\n auto temp = new char[27];\n\n memset(eText, 0, text.size() + 1);\n memset(temp, 0, 27);\n\n for (size_t i = 0; i < text.size(); i++) {\n if (showSteps) std::cout << left << ' ' << right << '\\n';\n size_t index;\n if (mode == Mode::ENCRYPT) {\n index = right.find(text[i]);\n eText[i] = left[index];\n } else {\n index = left.find(text[i]);\n eText[i] = right[index];\n }\n if (i == text.size() - 1) break;\n\n // permute left\n\n for (int j = index; j < 26; ++j) temp[j - index] = left[j];\n for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j];\n auto store = temp[1];\n for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j];\n temp[13] = store;\n left = temp;\n\n // permurte right\n\n for (int j = index; j < 26; ++j) temp[j - index] = right[j];\n for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j];\n store = temp[0];\n for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j];\n temp[25] = store;\n store = temp[2];\n for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j];\n temp[13] = store;\n right = temp;\n }\n\n return eText;\n}\n\nint main() {\n auto plainText = \"WELLDONEISBETTERTHANWELLSAID\";\n std::cout << \"The original plaintext is : \" << plainText << \"\\n\\n\";\n std::cout << \"The left and right alphabets after each permutation during encryption are :\\n\";\n auto cipherText = exec(plainText, Mode::ENCRYPT, true);\n std::cout << \"\\nThe ciphertext is : \" << cipherText << '\\n';\n auto plainText2 = exec(cipherText, Mode::DECRYPT);\n std::cout << \"\\nThe recovered plaintext is : \" << plainText2 << '\\n';\n\n return 0;\n}"} {"title": "Chaos game", "language": "C++", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "#include \n#include \n#include \n#include \n \nconst int BMP_SIZE = 600;\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n \n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n \n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n \n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n \n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n \n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n \n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n \n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n \n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n \n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n \n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass chaos {\npublic:\n void start() {\n POINT org;\n fillPts(); initialPoint( org ); initColors();\n int cnt = 0, i;\n bmp.create( BMP_SIZE, BMP_SIZE );\n bmp.clear( 255 );\n\n while( cnt++ < 1000000 ) {\n switch( rand() % 6 ) {\n case 0: case 3: i = 0; break;\n case 1: case 5: i = 1; break;\n case 2: case 4: i = 2;\n }\n setPoint( org, myPoints[i], i );\n }\n // --- edit this path --- //\n bmp.saveBitmap( \"F:/st.bmp\" );\n }\nprivate:\n void setPoint( POINT &o, POINT v, int i ) {\n POINT z;\n o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1;\n SetPixel( bmp.getDC(), o.x, o.y, colors[i] );\n }\n void fillPts() {\n int a = BMP_SIZE - 1;\n myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0;\n myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a;\n }\n void initialPoint( POINT& p ) {\n p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );\n p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );\n }\n void initColors() {\n colors[0] = RGB( 255, 0, 0 );\n colors[1] = RGB( 0, 255, 0 );\n colors[2] = RGB( 0, 0, 255 );\n }\n \n myBitmap bmp;\n POINT myPoints[3];\n COLORREF colors[3];\n};\nint main( int argc, char* argv[] ) {\n srand( ( unsigned )time( 0 ) );\n chaos c; c.start();\n return 0;\n}\n"} {"title": "Check output device is a terminal", "language": "C++ from C", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "#if _WIN32\n#include \n#define ISATTY _isatty\n#define FILENO _fileno\n#else\n#include \n#define ISATTY isatty\n#define FILENO fileno\n#endif\n\n#include \n\nint main() {\n if (ISATTY(FILENO(stdout))) {\n std::cout << \"stdout is a tty\\n\";\n } else {\n std::cout << \"stdout is not a tty\\n\";\n }\n\n return 0;\n}"} {"title": "Cheryl's birthday", "language": "C++ from Go", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nconst vector MONTHS = {\n \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"\n};\n\nstruct Birthday {\n int month, day;\n\n friend ostream &operator<<(ostream &, const Birthday &);\n};\n\nostream &operator<<(ostream &out, const Birthday &birthday) {\n return out << MONTHS[birthday.month - 1] << ' ' << birthday.day;\n}\n\ntemplate \nbool monthUniqueIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n int count = 0;\n while (it != end) {\n if (it->month == b.month) {\n count++;\n }\n it = next(it);\n }\n return count == 1;\n}\n\ntemplate \nbool dayUniqueIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n int count = 0;\n while (it != end) {\n if (it->day == b.day) {\n count++;\n }\n it = next(it);\n }\n return count == 1;\n}\n\ntemplate \nbool monthWithUniqueDayIn(const Birthday &b, const C &container) {\n auto it = cbegin(container);\n auto end = cend(container);\n while (it != end) {\n if (it->month == b.month && dayUniqueIn(*it, container)) {\n return true;\n }\n it = next(it);\n }\n return false;\n}\n\nint main() {\n vector choices = {\n {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18},\n {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17},\n };\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n vector filtered;\n for (auto bd : choices) {\n if (!monthUniqueIn(bd, choices)) {\n filtered.push_back(bd);\n }\n }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n vector filtered2;\n for (auto bd : filtered) {\n if (!monthWithUniqueDayIn(bd, filtered)) {\n filtered2.push_back(bd);\n }\n }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n vector filtered3;\n for (auto bd : filtered2) {\n if (dayUniqueIn(bd, filtered2)) {\n filtered3.push_back(bd);\n }\n }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n vector filtered4;\n for (auto bd : filtered3) {\n if (monthUniqueIn(bd, filtered3)) {\n filtered4.push_back(bd);\n }\n }\n\n if (filtered4.size() == 1) {\n cout << \"Cheryl's birthday is \" << filtered4[0] << '\\n';\n } else {\n cout << \"Something went wrong!\\n\";\n }\n\n return 0;\n}"} {"title": "Chinese remainder theorem", "language": "C++", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "// Requires C++17\n#include \n#include \n#include \n#include \n\ntemplate _Ty mulInv(_Ty a, _Ty b) {\n\t_Ty b0 = b;\n\t_Ty x0 = 0;\n\t_Ty x1 = 1;\n\n\tif (b == 1) {\n\t\treturn 1;\n\t}\n\n\twhile (a > 1) {\n\t\t_Ty q = a / b;\n\t\t_Ty amb = a % b;\n\t\ta = b;\n\t\tb = amb;\n\n\t\t_Ty xqx = x1 - q * x0;\n\t\tx1 = x0;\n\t\tx0 = xqx;\n\t}\n\n\tif (x1 < 0) {\n\t\tx1 += b0;\n\t}\n\n\treturn x1;\n}\n\ntemplate _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {\n\t_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });\n\n\t_Ty sm = 0;\n\tfor (int i = 0; i < n.size(); i++) {\n\t\t_Ty p = prod / n[i];\n\t\tsm += a[i] * mulInv(p, n[i]) * p;\n\t}\n\n\treturn sm % prod;\n}\n\nint main() {\n\tvector n = { 3, 5, 7 };\n\tvector a = { 2, 3, 2 };\n \n\tcout << chineseRemainder(n,a) << endl;\n \n\treturn 0;\n}"} {"title": "Chinese zodiac", "language": "C++", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "#include \n#include \n\nusing namespace std;\n\nconst string animals[]={\"Rat\",\"Ox\",\"Tiger\",\"Rabbit\",\"Dragon\",\"Snake\",\"Horse\",\"Goat\",\"Monkey\",\"Rooster\",\"Dog\",\"Pig\"};\nconst string elements[]={\"Wood\",\"Fire\",\"Earth\",\"Metal\",\"Water\"};\n\nstring getElement(int year)\n{\n int element = floor((year-4)%10/2);\n return elements[element];\n}\n\nstring getAnimal(int year)\n{\n return animals[(year-4)%12];\n}\n\nstring getYY(int year)\n{\n if(year%2==0)\n {\n return \"yang\";\n }\n else\n {\n return \"yin\";\n }\n}\n\nint main()\n{\n int years[]={1935,1938,1968,1972,1976,2017};\n //the zodiac cycle didnt start until 4 CE, so years <4 shouldnt be valid\n for(int i=0;i<6;i++)\n {\n cout << years[i] << \" is the year of the \" << getElement(years[i]) << \" \" << getAnimal(years[i]) << \" (\" << getYY(years[i]) << \").\" << endl;\n }\n return 0;\n}"} {"title": "Church numerals", "language": "C++", "task": "In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n\n", "solution": "#include \n\n// apply the function zero times (return an identity function)\nauto Zero = [](auto){ return [](auto x){ return x; }; };\n\n// define Church True and False\nauto True = [](auto a){ return [=](auto){ return a; }; };\nauto False = [](auto){ return [](auto b){ return b; }; };\n\n// apply the function f one more time\nauto Successor(auto a) {\n return [=](auto f) {\n return [=](auto x) {\n return a(f)(f(x));\n };\n };\n}\n\n// apply the function a times after b times\nauto Add(auto a, auto b) {\n return [=](auto f) {\n return [=](auto x) {\n return a(f)(b(f)(x));\n };\n };\n}\n\n// apply the function a times b times\nauto Multiply(auto a, auto b) {\n return [=](auto f) {\n return a(b(f));\n };\n}\n\n// apply the function a^b times\nauto Exp(auto a, auto b) {\n return b(a);\n}\n\n// check if a number is zero\nauto IsZero(auto a){\n return a([](auto){ return False; })(True);\n}\n\n// apply the function f one less time\nauto Predecessor(auto a) {\n return [=](auto f) {\n return [=](auto x) {\n return a(\n [=](auto g) {\n return [=](auto h){\n return h(g(f));\n };\n }\n )([=](auto){ return x; })([](auto y){ return y; });\n };\n };\n}\n\n// apply the Predecessor function b times to a\nauto Subtract(auto a, auto b) {\n {\n return b([](auto c){ return Predecessor(c); })(a);\n };\n}\n\nnamespace\n{\n // helper functions for division.\n\n // end the recusrion\n auto Divr(decltype(Zero), auto) {\n return Zero;\n }\n\n // count how many times b can be subtracted from a\n auto Divr(auto a, auto b) {\n auto a_minus_b = Subtract(a, b);\n auto isZero = IsZero(a_minus_b);\n\n // normalize all Church zeros to be the same (intensional equality).\n // In this implemetation, Church numerals have extensional equality\n // but not intensional equality. '6 - 3' and '4 - 1' have extensional\n // equality because they will both cause a function to be called\n // three times but due to the static type system they do not have\n // intensional equality. Internally the two numerals are represented\n // by different lambdas. Normalize all Church zeros (1 - 1, 2 - 2, etc.)\n // to the same zero (Zero) so it will match the function that end the\n // recursion.\n return isZero\n (Zero)\n (Successor(Divr(isZero(Zero)(a_minus_b), b)));\n }\n}\n\n// apply the function a / b times\nauto Divide(auto a, auto b) {\n return Divr(Successor(a), b);\n}\n\n// create a Church numeral from an integer at compile time\ntemplate constexpr auto ToChurch() {\n if constexpr(N<=0) return Zero;\n else return Successor(ToChurch());\n}\n\n// use an increment function to convert the Church number to an integer\nint ToInt(auto church) {\n return church([](int n){ return n + 1; })(0);\n}\n\nint main() {\n // show some examples\n auto three = Successor(Successor(Successor(Zero)));\n auto four = Successor(three);\n auto six = ToChurch<6>();\n auto ten = ToChurch<10>();\n auto thousand = Exp(ten, three);\n\n std::cout << \"\\n 3 + 4 = \" << ToInt(Add(three, four));\n std::cout << \"\\n 3 * 4 = \" << ToInt(Multiply(three, four));\n std::cout << \"\\n 3^4 = \" << ToInt(Exp(three, four));\n std::cout << \"\\n 4^3 = \" << ToInt(Exp(four, three));\n std::cout << \"\\n 0^0 = \" << ToInt(Exp(Zero, Zero));\n std::cout << \"\\n 4 - 3 = \" << ToInt(Subtract(four, three));\n std::cout << \"\\n 3 - 4 = \" << ToInt(Subtract(three, four));\n std::cout << \"\\n 6 / 3 = \" << ToInt(Divide(six, three));\n std::cout << \"\\n 3 / 6 = \" << ToInt(Divide(three, six));\n auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));\n auto looloolool = Successor(looloolooo);\n std::cout << \"\\n 10^9 + 10^6 + 10^3 + 1 = \" << ToInt(looloolool);\n\n // calculate the golden ratio by using a Church numeral to\n // apply the funtion 'f(x) = 1 + 1/x' a thousand times\n std::cout << \"\\n golden ratio = \" <<\n thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << \"\\n\";\n}\n"} {"title": "Circles of given radius through two points", "language": "C++11", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "#include \n#include \n#include \n\nstruct point { double x, y; };\n\nbool operator==(const point& lhs, const point& rhs)\n{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }\n\nenum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };\n\nusing result_t = std::tuple;\n\ndouble distance(point l, point r)\n{ return std::hypot(l.x - r.x, l.y - r.y); }\n\nresult_t find_circles(point p1, point p2, double r)\n{\n point ans1 { 1/0., 1/0.}, ans2 { 1/0., 1/0.};\n if (p1 == p2) {\n if(r == 0.) return std::make_tuple(ONE_COINCEDENT, p1, p2 );\n else return std::make_tuple(INFINITE, ans1, ans2);\n }\n point center { p1.x/2 + p2.x/2, p1.y/2 + p2.y/2};\n double half_distance = distance(center, p1);\n if(half_distance > r) return std::make_tuple(NONE, ans1, ans2);\n if(half_distance - r == 0) return std::make_tuple(ONE_DIAMETER, center, ans2);\n double root = sqrt(pow(r, 2.l) - pow(half_distance, 2.l)) / distance(p1, p2);\n ans1.x = center.x + root * (p1.y - p2.y);\n ans1.y = center.y + root * (p2.x - p1.x);\n ans2.x = center.x - root * (p1.y - p2.y);\n ans2.y = center.y - root * (p2.x - p1.x);\n return std::make_tuple(TWO, ans1, ans2);\n}\n\nvoid print(result_t result, std::ostream& out = std::cout)\n{\n point r1, r2; result_category res;\n std::tie(res, r1, r2) = result;\n switch(res) {\n case NONE:\n out << \"There are no solutions, points are too far away\\n\"; break;\n case ONE_COINCEDENT: case ONE_DIAMETER:\n out << \"Only one solution: \" << r1.x << ' ' << r1.y << '\\n'; break;\n case INFINITE:\n out << \"Infinitely many circles can be drawn\\n\"; break;\n case TWO:\n out << \"Two solutions: \" << r1.x << ' ' << r1.y << \" and \" << r2.x << ' ' << r2.y << '\\n'; break;\n }\n}\n\nint main()\n{\n constexpr int size = 5;\n const point points[size*2] = {\n {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000},\n {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345},\n {0.1234, 0.9876}, {0.1234, 0.9876}\n };\n const double radius[size] = {2., 1., 2., .5, 0.};\n\n for(int i = 0; i < size; ++i)\n print(find_circles(points[i*2], points[i*2 + 1], radius[i]));\n}"} {"title": "Cistercian numerals", "language": "C++ from Go", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "#include \n#include \n\ntemplate\nusing FixedSquareGrid = std::array, S>;\n\nstruct Cistercian {\npublic:\n Cistercian() {\n initN();\n }\n\n Cistercian(int v) {\n initN();\n draw(v);\n }\n\n Cistercian &operator=(int v) {\n initN();\n draw(v);\n }\n\n friend std::ostream &operator<<(std::ostream &, const Cistercian &);\n\nprivate:\n FixedSquareGrid canvas;\n\n void initN() {\n for (auto &row : canvas) {\n row.fill(' ');\n row[5] = 'x';\n }\n }\n\n void horizontal(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r][c] = 'x';\n }\n }\n\n void vertical(size_t r1, size_t r2, size_t c) {\n for (size_t r = r1; r <= r2; r++) {\n canvas[r][c] = 'x';\n }\n }\n\n void diagd(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r + c - c1][c] = 'x';\n }\n }\n\n void diagu(size_t c1, size_t c2, size_t r) {\n for (size_t c = c1; c <= c2; c++) {\n canvas[r - c + c1][c] = 'x';\n }\n }\n\n void drawOnes(int v) {\n switch (v) {\n case 1:\n horizontal(6, 10, 0);\n break;\n case 2:\n horizontal(6, 10, 4);\n break;\n case 3:\n diagd(6, 10, 0);\n break;\n case 4:\n diagu(6, 10, 4);\n break;\n case 5:\n drawOnes(1);\n drawOnes(4);\n break;\n case 6:\n vertical(0, 4, 10);\n break;\n case 7:\n drawOnes(1);\n drawOnes(6);\n break;\n case 8:\n drawOnes(2);\n drawOnes(6);\n break;\n case 9:\n drawOnes(1);\n drawOnes(8);\n break;\n default:\n break;\n }\n }\n\n void drawTens(int v) {\n switch (v) {\n case 1:\n horizontal(0, 4, 0);\n break;\n case 2:\n horizontal(0, 4, 4);\n break;\n case 3:\n diagu(0, 4, 4);\n break;\n case 4:\n diagd(0, 4, 0);\n break;\n case 5:\n drawTens(1);\n drawTens(4);\n break;\n case 6:\n vertical(0, 4, 0);\n break;\n case 7:\n drawTens(1);\n drawTens(6);\n break;\n case 8:\n drawTens(2);\n drawTens(6);\n break;\n case 9:\n drawTens(1);\n drawTens(8);\n break;\n default:\n break;\n }\n }\n\n void drawHundreds(int hundreds) {\n switch (hundreds) {\n case 1:\n horizontal(6, 10, 14);\n break;\n case 2:\n horizontal(6, 10, 10);\n break;\n case 3:\n diagu(6, 10, 14);\n break;\n case 4:\n diagd(6, 10, 10);\n break;\n case 5:\n drawHundreds(1);\n drawHundreds(4);\n break;\n case 6:\n vertical(10, 14, 10);\n break;\n case 7:\n drawHundreds(1);\n drawHundreds(6);\n break;\n case 8:\n drawHundreds(2);\n drawHundreds(6);\n break;\n case 9:\n drawHundreds(1);\n drawHundreds(8);\n break;\n default:\n break;\n }\n }\n\n void drawThousands(int thousands) {\n switch (thousands) {\n case 1:\n horizontal(0, 4, 14);\n break;\n case 2:\n horizontal(0, 4, 10);\n break;\n case 3:\n diagd(0, 4, 10);\n break;\n case 4:\n diagu(0, 4, 14);\n break;\n case 5:\n drawThousands(1);\n drawThousands(4);\n break;\n case 6:\n vertical(10, 14, 0);\n break;\n case 7:\n drawThousands(1);\n drawThousands(6);\n break;\n case 8:\n drawThousands(2);\n drawThousands(6);\n break;\n case 9:\n drawThousands(1);\n drawThousands(8);\n break;\n default:\n break;\n }\n }\n\n void draw(int v) {\n int thousands = v / 1000;\n v %= 1000;\n\n int hundreds = v / 100;\n v %= 100;\n\n int tens = v / 10;\n int ones = v % 10;\n\n if (thousands > 0) {\n drawThousands(thousands);\n }\n if (hundreds > 0) {\n drawHundreds(hundreds);\n }\n if (tens > 0) {\n drawTens(tens);\n }\n if (ones > 0) {\n drawOnes(ones);\n }\n }\n};\n\nstd::ostream &operator<<(std::ostream &os, const Cistercian &c) {\n for (auto &row : c.canvas) {\n for (auto cell : row) {\n os << cell;\n }\n os << '\\n';\n }\n return os;\n}\n\nint main() {\n for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {\n std::cout << number << \":\\n\";\n\n Cistercian c(number);\n std::cout << c << '\\n';\n }\n\n return 0;\n}"} {"title": "Closures/Value capture", "language": "C++11", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "#include \n#include \n#include \n\nint main() {\n std::vector > funcs;\n for (int i = 0; i < 10; i++)\n funcs.push_back([=]() { return i * i; });\n for ( std::function f : funcs ) \n std::cout << f( ) << std::endl ; \n return 0;\n}"} {"title": "Colour bars/Display", "language": "C++", "task": "Display a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* the system palette, or \n:::* the sequence of colors: \n::::::* black\n::::::* red\n::::::* green\n::::::* blue\n::::::* magenta\n::::::* cyan\n::::::* yellow\n::::::* white\n\n", "solution": "#include \n#include \"colorbars.h\"\n\nMyWidget::MyWidget( ) :\n width( 640 ) ,\n height( 240 ) ,\n colornumber( 8 ) {\n setGeometry( 0, 0 , width , height ) ;\n}\n\nvoid MyWidget::paintEvent ( QPaintEvent * ) {\n int rgbtriplets[ ] = { 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 0 , \n 0 , 0 , 255 , 255 , 0 , 255 , 0 , 255 , 255 , 255 , 255 , 0 ,\n 255 , 255 , 255 } ; \n QPainter myPaint( this ) ;\n int rectwidth = width / colornumber ; //width of one rectangle\n int xstart = 1 ; //x coordinate of the first rectangle\n int offset = -1 ; //to allow for ++offset to define the red value even in the first run of the loop below\n for ( int i = 0 ; i < colornumber ; i++ ) {\n QColor rectColor ;\n rectColor.setRed( rgbtriplets[ ++offset ] ) ;\n rectColor.setGreen( rgbtriplets[ ++offset ] ) ;\n rectColor.setBlue( rgbtriplets[ ++offset ] ) ;\n myPaint.fillRect( xstart , 0 , rectwidth , height - 1 , rectColor ) ;\n xstart += rectwidth + 1 ;\n }\n}"} {"title": "Comma quibbling", "language": "C++", "task": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "#include \n\ntemplate\nvoid quibble(std::ostream& o, T i, T e) {\n o << \"{\";\n if (e != i) {\n T n = i++;\n const char* more = \"\";\n while (e != i) {\n o << more << *n;\n more = \", \";\n n = i++;\n }\n o << (*more?\" and \":\"\") << *n;\n }\n o << \"}\";\n}\n\nint main(int argc, char** argv) {\n char const* a[] = {\"ABC\",\"DEF\",\"G\",\"H\"};\n for (int i=0; i<5; i++) {\n quibble(std::cout, a, a+i);\n std::cout << std::endl;\n }\n return 0;\n}"} {"title": "Command-line arguments", "language": "C++", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "#include \n\nint main(int argc, const char* argv[]) {\n std::cout << \"This program is named \" << argv[0] << '\\n'\n << \"There are \" << argc - 1 << \" arguments given.\\n\";\n for (int i = 1; i < argc; ++i)\n std::cout << \"The argument #\" << i << \" is \" << argv[i] << '\\n';\n}"} {"title": "Compare a list of strings", "language": "C++", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "Assuming that the strings variable is of type T<std::string> where T is an ordered STL container such as std::vector:\n\n"} {"title": "Compare a list of strings", "language": "C++ 11", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "#include \n#include \n\n// Bug: calling operator++ on an empty collection invokes undefined behavior.\nstd::all_of( ++(strings.begin()), strings.end(),\n [&](std::string a){ return a == strings.front(); } ) // All equal\n\nstd::is_sorted( strings.begin(), strings.end(),\n [](std::string a, std::string b){ return !(b < a); }) ) // Strictly ascending"} {"title": "Compile-time calculation", "language": "C++", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "#include \n\ntemplate struct Fac\n{\n static const int result = i * Fac::result;\n};\n\ntemplate<> struct Fac<1>\n{\n static const int result = 1;\n};\n\n\nint main()\n{\n std::cout << \"10! = \" << Fac<10>::result << \"\\n\";\n return 0;\n}"} {"title": "Compile-time calculation", "language": "C++11", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "#include \n\nconstexpr int factorial(int n) {\n return n ? (n * factorial(n - 1)) : 1;\n}\n\nconstexpr int f10 = factorial(10);\n\nint main() {\n printf(\"%d\\n\", f10);\n return 0;\n}"} {"title": "Compiler/lexical analyzer", "language": "C++", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "#include // std::from_chars\n#include // file_to_string, string_to_file\n#include // std::invoke\n#include // std::setw\n#include // std::left\n#include \n#include // keywords\n#include \n#include \n#include // std::forward\n#include // TokenVal\n\nusing namespace std;\n\n// =====================================================================================================================\n// Machinery\n// =====================================================================================================================\nstring file_to_string (const string& path)\n{\n // Open file\n ifstream file {path, ios::in | ios::binary | ios::ate};\n if (!file) throw (errno);\n\n // Allocate string memory\n string contents;\n contents.resize(file.tellg());\n\n // Read file contents into string\n file.seekg(0);\n file.read(contents.data(), contents.size());\n\n return contents;\n}\n\nvoid string_to_file (const string& path, string contents)\n{\n ofstream file {path, ios::out | ios::binary};\n if (!file) throw (errno);\n\n file.write(contents.data(), contents.size());\n}\n\ntemplate \nvoid with_IO (string source, string destination, F&& f)\n{\n string input;\n\n if (source == \"stdin\") getline(cin, input);\n else input = file_to_string(source);\n\n string output = invoke(forward(f), input);\n\n if (destination == \"stdout\") cout << output;\n else string_to_file(destination, output);\n}\n\n// Add escaped newlines and backslashes back in for printing\nstring sanitize (string s)\n{\n for (auto i = 0u; i < s.size(); ++i)\n {\n if (s[i] == '\\n') s.replace(i++, 1, \"\\\\n\");\n else if (s[i] == '\\\\') s.replace(i++, 1, \"\\\\\\\\\");\n }\n\n return s;\n}\n\nclass Scanner\n{\npublic:\n const char* pos;\n int line = 1;\n int column = 1;\n\n Scanner (const char* source) : pos {source} {}\n\n inline char peek () { return *pos; }\n\n void advance ()\n {\n if (*pos == '\\n') { ++line; column = 1; }\n else ++column;\n\n ++pos;\n }\n\n char next ()\n {\n advance();\n return peek();\n }\n\n void skip_whitespace ()\n {\n while (isspace(static_cast(peek())))\n advance();\n }\n}; // class Scanner\n\n\n// =====================================================================================================================\n// Tokens\n// =====================================================================================================================\nenum class TokenName\n{\n OP_MULTIPLY, OP_DIVIDE, OP_MOD, OP_ADD, OP_SUBTRACT, OP_NEGATE,\n OP_LESS, OP_LESSEQUAL, OP_GREATER, OP_GREATEREQUAL, OP_EQUAL, OP_NOTEQUAL,\n OP_NOT, OP_ASSIGN, OP_AND, OP_OR,\n LEFTPAREN, RIGHTPAREN, LEFTBRACE, RIGHTBRACE, SEMICOLON, COMMA,\n KEYWORD_IF, KEYWORD_ELSE, KEYWORD_WHILE, KEYWORD_PRINT, KEYWORD_PUTC,\n IDENTIFIER, INTEGER, STRING,\n END_OF_INPUT, ERROR\n};\n\nusing TokenVal = variant;\n\nstruct Token\n{\n TokenName name;\n TokenVal value;\n int line;\n int column;\n};\n\n\nconst char* to_cstring (TokenName name)\n{\n static const char* s[] =\n {\n \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\", \"Op_subtract\", \"Op_negate\",\n \"Op_less\", \"Op_lessequal\", \"Op_greater\", \"Op_greaterequal\", \"Op_equal\", \"Op_notequal\",\n \"Op_not\", \"Op_assign\", \"Op_and\", \"Op_or\",\n \"LeftParen\", \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\",\n \"Keyword_if\", \"Keyword_else\", \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\",\n \"Identifier\", \"Integer\", \"String\",\n \"End_of_input\", \"Error\"\n };\n\n return s[static_cast(name)];\n}\n\n\nstring to_string (Token t)\n{\n ostringstream out;\n out << setw(2) << t.line << \" \" << setw(2) << t.column << \" \";\n\n switch (t.name)\n {\n case (TokenName::IDENTIFIER) : out << \"Identifier \" << get(t.value); break;\n case (TokenName::INTEGER) : out << \"Integer \" << left << get(t.value); break;\n case (TokenName::STRING) : out << \"String \\\"\" << sanitize(get(t.value)) << '\"'; break;\n case (TokenName::END_OF_INPUT) : out << \"End_of_input\"; break;\n case (TokenName::ERROR) : out << \"Error \" << get(t.value); break;\n default : out << to_cstring(t.name);\n }\n\n out << '\\n';\n\n return out.str();\n}\n\n\n// =====================================================================================================================\n// Lexer\n// =====================================================================================================================\nclass Lexer\n{\npublic:\n Lexer (const char* source) : s {source}, pre_state {s} {}\n\n bool has_more () { return s.peek() != '\\0'; }\n\n Token next_token ()\n {\n s.skip_whitespace();\n\n pre_state = s;\n\n switch (s.peek())\n {\n case '*' : return simply(TokenName::OP_MULTIPLY);\n case '%' : return simply(TokenName::OP_MOD);\n case '+' : return simply(TokenName::OP_ADD);\n case '-' : return simply(TokenName::OP_SUBTRACT);\n case '{' : return simply(TokenName::LEFTBRACE);\n case '}' : return simply(TokenName::RIGHTBRACE);\n case '(' : return simply(TokenName::LEFTPAREN);\n case ')' : return simply(TokenName::RIGHTPAREN);\n case ';' : return simply(TokenName::SEMICOLON);\n case ',' : return simply(TokenName::COMMA);\n case '&' : return expect('&', TokenName::OP_AND);\n case '|' : return expect('|', TokenName::OP_OR);\n case '<' : return follow('=', TokenName::OP_LESSEQUAL, TokenName::OP_LESS);\n case '>' : return follow('=', TokenName::OP_GREATEREQUAL, TokenName::OP_GREATER);\n case '=' : return follow('=', TokenName::OP_EQUAL, TokenName::OP_ASSIGN);\n case '!' : return follow('=', TokenName::OP_NOTEQUAL, TokenName::OP_NOT);\n case '/' : return divide_or_comment();\n case '\\'' : return char_lit();\n case '\"' : return string_lit();\n\n default : if (is_id_start(s.peek())) return identifier();\n if (is_digit(s.peek())) return integer_lit();\n return error(\"Unrecognized character '\", s.peek(), \"'\");\n\n case '\\0' : return make_token(TokenName::END_OF_INPUT);\n }\n }\n\n\nprivate:\n Scanner s;\n Scanner pre_state;\n static const map keywords;\n\n\n template \n Token error (Args&&... ostream_args)\n {\n string code {pre_state.pos, (string::size_type) s.column - pre_state.column};\n\n ostringstream msg;\n (msg << ... << forward(ostream_args)) << '\\n'\n << string(28, ' ') << \"(\" << s.line << \", \" << s.column << \"): \" << code;\n\n if (s.peek() != '\\0') s.advance();\n\n return make_token(TokenName::ERROR, msg.str());\n }\n\n\n inline Token make_token (TokenName name, TokenVal value = 0)\n {\n return {name, value, pre_state.line, pre_state.column};\n }\n\n\n Token simply (TokenName name)\n {\n s.advance();\n return make_token(name);\n }\n\n\n Token expect (char expected, TokenName name)\n {\n if (s.next() == expected) return simply(name);\n else return error(\"Unrecognized character '\", s.peek(), \"'\");\n }\n\n\n Token follow (char expected, TokenName ifyes, TokenName ifno)\n {\n if (s.next() == expected) return simply(ifyes);\n else return make_token(ifno);\n }\n\n\n Token divide_or_comment ()\n {\n if (s.next() != '*') return make_token(TokenName::OP_DIVIDE);\n\n while (s.next() != '\\0')\n {\n if (s.peek() == '*' && s.next() == '/')\n {\n s.advance();\n return next_token();\n }\n }\n\n return error(\"End-of-file in comment. Closing comment characters not found.\");\n }\n\n\n Token char_lit ()\n {\n int n = s.next();\n\n if (n == '\\'') return error(\"Empty character constant\");\n\n if (n == '\\\\') switch (s.next())\n {\n case 'n' : n = '\\n'; break;\n case '\\\\' : n = '\\\\'; break;\n default : return error(\"Unknown escape sequence \\\\\", s.peek());\n }\n\n if (s.next() != '\\'') return error(\"Multi-character constant\");\n\n s.advance();\n return make_token(TokenName::INTEGER, n);\n }\n\n\n Token string_lit ()\n {\n string text = \"\";\n\n while (s.next() != '\"')\n switch (s.peek())\n {\n case '\\\\' : switch (s.next())\n {\n case 'n' : text += '\\n'; continue;\n case '\\\\' : text += '\\\\'; continue;\n default : return error(\"Unknown escape sequence \\\\\", s.peek());\n }\n\n case '\\n' : return error(\"End-of-line while scanning string literal.\"\n \" Closing string character not found before end-of-line.\");\n\n case '\\0' : return error(\"End-of-file while scanning string literal.\"\n \" Closing string character not found.\");\n\n default : text += s.peek();\n }\n\n s.advance();\n return make_token(TokenName::STRING, text);\n }\n\n\n static inline bool is_id_start (char c) { return isalpha(static_cast(c)) || c == '_'; }\n static inline bool is_id_end (char c) { return isalnum(static_cast(c)) || c == '_'; }\n static inline bool is_digit (char c) { return isdigit(static_cast(c)); }\n\n\n Token identifier ()\n {\n string text (1, s.peek());\n\n while (is_id_end(s.next())) text += s.peek();\n\n auto i = keywords.find(text);\n if (i != keywords.end()) return make_token(i->second);\n\n return make_token(TokenName::IDENTIFIER, text);\n }\n\n\n Token integer_lit ()\n {\n while (is_digit(s.next()));\n\n if (is_id_start(s.peek()))\n return error(\"Invalid number. Starts like a number, but ends in non-numeric characters.\");\n\n int n;\n\n auto r = from_chars(pre_state.pos, s.pos, n);\n if (r.ec == errc::result_out_of_range) return error(\"Number exceeds maximum value\");\n\n return make_token(TokenName::INTEGER, n);\n }\n}; // class Lexer\n\n\nconst map Lexer::keywords =\n{\n {\"else\", TokenName::KEYWORD_ELSE},\n {\"if\", TokenName::KEYWORD_IF},\n {\"print\", TokenName::KEYWORD_PRINT},\n {\"putc\", TokenName::KEYWORD_PUTC},\n {\"while\", TokenName::KEYWORD_WHILE}\n};\n\n\nint main (int argc, char* argv[])\n{\n string in = (argc > 1) ? argv[1] : \"stdin\";\n string out = (argc > 2) ? argv[2] : \"stdout\";\n\n with_IO(in, out, [](string input)\n {\n Lexer lexer {input.data()};\n\n string s = \"Location Token name Value\\n\"\n \"--------------------------------------\\n\";\n\n while (lexer.has_more()) s += to_string(lexer.next_token());\n return s;\n });\n}\n"} {"title": "Conjugate transpose", "language": "C++", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate class complex_matrix {\npublic:\n using element_type = std::complex;\n\n complex_matrix(size_t rows, size_t columns)\n : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n complex_matrix(size_t rows, size_t columns, element_type value)\n : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n complex_matrix(size_t rows, size_t columns,\n const std::initializer_list>& values)\n : rows_(rows), columns_(columns), elements_(rows * columns) {\n assert(values.size() <= rows_);\n size_t i = 0;\n for (const auto& row : values) {\n assert(row.size() <= columns_);\n std::copy(begin(row), end(row), &elements_[i]);\n i += columns_;\n }\n }\n\n size_t rows() const { return rows_; }\n size_t columns() const { return columns_; }\n\n const element_type& operator()(size_t row, size_t column) const {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n element_type& operator()(size_t row, size_t column) {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n\n friend bool operator==(const complex_matrix& a, const complex_matrix& b) {\n return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&\n a.elements_ == b.elements_;\n }\n\nprivate:\n size_t rows_;\n size_t columns_;\n std::vector elements_;\n};\n\ntemplate \ncomplex_matrix product(const complex_matrix& a,\n const complex_matrix& b) {\n assert(a.columns() == b.rows());\n size_t arows = a.rows();\n size_t bcolumns = b.columns();\n size_t n = a.columns();\n complex_matrix c(arows, bcolumns);\n for (size_t i = 0; i < arows; ++i) {\n for (size_t j = 0; j < n; ++j) {\n for (size_t k = 0; k < bcolumns; ++k)\n c(i, k) += a(i, j) * b(j, k);\n }\n }\n return c;\n}\n\ntemplate \ncomplex_matrix\nconjugate_transpose(const complex_matrix& a) {\n size_t rows = a.rows(), columns = a.columns();\n complex_matrix b(columns, rows);\n for (size_t i = 0; i < columns; i++) {\n for (size_t j = 0; j < rows; j++) {\n b(i, j) = std::conj(a(j, i));\n }\n }\n return b;\n}\n\ntemplate \nstd::string to_string(const std::complex& c) {\n std::ostringstream out;\n const int precision = 6;\n out << std::fixed << std::setprecision(precision);\n out << std::setw(precision + 3) << c.real();\n if (c.imag() > 0)\n out << \" + \" << std::setw(precision + 2) << c.imag() << 'i';\n else if (c.imag() == 0)\n out << \" + \" << std::setw(precision + 2) << 0.0 << 'i';\n else\n out << \" - \" << std::setw(precision + 2) << -c.imag() << 'i';\n return out.str();\n}\n\ntemplate \nvoid print(std::ostream& out, const complex_matrix& a) {\n size_t rows = a.rows(), columns = a.columns();\n for (size_t row = 0; row < rows; ++row) {\n for (size_t column = 0; column < columns; ++column) {\n if (column > 0)\n out << ' ';\n out << to_string(a(row, column));\n }\n out << '\\n';\n }\n}\n\ntemplate \nbool is_hermitian_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n return matrix == conjugate_transpose(matrix);\n}\n\ntemplate \nbool is_normal_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n auto c = conjugate_transpose(matrix);\n return product(c, matrix) == product(matrix, c);\n}\n\nbool is_equal(const std::complex& a, double b) {\n constexpr double e = 1e-15;\n return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;\n}\n\ntemplate \nbool is_identity_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n size_t rows = matrix.rows();\n for (size_t i = 0; i < rows; ++i) {\n for (size_t j = 0; j < rows; ++j) {\n if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool is_unitary_matrix(const complex_matrix& matrix) {\n if (matrix.rows() != matrix.columns())\n return false;\n auto c = conjugate_transpose(matrix);\n auto p = product(c, matrix);\n return is_identity_matrix(p) && p == product(matrix, c);\n}\n\ntemplate \nvoid test(const complex_matrix& matrix) {\n std::cout << \"Matrix:\\n\";\n print(std::cout, matrix);\n std::cout << \"Conjugate transpose:\\n\";\n print(std::cout, conjugate_transpose(matrix));\n std::cout << std::boolalpha;\n std::cout << \"Hermitian: \" << is_hermitian_matrix(matrix) << '\\n';\n std::cout << \"Normal: \" << is_normal_matrix(matrix) << '\\n';\n std::cout << \"Unitary: \" << is_unitary_matrix(matrix) << '\\n';\n}\n\nint main() {\n using matrix = complex_matrix;\n\n matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},\n {{2, -1}, {3, 0}, {0, 1}},\n {{4, 0}, {0, -1}, {1, 0}}});\n\n double n = std::sqrt(0.5);\n matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},\n {{0, -n}, {0, n}, {0, 0}},\n {{0, 0}, {0, 0}, {0, 1}}});\n\n matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},\n {{2, -1}, {4, 1}, {0, 0}},\n {{7, -5}, {1, -4}, {1, 0}}});\n\n test(matrix1);\n std::cout << '\\n';\n test(matrix2);\n std::cout << '\\n';\n test(matrix3);\n return 0;\n}"} {"title": "Continued fraction", "language": "C++", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "#include \n#include \n#include \n\ntypedef std::tuple coeff_t; // coefficients type\ntypedef coeff_t (*func_t)(int); // callback function type\n\ndouble calc(func_t func, int n)\n{\n double a, b, temp = 0;\n for (; n > 0; --n) {\n std::tie(a, b) = func(n);\n temp = b / (a + temp);\n }\n std::tie(a, b) = func(0);\n return a + temp;\n}\n\ncoeff_t sqrt2(int n)\n{\n return coeff_t(n > 0 ? 2 : 1, 1);\n}\n\ncoeff_t napier(int n)\n{\n return coeff_t(n > 0 ? n : 2, n > 1 ? n - 1 : 1);\n}\n\ncoeff_t pi(int n)\n{\n return coeff_t(n > 0 ? 6 : 3, (2 * n - 1) * (2 * n - 1));\n}\n\nint main()\n{\n std::streamsize old_prec = std::cout.precision(15); // set output digits\n std::cout \n << calc(sqrt2, 20) << '\\n'\n << calc(napier, 15) << '\\n'\n << calc(pi, 10000) << '\\n'\n << std::setprecision(old_prec); // reset precision\n}"} {"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "C++", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "#include \n/* Interface for all Continued Fractions\n Nigel Galloway, February 9th., 2013.\n*/\nclass ContinuedFraction {\n\tpublic:\n\tvirtual const int nextTerm(){};\n\tvirtual const bool moreTerms(){};\n};\n/* Create a continued fraction from a rational number\n Nigel Galloway, February 9th., 2013.\n*/\nclass r2cf : public ContinuedFraction {\n\tprivate: int n1, n2;\n\tpublic:\n\tr2cf(const int numerator, const int denominator): n1(numerator), n2(denominator){}\n\tconst int nextTerm() {\n\t\tconst int thisTerm = n1/n2;\n\t\tconst int t2 = n2; n2 = n1 - thisTerm * n2; n1 = t2;\n\t\treturn thisTerm;\n\t}\n\tconst bool moreTerms() {return fabs(n2) > 0;}\n};\n/* Generate a continued fraction for sqrt of 2\n Nigel Galloway, February 9th., 2013.\n*/\nclass SQRT2 : public ContinuedFraction {\n\tprivate: bool first=true;\n\tpublic:\n\tconst int nextTerm() {if (first) {first = false; return 1;} else return 2;}\n\tconst bool moreTerms() {return true;}\n};"} {"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "C++", "task": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix}\nI may perform perform the following operations:\n:Input the next term of N1\n:Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \\frac{a}{b} and \\frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \\infty.\n\nWhen I input a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a + a_1 * t & a_1 \\\\\n b + b_1 * t & b_1 \n\\end{bmatrix}\n\nWhen I output a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} b_1 & b \\\\\n a_1 - b_1 * t & a - b * t \n\\end{bmatrix}\n\nWhen I need a term t but there are no more my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a_1 & a_1 \\\\\n b_1 & b_1 \n\\end{bmatrix}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n:[1;5,2] + 1/2\n:[3;7] + 1/2 \n:[3;7] divided by 4\nUsing a generator for \\sqrt{2} (e.g., from [[Continued fraction]]) calculate \\frac{1}{\\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.\n\nThe first step in implementing [[Arithmetic-geometric mean]] is to calculate \\frac{1 + \\frac{1}{\\sqrt{2}}}{2} do this now to cross the starting line and begin the race.\n\n", "solution": "/* Interface for all matrixNG classes\n Nigel Galloway, February 10th., 2013.\n*/\nclass matrixNG {\n private:\n virtual void consumeTerm(){}\n virtual void consumeTerm(int n){}\n virtual const bool needTerm(){}\n protected: int cfn = 0, thisTerm;\n bool haveTerm = false;\n friend class NG;\n};\n/* Implement the babyNG matrix\n Nigel Galloway, February 10th., 2013.\n*/\nclass NG_4 : public matrixNG {\n private: int a1, a, b1, b, t;\n const bool needTerm() {\n if (b1==0 and b==0) return false;\n if (b1==0 or b==0) return true; else thisTerm = a/b;\n if (thisTerm==(int)(a1/b1)){\n t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;\n haveTerm=true; return false;\n }\n return true;\n }\n void consumeTerm(){a=a1; b=b1;}\n void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}\n public:\n NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}\n};\n/* Implement a Continued Fraction which returns the result of an arithmetic operation on\n 1 or more Continued Fractions (Currently 1 or 2).\n Nigel Galloway, February 10th., 2013.\n*/\nclass NG : public ContinuedFraction {\n private:\n matrixNG* ng;\n ContinuedFraction* n[2];\n public:\n NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}\n NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}\n const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}\n const bool moreTerms(){\n while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();\n return ng->haveTerm;\n }\n};"} {"title": "Convert seconds to compound duration", "language": "C++11", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "#include \n#include \n\nusing entry = std::pair;\n\nvoid print(const std::vector& entries, std::ostream& out = std::cout)\n{\n bool first = true;\n for(const auto& e: entries) {\n if(!first) out << \", \";\n first = false;\n out << e.first << \" \" << e.second;\n }\n out << '\\n';\n}\n\nstd::vector convert(int seconds)\n{\n static const entry time_table[] = {\n {7*24*60*60, \"wk\"}, {24*60*60, \"d\"}, {60*60, \"hr\"}, {60, \"min\"}, {1, \"sec\"}\n };\n std::vector result;\n for(const auto& e: time_table) {\n int time = seconds / e.first;\n if(time != 0) result.emplace_back(time, e.second);\n seconds %= e.first;\n }\n return result;\n}\n\nint main()\n{\n std::cout << \" 7259 sec is \"; print(convert( 7259));\n std::cout << \" 86400 sec is \"; print(convert( 86400));\n std::cout << \"6000000 sec is \"; print(convert(6000000));\n}"} {"title": "Copy stdin to stdout", "language": "C++", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "#include \n#include \n\nint main() {\n using namespace std;\n noskipws(cin);\n copy(\n istream_iterator(cin),\n istream_iterator(),\n ostream_iterator(cout)\n );\n return 0;\n}"} {"title": "Count the coins", "language": "C++", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n\nstruct DataFrame {\n int sum;\n std::vector coins;\n std::vector avail_coins;\n};\n\nint main() {\n std::stack s;\n s.push({ 100, {}, { 25, 10, 5, 1 } });\n int ways = 0;\n while (!s.empty()) {\n DataFrame top = s.top();\n s.pop();\n if (top.sum < 0) continue;\n if (top.sum == 0) {\n ++ways;\n continue;\n }\n if (top.avail_coins.empty()) continue;\n DataFrame d = top;\n d.sum -= top.avail_coins[0];\n d.coins.push_back(top.avail_coins[0]);\n s.push(d);\n d = top;\n d.avail_coins.erase(std::begin(d.avail_coins));\n s.push(d);\n }\n std::cout << ways << std::endl;\n return 0;\n}"} {"title": "Create an HTML table", "language": "C++", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nvoid makeGap( int gap , std::string & text ) {\n for ( int i = 0 ; i < gap ; i++ ) \n text.append( \" \" ) ;\n}\n\nint main( ) {\n boost::array chars = { 'X' , 'Y' , 'Z' } ;\n int headgap = 3 ;\n int bodygap = 3 ;\n int tablegap = 6 ;\n int rowgap = 9 ;\n std::string tabletext( \"\\n\" ) ;\n makeGap( headgap , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( bodygap , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap, tabletext ) ;\n tabletext += \"\" ;\n for ( int i = 0 ; i < 3 ; i++ ) {\n tabletext += \"\" ;\n }\n tabletext += \"\\n\" ;\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\" ;\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\\n\" ;\n srand( time( 0 ) ) ;\n for ( int row = 0 ; row < 5 ; row++ ) {\n makeGap( rowgap , tabletext ) ;\n std::ostringstream oss ;\n tabletext += \"\" ;\n }\n tabletext += \"\\n\" ;\n }\n makeGap( tablegap + 1 , tabletext ) ;\n tabletext += \"\\n\" ;\n makeGap( tablegap , tabletext ) ;\n tabletext += \"
\" ;\n tabletext += *(chars.begin( ) + i ) ;\n tabletext += \"
\" ;\n oss << row ;\n tabletext += oss.str( ) ;\n for ( int col = 0 ; col < 3 ; col++ ) {\n\t oss.str( \"\" ) ;\n\t int randnumber = rand( ) % 10000 ;\n\t oss << randnumber ;\n\t tabletext += \"\" ;\n\t tabletext.append( oss.str( ) ) ;\n\t tabletext += \"
\\n\" ;\n makeGap( bodygap , tabletext ) ;\n tabletext += \"\\n\" ;\n tabletext += \"\\n\" ;\n std::ofstream htmltable( \"testtable.html\" , std::ios::out | std::ios::trunc ) ;\n htmltable << tabletext ;\n htmltable.close( ) ;\n return 0 ;\n}"} {"title": "Currying", "language": "C++", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "Currying may be achieved in [[C++]] using the [[wp:Standard Template Library|Standard Template Library]] function object adapters (binder1st and binder2nd), and more generically using the [[wp:Boost library|Boost]] bind mechanism.\n\n"} {"title": "Curzon numbers", "language": "C++", "task": "A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''.\n\n'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''.\n\n''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' \n\nGeneralized Curzon numbers only exist for even base integers. \n\n\n;Task \n\n* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.\n\n\n;Stretch\n\n* Find and show the '''one thousandth'''.\n\n\n;See also\n\n;* Numbers Aplenty - Curzon numbers\n;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)\n\n''and even though it is not specifically mentioned that they are Curzon numbers:''\n\n;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)\n\n", "solution": "#include \n#include \n#include \n#include \n\nuint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {\n if (mod == 1)\n return 0;\n uint64_t result = 1;\n base %= mod;\n for (; exp > 0; exp >>= 1) {\n if ((exp & 1) == 1)\n result = (result * base) % mod;\n base = (base * base) % mod;\n }\n return result;\n}\n\nbool is_curzon(uint64_t n, uint64_t k) {\n const uint64_t r = k * n;\n return modpow(k, n, r + 1) == r;\n}\n\nint main() {\n for (uint64_t k = 2; k <= 10; k += 2) {\n std::cout << \"Curzon numbers with base \" << k << \":\\n\";\n uint64_t count = 0, n = 1;\n for (; count < 50; ++n) {\n if (is_curzon(n, k)) {\n std::cout << std::setw(4) << n\n << (++count % 10 == 0 ? '\\n' : ' ');\n }\n }\n for (;;) {\n if (is_curzon(n, k))\n ++count;\n if (count == 1000)\n break;\n ++n;\n }\n std::cout << \"1000th Curzon number with base \" << k << \": \" << n\n << \"\\n\\n\";\n }\n return 0;\n}"} {"title": "Cut a rectangle", "language": "C++ from Java", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "#include \n#include \n#include \n#include \n\nconst std::array, 4> DIRS = {\n std::make_pair(0, -1),\n std::make_pair(-1, 0),\n std::make_pair(0, 1),\n std::make_pair(1, 0),\n};\n\nvoid printResult(const std::vector> &v) {\n for (auto &row : v) {\n auto it = row.cbegin();\n auto end = row.cend();\n\n std::cout << '[';\n if (it != end) {\n std::cout << *it;\n it = std::next(it);\n }\n while (it != end) {\n std::cout << \", \" << *it;\n it = std::next(it);\n }\n std::cout << \"]\\n\";\n }\n}\n\nvoid cutRectangle(int w, int h) {\n if (w % 2 == 1 && h % 2 == 1) {\n return;\n }\n\n std::vector> grid(h, std::vector(w));\n std::stack stack;\n\n int half = (w * h) / 2;\n long bits = (long)pow(2, half) - 1;\n\n for (; bits > 0; bits -= 2) {\n for (int i = 0; i < half; i++) {\n int r = i / w;\n int c = i % w;\n grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;\n grid[h - r - 1][w - c - 1] = 1 - grid[r][c];\n }\n\n stack.push(0);\n grid[0][0] = 2;\n int count = 1;\n while (!stack.empty()) {\n int pos = stack.top();\n stack.pop();\n\n int r = pos / w;\n int c = pos % w;\n for (auto dir : DIRS) {\n int nextR = r + dir.first;\n int nextC = c + dir.second;\n\n if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {\n if (grid[nextR][nextC] == 1) {\n stack.push(nextR * w + nextC);\n grid[nextR][nextC] = 2;\n count++;\n }\n }\n }\n }\n if (count == half) {\n printResult(grid);\n std::cout << '\\n';\n }\n }\n}\n\nint main() {\n cutRectangle(2, 2);\n cutRectangle(4, 3);\n\n return 0;\n}"} {"title": "Cyclotomic polynomial", "language": "C++ from Java", "task": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.\n\n\n;Task:\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\n\n;See also\n* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.\n* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst int MAX_ALL_FACTORS = 100000;\nconst int algorithm = 2;\nint divisions = 0;\n\n//Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\nclass Term {\nprivate:\n long m_coefficient;\n long m_exponent;\n\npublic:\n Term(long c, long e) : m_coefficient(c), m_exponent(e) {\n // empty\n }\n\n Term(const Term &t) : m_coefficient(t.m_coefficient), m_exponent(t.m_exponent) {\n // empty\n }\n\n long coefficient() const {\n return m_coefficient;\n }\n\n long degree() const {\n return m_exponent;\n }\n\n Term operator -() const {\n return { -m_coefficient, m_exponent };\n }\n\n Term operator *(const Term &rhs) const {\n return { m_coefficient * rhs.m_coefficient, m_exponent + rhs.m_exponent };\n }\n\n Term operator +(const Term &rhs) const {\n if (m_exponent != rhs.m_exponent) {\n throw std::runtime_error(\"Exponents not equal\");\n }\n return { m_coefficient + rhs.m_coefficient, m_exponent };\n }\n\n friend std::ostream &operator<<(std::ostream &, const Term &);\n};\n\nstd::ostream &operator<<(std::ostream &os, const Term &t) {\n if (t.m_coefficient == 0) {\n return os << '0';\n }\n if (t.m_exponent == 0) {\n return os << t.m_coefficient;\n }\n if (t.m_coefficient == 1) {\n if (t.m_exponent == 1) {\n return os << 'x';\n }\n return os << \"x^\" << t.m_exponent;\n }\n if (t.m_coefficient == -1) {\n if (t.m_exponent == 1) {\n return os << \"-x\";\n }\n return os << \"-x^\" << t.m_exponent;\n }\n if (t.m_exponent == 1) {\n return os << t.m_coefficient << 'x';\n }\n return os << t.m_coefficient << \"x^\" << t.m_exponent;\n}\n\nclass Polynomial {\npublic:\n std::vector polynomialTerms;\n\n Polynomial() {\n polynomialTerms.push_back({ 0, 0 });\n }\n\n Polynomial(std::initializer_list values) {\n if (values.size() % 2 != 0) {\n throw std::runtime_error(\"Length must be even.\");\n }\n\n bool ready = false;\n long t;\n for (auto v : values) {\n if (ready) {\n polynomialTerms.push_back({ t, v });\n } else {\n t = v;\n }\n ready = !ready;\n }\n std::sort(\n polynomialTerms.begin(), polynomialTerms.end(),\n [](const Term &t, const Term &u) {\n return u.degree() < t.degree();\n }\n );\n }\n\n Polynomial(const std::vector &termList) {\n if (termList.size() == 0) {\n polynomialTerms.push_back({ 0, 0 });\n } else {\n for (auto t : termList) {\n if (t.coefficient() != 0) {\n polynomialTerms.push_back(t);\n }\n }\n if (polynomialTerms.size() == 0) {\n polynomialTerms.push_back({ 0, 0 });\n }\n std::sort(\n polynomialTerms.begin(), polynomialTerms.end(),\n [](const Term &t, const Term &u) {\n return u.degree() < t.degree();\n }\n );\n }\n }\n\n Polynomial(const Polynomial &p) : Polynomial(p.polynomialTerms) {\n // empty\n }\n\n long leadingCoefficient() const {\n return polynomialTerms[0].coefficient();\n }\n\n long degree() const {\n return polynomialTerms[0].degree();\n }\n\n bool hasCoefficientAbs(int coeff) {\n for (auto term : polynomialTerms) {\n if (abs(term.coefficient()) == coeff) {\n return true;\n }\n }\n return false;\n }\n\n Polynomial operator+(const Term &term) const {\n std::vector termList;\n bool added = false;\n for (size_t index = 0; index < polynomialTerms.size(); index++) {\n auto currentTerm = polynomialTerms[index];\n if (currentTerm.degree() == term.degree()) {\n added = true;\n if (currentTerm.coefficient() + term.coefficient() != 0) {\n termList.push_back(currentTerm + term);\n }\n } else {\n termList.push_back(currentTerm);\n }\n }\n if (!added) {\n termList.push_back(term);\n }\n return Polynomial(termList);\n }\n\n Polynomial operator*(const Term &term) const {\n std::vector termList;\n for (size_t index = 0; index < polynomialTerms.size(); index++) {\n auto currentTerm = polynomialTerms[index];\n termList.push_back(currentTerm * term);\n }\n return Polynomial(termList);\n }\n\n Polynomial operator+(const Polynomial &p) const {\n std::vector termList;\n int thisCount = polynomialTerms.size();\n int polyCount = p.polynomialTerms.size();\n while (thisCount > 0 || polyCount > 0) {\n if (thisCount == 0) {\n auto polyTerm = p.polynomialTerms[polyCount - 1];\n termList.push_back(polyTerm);\n polyCount--;\n } else if (polyCount == 0) {\n auto thisTerm = polynomialTerms[thisCount - 1];\n termList.push_back(thisTerm);\n thisCount--;\n } else {\n auto polyTerm = p.polynomialTerms[polyCount - 1];\n auto thisTerm = polynomialTerms[thisCount - 1];\n if (thisTerm.degree() == polyTerm.degree()) {\n auto t = thisTerm + polyTerm;\n if (t.coefficient() != 0) {\n termList.push_back(t);\n }\n thisCount--;\n polyCount--;\n } else if (thisTerm.degree() < polyTerm.degree()) {\n termList.push_back(thisTerm);\n thisCount--;\n } else {\n termList.push_back(polyTerm);\n polyCount--;\n }\n }\n }\n return Polynomial(termList);\n }\n\n Polynomial operator/(const Polynomial &v) {\n divisions++;\n\n Polynomial q;\n Polynomial r(*this);\n long lcv = v.leadingCoefficient();\n long dv = v.degree();\n while (r.degree() >= v.degree()) {\n long lcr = r.leadingCoefficient();\n long s = lcr / lcv;\n Term term(s, r.degree() - dv);\n q = q + term;\n r = r + v * -term;\n }\n\n return q;\n }\n\n friend std::ostream &operator<<(std::ostream &, const Polynomial &);\n};\n\nstd::ostream &operator<<(std::ostream &os, const Polynomial &p) {\n auto it = p.polynomialTerms.cbegin();\n auto end = p.polynomialTerms.cend();\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n if (it->coefficient() > 0) {\n os << \" + \" << *it;\n } else {\n os << \" - \" << -*it;\n }\n it = std::next(it);\n }\n return os;\n}\n\nstd::vector getDivisors(int number) {\n std::vector divisiors;\n long root = (long)sqrt(number);\n for (int i = 1; i <= root; i++) {\n if (number % i == 0) {\n divisiors.push_back(i);\n int div = number / i;\n if (div != i && div != number) {\n divisiors.push_back(div);\n }\n }\n }\n return divisiors;\n}\n\nstd::map> allFactors;\n\nstd::map getFactors(int number) {\n if (allFactors.find(number) != allFactors.end()) {\n return allFactors[number];\n }\n\n std::map factors;\n if (number % 2 == 0) {\n auto factorsDivTwo = getFactors(number / 2);\n factors.insert(factorsDivTwo.begin(), factorsDivTwo.end());\n if (factors.find(2) != factors.end()) {\n factors[2]++;\n } else {\n factors.insert(std::make_pair(2, 1));\n }\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n }\n long root = (long)sqrt(number);\n long i = 3;\n while (i <= root) {\n if (number % i == 0) {\n auto factorsDivI = getFactors(number / i);\n factors.insert(factorsDivI.begin(), factorsDivI.end());\n if (factors.find(i) != factors.end()) {\n factors[i]++;\n } else {\n factors.insert(std::make_pair(i, 1));\n }\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n }\n i += 2;\n }\n factors.insert(std::make_pair(number, 1));\n if (number < MAX_ALL_FACTORS) {\n allFactors.insert(std::make_pair(number, factors));\n }\n return factors;\n}\n\nstd::map COMPUTED;\nPolynomial cyclotomicPolynomial(int n) {\n if (COMPUTED.find(n) != COMPUTED.end()) {\n return COMPUTED[n];\n }\n\n if (n == 1) {\n // Polynomial: x - 1\n Polynomial p({ 1, 1, -1, 0 });\n COMPUTED.insert(std::make_pair(1, p));\n return p;\n }\n\n auto factors = getFactors(n);\n if (factors.find(n) != factors.end()) {\n // n prime\n std::vector termList;\n for (int index = 0; index < n; index++) {\n termList.push_back({ 1, index });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 2 && factors.find(2) != factors.end() && factors[2] == 1 && factors.find(n / 2) != factors.end() && factors[n / 2] == 1) {\n // n = 2p\n int prime = n / 2;\n std::vector termList;\n int coeff = -1;\n\n for (int index = 0; index < prime; index++) {\n coeff *= -1;\n termList.push_back({ coeff, index });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 1 && factors.find(2) != factors.end()) {\n // n = 2^h\n int h = factors[2];\n std::vector termList;\n termList.push_back({ 1, (int)pow(2, h - 1) });\n termList.push_back({ 1, 0 });\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 1 && factors.find(n) != factors.end()) {\n // n = p^k\n int p = 0;\n int k = 0;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n p = iter->first;\n k = iter->second;\n }\n std::vector termList;\n for (int index = 0; index < p; index++) {\n termList.push_back({ 1, index * (int)pow(p, k - 1) });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.size() == 2 && factors.find(2) != factors.end()) {\n // n = 2^h * p^k\n int p = 0;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n if (iter->first != 2) {\n p = iter->first;\n }\n }\n\n std::vector termList;\n int coeff = -1;\n int twoExp = (int)pow(2, factors[2] - 1);\n int k = factors[p];\n for (int index = 0; index < p; index++) {\n coeff *= -1;\n termList.push_back({ coeff, index * twoExp * (int)pow(p, k - 1) });\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (factors.find(2) != factors.end() && ((n / 2) % 2 == 1) && (n / 2) > 1) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n auto cycloDiv2 = cyclotomicPolynomial(n / 2);\n std::vector termList;\n for (auto term : cycloDiv2.polynomialTerms) {\n if (term.degree() % 2 == 0) {\n termList.push_back(term);\n } else {\n termList.push_back(-term);\n }\n }\n\n Polynomial cyclo(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n }\n\n // General Case\n\n if (algorithm == 0) {\n // slow - uses basic definition\n auto divisors = getDivisors(n);\n // Polynomial: (x^n - 1)\n Polynomial cyclo({ 1, n, -1, 0 });\n for (auto i : divisors) {\n auto p = cyclotomicPolynomial(i);\n cyclo = cyclo / p;\n }\n\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (algorithm == 1) {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n auto divisors = getDivisors(n);\n int maxDivisor = INT_MIN;\n for (auto div : divisors) {\n maxDivisor = std::max(maxDivisor, div);\n }\n std::vector divisorExceptMax;\n for (auto div : divisors) {\n if (maxDivisor % div != 0) {\n divisorExceptMax.push_back(div);\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n auto cyclo = Polynomial({ 1, n, -1, 0 }) / Polynomial({ 1, maxDivisor, -1, 0 });\n for (int i : divisorExceptMax) {\n auto p = cyclotomicPolynomial(i);\n cyclo = cyclo / p;\n }\n\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else if (algorithm == 2) {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n int m = 1;\n auto cyclo = cyclotomicPolynomial(m);\n std::vector primes;\n for (auto iter = factors.begin(); iter != factors.end(); ++iter) {\n primes.push_back(iter->first);\n }\n std::sort(primes.begin(), primes.end());\n for (auto prime : primes) {\n // CP(m)[x]\n auto cycloM = cyclo;\n // Compute CP(m)[x^p].\n std::vector termList;\n for (auto t : cycloM.polynomialTerms) {\n termList.push_back({ t.coefficient(), t.degree() * prime });\n }\n cyclo = Polynomial(termList) / cycloM;\n m = m * prime;\n }\n // Now, m is the largest square free divisor of n\n int s = n / m;\n // Compute CP(n)[x] = CP(m)[x^s]\n std::vector termList;\n for (auto t : cyclo.polynomialTerms) {\n termList.push_back({ t.coefficient(), t.degree() * s });\n }\n\n cyclo = Polynomial(termList);\n COMPUTED.insert(std::make_pair(n, cyclo));\n return cyclo;\n } else {\n throw std::runtime_error(\"Invalid algorithm\");\n }\n}\n\nint main() {\n // initialization\n std::map factors;\n factors.insert(std::make_pair(2, 1));\n allFactors.insert(std::make_pair(2, factors));\n\n // rest of main\n std::cout << \"Task 1: cyclotomic polynomials for n <= 30:\\n\";\n for (int i = 1; i <= 30; i++) {\n auto p = cyclotomicPolynomial(i);\n std::cout << \"CP[\" << i << \"] = \" << p << '\\n';\n }\n\n std::cout << \"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\\n\";\n int n = 0;\n for (int i = 1; i <= 10; i++) {\n while (true) {\n n++;\n auto cyclo = cyclotomicPolynomial(n);\n if (cyclo.hasCoefficientAbs(i)) {\n std::cout << \"CP[\" << n << \"] has coefficient with magnitude = \" << i << '\\n';\n n--;\n break;\n }\n }\n }\n\n return 0;\n}"} {"title": "Damm algorithm", "language": "C++ from C#", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "#include \n\n#include \n\ninline constexper int TABLE[][10] = {\n\t{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},\n\t{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},\n\t{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},\n\t{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},\n\t{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},\n\t{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},\n\t{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},\n\t{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},\n\t{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},\n\t{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},\n};\n\n[[nodiscard]] bool damm(std::string s) noexcept {\n\tint interim = 0;\n\tfor (const auto c : s) {\n\t\tinterim = TABLE[interim][c - '0'];\n\t}\n\treturn interim == 0;\n}\n\nint main() {\n\tfor (const auto num : { 5724, 5727, 112946, 112949 }) {\n\t\tif (damm(std::to_string(num))) {\n\t \t \tstd::printf(\"%6d is valid\\n\", num);\n\t\t}\t\n\t\telse std::printf(\"%6d is invalid\\n\", num);\n\t}\n}"} {"title": "De Bruijn sequences", "language": "C++ from D", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned char byte;\n\nstd::string deBruijn(int k, int n) {\n std::vector a(k * n, 0);\n std::vector seq;\n\n std::function db;\n db = [&](int t, int p) {\n if (t > n) {\n if (n % p == 0) {\n for (int i = 1; i < p + 1; i++) {\n seq.push_back(a[i]);\n }\n }\n } else {\n a[t] = a[t - p];\n db(t + 1, p);\n auto j = a[t - p] + 1;\n while (j < k) {\n a[t] = j & 0xFF;\n db(t + 1, t);\n j++;\n }\n }\n };\n\n db(1, 1);\n std::string buf;\n for (auto i : seq) {\n buf.push_back('0' + i);\n }\n return buf + buf.substr(0, n - 1);\n}\n\nbool allDigits(std::string s) {\n for (auto c : s) {\n if (c < '0' || '9' < c) {\n return false;\n }\n }\n return true;\n}\n\nvoid validate(std::string db) {\n auto le = db.size();\n std::vector found(10000, 0);\n std::vector errs;\n\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (size_t i = 0; i < le - 3; i++) {\n auto s = db.substr(i, 4);\n if (allDigits(s)) {\n auto n = stoi(s);\n found[n]++;\n }\n }\n\n for (int i = 0; i < 10000; i++) {\n if (found[i] == 0) {\n std::stringstream ss;\n ss << \" PIN number \" << i << \" missing\";\n errs.push_back(ss.str());\n } else if (found[i] > 1) {\n std::stringstream ss;\n ss << \" PIN number \" << i << \" occurs \" << found[i] << \" times\";\n errs.push_back(ss.str());\n }\n }\n\n if (errs.empty()) {\n std::cout << \" No errors found\\n\";\n } else {\n auto pl = (errs.size() == 1) ? \"\" : \"s\";\n std::cout << \" \" << errs.size() << \" error\" << pl << \" found:\\n\";\n for (auto e : errs) {\n std::cout << e << '\\n';\n }\n }\n}\n\nint main() {\n std::ostream_iterator oi(std::cout, \"\");\n auto db = deBruijn(10, 4);\n\n std::cout << \"The length of the de Bruijn sequence is \" << db.size() << \"\\n\\n\";\n std::cout << \"The first 130 digits of the de Bruijn sequence are: \";\n std::copy_n(db.cbegin(), 130, oi);\n std::cout << \"\\n\\nThe last 130 digits of the de Bruijn sequence are: \";\n std::copy(db.cbegin() + (db.size() - 130), db.cend(), oi);\n std::cout << \"\\n\";\n\n std::cout << \"\\nValidating the de Bruijn sequence:\\n\";\n validate(db);\n\n std::cout << \"\\nValidating the reversed de Bruijn sequence:\\n\";\n auto rdb = db;\n std::reverse(rdb.begin(), rdb.end());\n validate(rdb);\n\n auto by = db;\n by[4443] = '.';\n std::cout << \"\\nValidating the overlaid de Bruijn sequence:\\n\";\n validate(by);\n\n return 0;\n}"} {"title": "Deepcopy", "language": "C++", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nint main()\n{\n // make a nested structure to copy - a map of arrays containing vectors of strings\n auto myNumbers = std::vector{\"one\", \"two\", \"three\", \"four\"};\n auto myColors = std::vector{\"red\", \"green\", \"blue\"};\n auto myArray = std::array, 2>{myNumbers, myColors};\n auto myMap = std::map {{3, myArray}, {7, myArray}};\n\n // make a deep copy of the map\n auto mapCopy = myMap;\n\n // modify the copy\n mapCopy[3][0][1] = \"2\";\n mapCopy[7][1][2] = \"purple\";\n \n std::cout << \"the original values:\\n\";\n std::cout << myMap[3][0][1] << \"\\n\";\n std::cout << myMap[7][1][2] << \"\\n\\n\";\n\n std::cout << \"the modified copy:\\n\";\n std::cout << mapCopy[3][0][1] << \"\\n\";\n std::cout << mapCopy[7][1][2] << \"\\n\"; \n}"} {"title": "Department numbers", "language": "C++", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "#include \n#include \n\nint main( int argc, char* argv[] ) {\n int sol = 1;\n std::cout << \"\\t\\tFIRE\\t\\tPOLICE\\t\\tSANITATION\\n\";\n for( int f = 1; f < 8; f++ ) {\n for( int p = 1; p < 8; p++ ) {\n for( int s = 1; s < 8; s++ ) {\n if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {\n std::cout << \"SOLUTION #\" << std::setw( 2 ) << sol++ << std::setw( 2 ) \n << \":\\t\" << std::setw( 2 ) << f << \"\\t\\t \" << std::setw( 3 ) << p \n << \"\\t\\t\" << std::setw( 6 ) << s << \"\\n\";\n }\n }\n }\n }\n return 0;\n}"} {"title": "Descending primes", "language": "C++ from C#", "task": "Generate and show all primes with strictly descending decimal digits.\n\n;See also\n;* OEIS:A052014 - Primes with distinct digits in descending order\n\n;Related:\n*[[Ascending primes]]\n\n\n", "solution": "#include \n\nbool ispr(unsigned int n) {\n if ((n & 1) == 0 || n < 2) return n == 2;\n for (unsigned int j = 3; j * j <= n; j += 2)\n if (n % j == 0) return false; return true; }\n\nint main() {\n unsigned int c = 0, nc, pc = 9, i, a, b, l,\n ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];\n while (true) {\n nc = 0;\n for (i = 0; i < pc; i++) {\n if (ispr(a = ps[i]))\n printf(\"%8d%s\", a, ++c % 5 == 0 ? \"\\n\" : \" \");\n for (b = a * 10, l = a % 10 + b++; b < l; b++)\n nxt[nc++] = b;\n }\n if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];\n else break;\n }\n printf(\"\\n%d descending primes found\", c);\n}"} {"title": "Detect division by zero", "language": "C++", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "#include\n#include /* for signal */\n#include\n\nusing namespace std;\n\nvoid fpe_handler(int signal)\n{\n cerr << \"Floating Point Exception: division by zero\" << endl;\n exit(signal);\n}\n\nint main()\n{\n // Register floating-point exception handler.\n signal(SIGFPE, fpe_handler);\n\n int a = 1;\n int b = 0;\n cout << a/b << endl;\n\n return 0;\n}\n"} {"title": "Determinant and permanent", "language": "C++ from Java", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "#include \n#include \n\ntemplate \nstd::ostream &operator<<(std::ostream &os, const std::vector &v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n return os << ']';\n}\n\nusing Matrix = std::vector>;\n\nMatrix squareMatrix(size_t n) {\n Matrix m;\n for (size_t i = 0; i < n; i++) {\n std::vector inner;\n for (size_t j = 0; j < n; j++) {\n inner.push_back(nan(\"\"));\n }\n m.push_back(inner);\n }\n return m;\n}\n\nMatrix minor(const Matrix &a, int x, int y) {\n auto length = a.size() - 1;\n auto result = squareMatrix(length);\n for (int i = 0; i < length; i++) {\n for (int j = 0; j < length; j++) {\n if (i < x && j < y) {\n result[i][j] = a[i][j];\n } else if (i >= x && j < y) {\n result[i][j] = a[i + 1][j];\n } else if (i < x && j >= y) {\n result[i][j] = a[i][j + 1];\n } else {\n result[i][j] = a[i + 1][j + 1];\n }\n }\n }\n return result;\n}\n\ndouble det(const Matrix &a) {\n if (a.size() == 1) {\n return a[0][0];\n }\n\n int sign = 1;\n double sum = 0;\n for (size_t i = 0; i < a.size(); i++) {\n sum += sign * a[0][i] * det(minor(a, 0, i));\n sign *= -1;\n }\n return sum;\n}\n\ndouble perm(const Matrix &a) {\n if (a.size() == 1) {\n return a[0][0];\n }\n\n double sum = 0;\n for (size_t i = 0; i < a.size(); i++) {\n sum += a[0][i] * perm(minor(a, 0, i));\n }\n return sum;\n}\n\nvoid test(const Matrix &m) {\n auto p = perm(m);\n auto d = det(m);\n\n std::cout << m << '\\n';\n std::cout << \"Permanent: \" << p << \", determinant: \" << d << \"\\n\\n\";\n}\n\nint main() {\n test({ {1, 2}, {3, 4} });\n test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });\n 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} });\n\n return 0;\n}"} {"title": "Determine if a string has all the same characters", "language": "C++", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "#include \n#include \n\nvoid all_characters_are_the_same(const std::string& str) {\n size_t len = str.length();\n std::cout << \"input: \\\"\" << str << \"\\\", length: \" << len << '\\n';\n if (len > 0) {\n char ch = str[0];\n for (size_t i = 1; i < len; ++i) {\n if (str[i] != ch) {\n std::cout << \"Not all characters are the same.\\n\";\n std::cout << \"Character '\" << str[i]\n << \"' (hex \" << std::hex << static_cast(str[i])\n << \") at position \" << std::dec << i + 1\n << \" is not the same as '\" << ch << \"'.\\n\\n\";\n return;\n }\n }\n }\n std::cout << \"All characters are the same.\\n\\n\";\n}\n\nint main() {\n all_characters_are_the_same(\"\");\n all_characters_are_the_same(\" \");\n all_characters_are_the_same(\"2\");\n all_characters_are_the_same(\"333\");\n all_characters_are_the_same(\".55\");\n all_characters_are_the_same(\"tttTTT\");\n all_characters_are_the_same(\"4444 444k\");\n return 0;\n}"} {"title": "Determine if a string has all unique characters", "language": "C++", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "#include \n#include \n\nvoid string_has_repeated_character(const std::string& str) {\n size_t len = str.length();\n std::cout << \"input: \\\"\" << str << \"\\\", length: \" << len << '\\n';\n for (size_t i = 0; i < len; ++i) {\n for (size_t j = i + 1; j < len; ++j) {\n if (str[i] == str[j]) {\n std::cout << \"String contains a repeated character.\\n\";\n std::cout << \"Character '\" << str[i]\n << \"' (hex \" << std::hex << static_cast(str[i])\n << \") occurs at positions \" << std::dec << i + 1\n << \" and \" << j + 1 << \".\\n\\n\";\n return;\n }\n }\n }\n std::cout << \"String contains no repeated characters.\\n\\n\";\n}\n\nint main() {\n string_has_repeated_character(\"\");\n string_has_repeated_character(\".\");\n string_has_repeated_character(\"abcABC\");\n string_has_repeated_character(\"XYZ ZYX\");\n string_has_repeated_character(\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\");\n return 0;\n}"} {"title": "Determine if a string is collapsible", "language": "C++", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "#include \n#include \n#include \n\ntemplate\nstd::basic_string collapse(std::basic_string str) {\n auto i = std::unique(str.begin(), str.end());\n str.erase(i, str.end());\n return str;\n}\n\nvoid test(const std::string& str) {\n std::cout << \"original string: <<<\" << str << \">>>, length = \" << str.length() << '\\n';\n std::string collapsed(collapse(str));\n std::cout << \"result string: <<<\" << collapsed << \">>>, length = \" << collapsed.length() << '\\n';\n std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n test(\"\");\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \");\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\");\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \");\n test(\" --- Harry S Truman \");\n return 0;\n}"} {"title": "Determine if a string is squeezable", "language": "C++", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "#include \n#include \n#include \n\ntemplate\nstd::basic_string squeeze(std::basic_string str, char_type ch) {\n auto i = std::unique(str.begin(), str.end(),\n [ch](char_type a, char_type b) { return a == ch && b == ch; });\n str.erase(i, str.end());\n return str;\n}\n\nvoid test(const std::string& str, char ch) {\n std::cout << \"character: '\" << ch << \"'\\n\";\n std::cout << \"original: <<<\" << str << \">>>, length: \" << str.length() << '\\n';\n std::string squeezed(squeeze(str, ch));\n std::cout << \"result: <<<\" << squeezed << \">>>, length: \" << squeezed.length() << '\\n';\n std::cout << '\\n';\n}\n\nint main(int argc, char** argv) {\n test(\"\", ' ');\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", '-');\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7');\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.');\n std::string truman(\" --- Harry S Truman \");\n test(truman, ' ');\n test(truman, '-');\n test(truman, 'r');\n return 0;\n}"} {"title": "Determine if two triangles overlap", "language": "C++", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\ntypedef std::pair TriPoint;\n\ninline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) \n{\n\treturn +p1.first*(p2.second-p3.second)\n\t\t+p2.first*(p3.second-p1.second)\n\t\t+p3.first*(p1.second-p2.second);\n}\n\nvoid CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed)\n{\n\tdouble detTri = Det2D(p1, p2, p3);\n\tif(detTri < 0.0)\n\t{\n\t\tif (allowReversed)\n\t\t{\n\t\t\tTriPoint a = p3;\n\t\t\tp3 = p2;\n\t\t\tp2 = a;\n\t\t}\n\t\telse throw std::runtime_error(\"triangle has wrong winding direction\");\n\t}\n}\n\nbool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)\n{\n\treturn Det2D(p1, p2, p3) < eps;\n}\n\nbool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)\n{\n\treturn Det2D(p1, p2, p3) <= eps;\n}\n\nbool TriTri2D(TriPoint *t1,\n\tTriPoint *t2,\n\tdouble eps = 0.0, bool allowReversed = false, bool onBoundary = true)\n{\n\t//Trangles must be expressed anti-clockwise\n\tCheckTriWinding(t1[0], t1[1], t1[2], allowReversed);\n\tCheckTriWinding(t2[0], t2[1], t2[2], allowReversed);\n\n\tbool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL;\n\tif(onBoundary) //Points on the boundary are considered as colliding\n\t\tchkEdge = BoundaryCollideChk;\n\telse //Points on the boundary are not considered as colliding\n\t\tchkEdge = BoundaryDoesntCollideChk;\n\n\t//For edge E of trangle 1,\n\tfor(int i=0; i<3; i++)\n\t{\n\t\tint j=(i+1)%3;\n\n\t\t//Check all points of trangle 2 lay on the external side of the edge E. If\n\t\t//they do, the triangles do not collide.\n\t\tif (chkEdge(t1[i], t1[j], t2[0], eps) &&\n\t\t\tchkEdge(t1[i], t1[j], t2[1], eps) &&\n\t\t\tchkEdge(t1[i], t1[j], t2[2], eps))\n\t\t\treturn false;\n\t}\n\n\t//For edge E of trangle 2,\n\tfor(int i=0; i<3; i++)\n\t{\n\t\tint j=(i+1)%3;\n\n\t\t//Check all points of trangle 1 lay on the external side of the edge E. If\n\t\t//they do, the triangles do not collide.\n\t\tif (chkEdge(t2[i], t2[j], t1[0], eps) &&\n\t\t\tchkEdge(t2[i], t2[j], t1[1], eps) &&\n\t\t\tchkEdge(t2[i], t2[j], t1[2], eps))\n\t\t\treturn false;\n\t}\n\n\t//The triangles collide\n\treturn true;\n}\n\nint main()\n{\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};\n\tTriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)};\n\tcout << TriTri2D(t1, t2) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};\n\tTriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};\n\tcout << TriTri2D(t1, t2, 0.0, true) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};\n\tTriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)};\n\tTriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)};\n\tcout << TriTri2D(t1, t2) << \",\" << true << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};\n\tTriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};\n\tTriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)};\n\tcout << TriTri2D(t1, t2) << \",\" << false << endl;}\n\n\t//Barely touching\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};\n\tTriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};\n\tcout << TriTri2D(t1, t2, 0.0, false, true) << \",\" << true << endl;}\n\n\t//Barely touching\n\t{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};\n\tTriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};\n\tcout << TriTri2D(t1, t2, 0.0, false, false) << \",\" << false << endl;}\n\n}"} {"title": "Dice game probabilities", "language": "C++", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n// Returns map from sum of faces to number of ways it can happen\nstd::map get_totals(uint32_t dice, uint32_t faces) {\n std::map result;\n for (uint32_t i = 1; i <= faces; ++i)\n result.emplace(i, 1);\n for (uint32_t d = 2; d <= dice; ++d) {\n std::map tmp;\n for (const auto& p : result) {\n for (uint32_t i = 1; i <= faces; ++i)\n tmp[p.first + i] += p.second;\n }\n tmp.swap(result);\n }\n return result;\n}\n\ndouble probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {\n auto totals1 = get_totals(dice1, faces1);\n auto totals2 = get_totals(dice2, faces2);\n double wins = 0;\n for (const auto& p1 : totals1) {\n for (const auto& p2 : totals2) {\n if (p2.first >= p1.first)\n break;\n wins += p1.second * p2.second;\n }\n }\n double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);\n return wins/total;\n}\n\nint main() {\n std::cout << std::setprecision(10);\n std::cout << probability(9, 4, 6, 6) << '\\n';\n std::cout << probability(5, 10, 6, 7) << '\\n';\n return 0;\n}"} {"title": "Digital root", "language": "C++", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "// Calculate the Digital Root and Additive Persistance of an Integer - Compiles with gcc4.7\n//\n// Nigel Galloway. July 23rd., 2012\n//\n#include \n#include \n#include \n\ntemplate P_ IncFirst(const P_& src) {return P_(src.first + 1, src.second);}\n\nstd::pair DigitalRoot(unsigned long long digits, int base = 10) \n{\n int x = SumDigits(digits, base);\n return x < base ? std::make_pair(1, x) : IncFirst(DigitalRoot(x, base)); // x is implicitly converted to unsigned long long; this is lossless\n}\n\nint main() {\n const unsigned long long ip[] = {961038,923594037444,670033,448944221089};\n for (auto i:ip){\n auto res = DigitalRoot(i);\n std::cout << i << \" has digital root \" << res.second << \" and additive persistance \" << res.first << \"\\n\";\n }\n std::cout << \"\\n\";\n const unsigned long long hip[] = {0x7e0,0x14e344,0xd60141,0x12343210};\n for (auto i:hip){\n auto res = DigitalRoot(i,16);\n std::cout << std::hex << i << \" has digital root \" << res.second << \" and additive persistance \" << res.first << \"\\n\";\n }\n return 0;\n}"} {"title": "Disarium numbers", "language": "C++", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::vector decompose( int n ) {\n std::vector digits ;\n while ( n != 0 ) {\n digits.push_back( n % 10 ) ;\n n /= 10 ;\n }\n std::reverse( digits.begin( ) , digits.end( ) ) ;\n return digits ;\n}\n\nbool isDisarium( int n ) {\n std::vector digits( decompose( n ) ) ;\n int exposum = 0 ;\n for ( int i = 1 ; i < digits.size( ) + 1 ; i++ ) {\n exposum += static_cast( std::pow(\n static_cast(*(digits.begin( ) + i - 1 )) ,\n static_cast(i) )) ;\n }\n return exposum == n ;\n}\n\nint main( ) {\n std::vector disariums ;\n int current = 0 ;\n while ( disariums.size( ) != 18 ){\n if ( isDisarium( current ) ) \n disariums.push_back( current ) ;\n current++ ;\n }\n for ( int d : disariums ) \n std::cout << d << \" \" ;\n std::cout << std::endl ;\n return 0 ;\n}"} {"title": "Display a linear combination", "language": "C++ from D", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "#include \n#include \n#include \n#include \n\ntemplate\nstd::ostream& operator<<(std::ostream& os, const std::vector& v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n return os << ']';\n}\n\nstd::ostream& operator<<(std::ostream& os, const std::string& s) {\n return os << s.c_str();\n}\n\nstd::string linearCombo(const std::vector& c) {\n std::stringstream ss;\n for (size_t i = 0; i < c.size(); i++) {\n int n = c[i];\n if (n < 0) {\n if (ss.tellp() == 0) {\n ss << '-';\n } else {\n ss << \" - \";\n }\n } else if (n > 0) {\n if (ss.tellp() != 0) {\n ss << \" + \";\n }\n } else {\n continue;\n }\n\n int av = abs(n);\n if (av != 1) {\n ss << av << '*';\n }\n ss << \"e(\" << i + 1 << ')';\n }\n if (ss.tellp() == 0) {\n return \"0\";\n }\n return ss.str();\n}\n\nint main() {\n using namespace std;\n\n vector> combos{\n {1, 2, 3},\n {0, 1, 2, 3},\n {1, 0, 3, 4},\n {1, 2, 0},\n {0, 0, 0},\n {0},\n {1, 1, 1},\n {-1, -1, -1},\n {-1, -2, 0, -3},\n {-1},\n };\n\n for (auto& c : combos) {\n stringstream ss;\n ss << c;\n cout << setw(15) << ss.str() << \" -> \";\n cout << linearCombo(c) << '\\n';\n }\n\n return 0;\n}"} {"title": "Diversity prediction theorem", "language": "C++", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "#include \n#include \n#include \n\nfloat sum(const std::vector &array)\n{\n return std::accumulate(array.begin(), array.end(), 0.0);\n}\n\nfloat square(float x)\n{\n return x * x;\n}\n\nfloat mean(const std::vector &array)\n{\n return sum(array) / array.size();\n}\n\nfloat averageSquareDiff(float a, const std::vector &predictions)\n{\n std::vector results;\n for (float x : predictions)\n results.push_back(square(x - a));\n return mean(results);\n}\n\nvoid diversityTheorem(float truth, const std::vector &predictions)\n{\n float average = mean(predictions);\n std::cout\n << \"average-error: \" << averageSquareDiff(truth, predictions) << \"\\n\"\n << \"crowd-error: \" << square(truth - average) << \"\\n\"\n << \"diversity: \" << averageSquareDiff(average, predictions) << std::endl;\n}\n\nint main() {\n diversityTheorem(49, {48,47,51});\n diversityTheorem(49, {48,47,51,42});\n return 0;\n}\n"} {"title": "Doomsday rule", "language": "C++", "task": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "#include \n#include \n\nstruct Date {\n std::uint16_t year;\n std::uint8_t month;\n std::uint8_t day;\n};\n\nconstexpr bool leap(int year) {\n return year%4==0 && (year%100!=0 || year%400==0);\n}\n\nconst std::string& weekday(const Date& date) {\n static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};\n static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};\n \n static const std::string days[] = {\n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\"\n };\n \n unsigned const c = date.year/100, r = date.year%100;\n unsigned const s = r/12, t = r%12;\n \n unsigned const c_anchor = (5 * (c%4) + 2) % 7;\n unsigned const doom = (s + t + t/4 + c_anchor) % 7;\n unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];\n return days[(doom+date.day-anchor+7)%7];\n}\n\nint main(void) {\n const std::string months[] = {\"\",\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n };\n \n const Date dates[] = {\n {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},\n {2077,2,12}, {2101,4,2}\n };\n \n for (const Date& d : dates) {\n std::cout << months[d.month] << \" \" << (int)d.day << \", \" << d.year;\n std::cout << (d.year > 2021 ? \" will be \" : \" was \");\n std::cout << \"on a \" << weekday(d) << std::endl;\n }\n \n return 0;\n}"} {"title": "Dot product", "language": "C++", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "#include \n#include \n\nint main()\n{\n int a[] = { 1, 3, -5 };\n int b[] = { 4, -2, -1 };\n\n std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl;\n\n return 0;\n}"} {"title": "Draw a clock", "language": "C++", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nconst int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20,\n MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20;\nconst float PI = 3.1415926536f;\n\n//--------------------------------------------------------------------------------------------------\nclass vector2\n{\npublic:\n vector2() { x = y = 0; }\n vector2( int a, int b ) { x = a; y = b; }\n void set( int a, int b ) { x = a; y = b; }\n void rotate( float angle_r )\n {\n\tfloat _x = static_cast( x ),\n\t _y = static_cast( y ),\n\t s = sinf( angle_r ),\n\t c = cosf( angle_r ),\n\t a = _x * c - _y * s,\n\t b = _x * s + _y * c;\n\n\tx = static_cast( a );\n\ty = static_cast( b );\n }\n int x, y;\n};\n//--------------------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n }\n\n bool create( int w, int h )\n {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes = 1;\n\tbi.bmiHeader.biWidth = w;\n\tbi.bmiHeader.biHeight = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n }\n\n void clear( BYTE clr = 0 )\n {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n\n void setBrushColor( DWORD bClr )\n {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n }\n\n void setPenColor( DWORD c )\n {\n\tclr = c;\n\tcreatePen();\n }\n\n void setPenWidth( int w )\n {\n\twid = w;\n\tcreatePen();\n }\n\n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO infoheader;\n\tBITMAP bitmap;\n\tDWORD wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\t\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n }\n\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n\nprivate:\n void createPen()\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n }\n\n HBITMAP bmp;\n HDC hdc;\n HPEN pen;\n HBRUSH brush;\n void *pBits;\n int width, height, wid;\n DWORD clr;\n};\n//--------------------------------------------------------------------------------------------------\nclass clock\n{\npublic:\n clock() \n {\n\t_bmp.create( BMP_SIZE, BMP_SIZE );\n\t_bmp.clear( 100 );\n\t_bmp.setPenWidth( 2 );\n\t_ang = DegToRadian( 6 );\n }\n\t\n void setNow()\n {\n\tGetLocalTime( &_sysTime );\n\tdraw();\n }\n\n float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }\n\n void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n void drawTicks( HDC dc )\n {\n\tvector2 line;\n\t_bmp.setPenWidth( 1 );\n\tfor( int x = 0; x < 60; x++ )\n\t{\n\t line.set( 0, 50 );\n\t line.rotate( static_cast( x + 30 ) * _ang );\n\t MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL );\n\t LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) );\n\t}\n\n\t_bmp.setPenWidth( 3 );\n\tfor( int x = 0; x < 60; x += 5 )\n\t{\n\t line.set( 0, 50 );\n\t line.rotate( static_cast( x + 30 ) * _ang );\n\t MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL );\n\t LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) );\n\t}\n }\n\n void drawHands( HDC dc )\n {\n\tfloat hp = DegToRadian( ( 30.0f * static_cast( _sysTime.wMinute ) ) / 60.0f );\n\tint h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5;\n\t\t\n\t_bmp.setPenWidth( 3 );\n\t_bmp.setPenColor( RGB( 0, 0, 255 ) );\n\tdrawHand( dc, HOUR_LEN, ( _ang * static_cast( 30 + h ) ) + hp );\n\n\t_bmp.setPenColor( RGB( 0, 128, 0 ) );\n\tdrawHand( dc, MIN_LEN, _ang * static_cast( 30 + _sysTime.wMinute ) );\n\n\t_bmp.setPenWidth( 2 );\n\t_bmp.setPenColor( RGB( 255, 0, 0 ) );\n\tdrawHand( dc, SEC_LEN, _ang * static_cast( 30 + _sysTime.wSecond ) );\n }\n\n void drawHand( HDC dc, int len, float ang )\n {\n\tvector2 line;\n\tline.set( 0, len );\n\tline.rotate( ang );\n\tMoveToEx( dc, CENTER, CENTER, NULL );\n\tLineTo( dc, line.x + CENTER, line.y + CENTER );\n }\n\n void draw()\n {\n\tHDC dc = _bmp.getDC();\n\n\t_bmp.setBrushColor( RGB( 250, 250, 250 ) );\n\tEllipse( dc, 0, 0, BMP_SIZE, BMP_SIZE );\n\t_bmp.setBrushColor( RGB( 230, 230, 230 ) );\n\tEllipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 );\n\n\tdrawTicks( dc );\n\tdrawHands( dc );\n\n\t_bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 );\n\tEllipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 );\n\n\t_wdc = GetDC( _hwnd );\n\tBitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, _wdc );\n }\n\n myBitmap _bmp;\n HWND _hwnd;\n HDC _wdc;\n SYSTEMTIME _sysTime;\n float _ang;\n};\n//--------------------------------------------------------------------------------------------------\nclass wnd\n{\npublic:\n wnd() { _inst = this; }\n int wnd::Run( HINSTANCE hInst )\n {\n\t_hInst = hInst;\n\t_hwnd = InitAll();\n\tSetTimer( _hwnd, MY_TIMER, 1000, NULL );\n\t_clock.setHWND( _hwnd );\n\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t }\n\t}\n\treturn UnregisterClass( \"_MY_CLOCK_\", _hInst );\n }\nprivate:\n void wnd::doPaint( HDC dc ) { _clock.setNow(); }\n void wnd::doTimer() { _clock.setNow(); }\n static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n {\n\tswitch( msg )\n\t{\n\t case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t case WM_PAINT:\n\t {\n\t\tPAINTSTRUCT ps;\n\t\tHDC dc = BeginPaint( hWnd, &ps );\n\t\t_inst->doPaint( dc );\n\t\tEndPaint( hWnd, &ps );\n\t\treturn 0;\n\t }\n\t case WM_TIMER: _inst->doTimer(); break;\n\t default:\n\t\treturn DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n }\n\n HWND InitAll()\n {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize = sizeof( WNDCLASSEX );\n\twcex.style = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc = ( WNDPROC )WndProc;\n\twcex.hInstance = _hInst;\n\twcex.hCursor = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_CLOCK_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_CLOCK_\", \".: Clock -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n }\n\n static wnd* _inst;\n HINSTANCE _hInst;\n HWND _hwnd;\n clock _clock;\n};\nwnd* wnd::_inst = 0;\n//--------------------------------------------------------------------------------------------------\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n wnd myWnd;\n return myWnd.Run( hInstance );\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Duffinian numbers", "language": "C++", "task": "A '''Duffinian number''' is a composite number '''k''' that is relatively prime to its sigma sum '''s'''.\n\n''The sigma sum of '''k''' is the sum of the divisors of '''k'''.''\n\n\n;E.G.\n\n'''161''' is a '''Duffinian number'''. \n* It is composite. (7 x 23)\n* The sigma sum '''192''' (1 + 7 + 23 + 161) is relatively prime to '''161'''. \n\n\nDuffinian numbers are very common.\n\nIt is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.\n\nLess common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.\n\nMuch, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).\n\nIt is not possible to have six consecutive Duffinian numbers\n\n\n;Task\n* Find and show the first 50 Duffinian numbers.\n* Find and show at least the first 15 Duffinian triplets.\n\n\n;See also\n;* Numbers Aplenty - Duffinian numbers\n;* OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)\n\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nbool duffinian(int n) {\n if (n == 2)\n return false;\n int total = 1, power = 2, m = n;\n for (; (n & 1) == 0; power <<= 1, n >>= 1)\n total += power;\n for (int p = 3; p * p <= n; p += 2) {\n int sum = 1;\n for (power = p; n % p == 0; power *= p, n /= p)\n sum += power;\n total *= sum;\n }\n if (m == n)\n return false;\n if (n > 1)\n total *= n + 1;\n return std::gcd(total, m) == 1;\n}\n\nint main() {\n std::cout << \"First 50 Duffinian numbers:\\n\";\n for (int n = 1, count = 0; count < 50; ++n) {\n if (duffinian(n))\n std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\\n' : ' ');\n }\n std::cout << \"\\nFirst 50 Duffinian triplets:\\n\";\n for (int n = 1, m = 0, count = 0; count < 50; ++n) {\n if (duffinian(n))\n ++m;\n else\n m = 0;\n if (m == 3) {\n std::ostringstream os;\n os << '(' << n - 2 << \", \" << n - 1 << \", \" << n << ')';\n std::cout << std::left << std::setw(24) << os.str()\n << (++count % 3 == 0 ? '\\n' : ' ');\n }\n }\n std::cout << '\\n';\n}"} {"title": "Dutch national flag problem", "language": "C++", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "#include \n#include \n\n// Dutch national flag problem\ntemplate \nvoid dnf_partition(BidIt first, BidIt last, const T& low, const T& high)\n{\n for (BidIt next = first; next != last; ) {\n if (*next < low) {\n std::iter_swap(first++, next++);\n } else if (!(*next < high)) {\n std::iter_swap(next, --last);\n } else {\n ++next;\n }\n }\n}\n\nenum Colors { RED, WHITE, BLUE };\n\nvoid print(const Colors *balls, size_t size)\n{\n static const char *label[] = { \"red\", \"white\", \"blue\" };\n\n std::cout << \"Balls:\";\n for (size_t i = 0; i < size; ++i) {\n std::cout << ' ' << label[balls[i]];\n }\n std::cout << \"\\nSorted: \" << std::boolalpha << std::is_sorted(balls, balls + size) << '\\n';\n}\n\nint main()\n{\n Colors balls[] = { RED, WHITE, BLUE, RED, WHITE, BLUE, RED, WHITE, BLUE };\n\n std::random_shuffle(balls, balls + 9);\n print(balls, 9);\n\n dnf_partition(balls, balls + 9, WHITE, BLUE);\n print(balls, 9);\n}"} {"title": "Eban numbers", "language": "C++ from D", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count\n:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count\n:::* show a count of all eban numbers up and including '''10,000'''\n:::* show a count of all eban numbers up and including '''100,000'''\n:::* show a count of all eban numbers up and including '''1,000,000'''\n:::* show a count of all eban numbers up and including '''10,000,000'''\n:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "#include \n\nstruct Interval {\n int start, end;\n bool print;\n};\n\nint main() {\n Interval intervals[] = {\n {2, 1000, true},\n {1000, 4000, true},\n {2, 10000, false},\n {2, 100000, false},\n {2, 1000000, false},\n {2, 10000000, false},\n {2, 100000000, false},\n {2, 1000000000, false},\n };\n\n for (auto intv : intervals) {\n if (intv.start == 2) {\n std::cout << \"eban numbers up to and including \" << intv.end << \":\\n\";\n } else {\n std::cout << \"eban numbers bwteen \" << intv.start << \" and \" << intv.end << \" (inclusive):\\n\";\n }\n\n int count = 0;\n for (int i = intv.start; i <= intv.end; i += 2) {\n int b = i / 1000000000;\n int r = i % 1000000000;\n int m = r / 1000000;\n r = i % 1000000;\n int t = r / 1000;\n r %= 1000;\n if (m >= 30 && m <= 66) m %= 10;\n if (t >= 30 && t <= 66) t %= 10;\n if (r >= 30 && r <= 66) r %= 10;\n if (b == 0 || b == 2 || b == 4 || b == 6) {\n if (m == 0 || m == 2 || m == 4 || m == 6) {\n if (t == 0 || t == 2 || t == 4 || t == 6) {\n if (r == 0 || r == 2 || r == 4 || r == 6) {\n if (intv.print) std::cout << i << ' ';\n count++;\n }\n }\n }\n }\n }\n if (intv.print) {\n std::cout << '\\n';\n }\n std::cout << \"count = \" << count << \"\\n\\n\";\n }\n\n return 0;\n}"} {"title": "Eertree", "language": "C++ from D", "task": "An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. \n\nThe data structure has commonalities to both ''tries'' and ''suffix trees''.\n See links below. \n\n\n;Task:\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\n\n;See also:\n* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n\n", "solution": "#include \n#include \n#include \n#include \n\nstruct Node {\n int length;\n std::map edges;\n int suffix;\n\n Node(int l) : length(l), suffix(0) {\n /* empty */\n }\n\n Node(int l, const std::map& m, int s) : length(l), edges(m), suffix(s) {\n /* empty */\n }\n};\n\nconstexpr int evenRoot = 0;\nconstexpr int oddRoot = 1;\n\nstd::vector eertree(const std::string& s) {\n std::vector tree = {\n Node(0, {}, oddRoot),\n Node(-1, {}, oddRoot)\n };\n int suffix = oddRoot;\n int n, k;\n\n for (size_t i = 0; i < s.length(); ++i) {\n char c = s[i];\n for (n = suffix; ; n = tree[n].suffix) {\n k = tree[n].length;\n int b = i - k - 1;\n if (b >= 0 && s[b] == c) {\n break;\n }\n }\n\n auto it = tree[n].edges.find(c);\n auto end = tree[n].edges.end();\n if (it != end) {\n suffix = it->second;\n continue;\n }\n suffix = tree.size();\n tree.push_back(Node(k + 2));\n tree[n].edges[c] = suffix;\n if (tree[suffix].length == 1) {\n tree[suffix].suffix = 0;\n continue;\n }\n while (true) {\n n = tree[n].suffix;\n int b = i - tree[n].length - 1;\n if (b >= 0 && s[b] == c) {\n break;\n }\n }\n tree[suffix].suffix = tree[n].edges[c];\n }\n\n return tree;\n}\n\nstd::vector subPalindromes(const std::vector& tree) {\n std::vector s;\n\n std::function children;\n children = [&children, &tree, &s](int n, std::string p) {\n auto it = tree[n].edges.cbegin();\n auto end = tree[n].edges.cend();\n for (; it != end; it = std::next(it)) {\n auto c = it->first;\n auto m = it->second;\n\n std::string pl = c + p + c;\n s.push_back(pl);\n children(m, pl);\n }\n };\n children(0, \"\");\n\n auto it = tree[1].edges.cbegin();\n auto end = tree[1].edges.cend();\n for (; it != end; it = std::next(it)) {\n auto c = it->first;\n auto n = it->second;\n\n std::string ct(1, c);\n s.push_back(ct);\n\n children(n, ct);\n }\n\n return s;\n}\n\nint main() {\n using namespace std;\n\n auto tree = eertree(\"eertree\");\n auto pal = subPalindromes(tree);\n\n auto it = pal.cbegin();\n auto end = pal.cend();\n\n cout << \"[\";\n if (it != end) {\n cout << it->c_str();\n it++;\n }\n while (it != end) {\n cout << \", \" << it->c_str();\n it++;\n }\n cout << \"]\" << endl;\n\n return 0;\n}"} {"title": "Egyptian division", "language": "C++ from C", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "#include \n#include \n\ntypedef unsigned long ulong;\n\n/*\n * Remainder is an out paramerter. Use nullptr if the remainder is not needed.\n */\nulong egyptian_division(ulong dividend, ulong divisor, ulong* remainder) {\n constexpr int SIZE = 64;\n ulong powers[SIZE];\n ulong doublings[SIZE];\n int i = 0;\n\n for (; i < SIZE; ++i) {\n powers[i] = 1 << i;\n doublings[i] = divisor << i;\n if (doublings[i] > dividend) {\n break;\n }\n }\n\n ulong answer = 0;\n ulong accumulator = 0;\n\n for (i = i - 1; i >= 0; --i) {\n /*\n * If the current value of the accumulator added to the\n * doublings cell would be less than or equal to the\n * dividend then add it to the accumulator\n */\n if (accumulator + doublings[i] <= dividend) {\n accumulator += doublings[i];\n answer += powers[i];\n }\n }\n\n if (remainder) {\n *remainder = dividend - accumulator;\n }\n return answer;\n}\n\nvoid print(ulong a, ulong b) {\n using namespace std;\n\n ulong x, y;\n x = egyptian_division(a, b, &y);\n\n cout << a << \" / \" << b << \" = \" << x << \" remainder \" << y << endl;\n assert(a == b * x + y);\n}\n\nint main() {\n print(580, 34);\n\n return 0;\n}"} {"title": "Elementary cellular automaton", "language": "C++", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "#include \n#include \n\n#define SIZE\t 80\n#define RULE 30\n#define RULE_TEST(x) (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset &s) {\n int i;\n std::bitset t(0);\n t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] );\n for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset s) {\n int i;\n for (i = SIZE; --i; ) printf(\"%c\", s[i] ? '#' : ' ');\n printf(\"\\n\");\n}\nint main() {\n int i;\n std::bitset state(1);\n state <<= SIZE / 2;\n for (i=0; i<10; i++) {\n\tshow(state);\n\tevolve(state);\n }\n return 0;\n}"} {"title": "Elementary cellular automaton/Infinite length", "language": "C++", "task": "The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.\n\nTo be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.\n\nExamples:\n\n\n1 -> ..., 0, 0, 1, 0, 0, ...\n0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...\n1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...\n\n\nMore complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.\n\n", "solution": "#include \n#include \n#include \n\nclass oo {\npublic:\n void evolve( int l, int rule ) {\n std::string cells = \"O\";\n std::cout << \" Rule #\" << rule << \":\\n\";\n for( int x = 0; x < l; x++ ) {\n addNoCells( cells );\n std::cout << std::setw( 40 + ( static_cast( cells.length() ) >> 1 ) ) << cells << \"\\n\";\n step( cells, rule );\n }\n }\nprivate:\n void step( std::string& cells, int rule ) {\n int bin;\n std::string newCells;\n for( size_t i = 0; i < cells.length() - 2; i++ ) {\n bin = 0;\n for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {\n bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );\n }\n newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );\n }\n cells = newCells;\n }\n void addNoCells( std::string& s ) {\n char l = s.at( 0 ) == 'O' ? '.' : 'O',\n r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';\n s = l + s + r;\n s = l + s + r;\n }\n};\nint main( int argc, char* argv[] ) {\n oo o;\n o.evolve( 35, 90 );\n std::cout << \"\\n\";\n return 0;\n}\n"} {"title": "Elementary cellular automaton/Random number generator", "language": "C++", "task": "Mathematica software for its default random number generator.\n\nSteven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.\n\nThe purpose of this task is to demonstrate this. With the code written in the most significant.\n\nYou can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.\n\nFor extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.\n\n;Reference:\n* Cellular automata: Is Rule 30 random? (PDF).\n\n\n", "solution": "#include \n#include \n\n#define SIZE\t 80\n#define RULE 30\n#define RULE_TEST(x) (RULE & 1 << (7 & (x)))\n\nvoid evolve(std::bitset &s) {\n int i;\n std::bitset t(0);\n t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );\n t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] );\n for (i = 1; i < SIZE-1; i++)\n\tt[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );\n for (i = 0; i < SIZE; i++) s[i] = t[i];\n}\nvoid show(std::bitset s) {\n int i;\n for (i = SIZE; i--; ) printf(\"%c\", s[i] ? '#' : ' ');\n printf(\"|\\n\");\n}\nunsigned char byte(std::bitset &s) {\n unsigned char b = 0;\n int i;\n for (i=8; i--; ) {\n\tb |= s[0] << i; \n\tevolve(s);\n }\n return b;\n}\n\nint main() {\n int i;\n std::bitset state(1);\n for (i=10; i--; )\n\tprintf(\"%u%c\", byte(state), i ? ' ' : '\\n');\n return 0;\n}"} {"title": "Elliptic curve arithmetic", "language": "C++", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\n// define a type for the points on the elliptic curve that behaves\n// like a built in type. \nclass EllipticPoint\n{\n double m_x, m_y;\n static constexpr double ZeroThreshold = 1e20;\n static constexpr double B = 7; // the 'b' in y^2 = x^3 + a * x + b\n // 'a' is 0\n \n void Double() noexcept\n {\n if(IsZero())\n {\n // doubling zero is still zero\n return;\n }\n // based on the property of the curve, the line going through the\n // current point and the negative doubled point is tangent to the\n // curve at the current point. wikipedia has a nice diagram.\n if(m_y == 0)\n {\n // at this point the tangent to the curve is vertical.\n // this point doubled is 0\n *this = EllipticPoint();\n }\n else\n {\n double L = (3 * m_x * m_x) / (2 * m_y);\n double newX = L * L - 2 * m_x;\n m_y = L * (m_x - newX) - m_y;\n m_x = newX;\n }\n }\n \npublic:\n friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);\n\n // Create a point that is initialized to Zero\n constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}\n\n // Create a point based on the yCoordiante. For a curve with a = 0 and b = 7\n // there is only one x for each y\n explicit EllipticPoint(double yCoordinate) noexcept\n {\n m_y = yCoordinate;\n m_x = cbrt(m_y * m_y - B);\n }\n\n // Check if the point is 0\n bool IsZero() const noexcept\n {\n // when the elliptic point is at 0, y = +/- infinity\n bool isNotZero = abs(m_y) < ZeroThreshold;\n return !isNotZero;\n }\n\n // make a negative version of the point (p = -q)\n EllipticPoint operator-() const noexcept\n {\n EllipticPoint negPt;\n negPt.m_x = m_x;\n negPt.m_y = -m_y;\n \n return negPt;\n }\n\n // add a point to this one ( p+=q )\n EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept\n {\n if(IsZero())\n {\n *this = rhs;\n }\n else if (rhs.IsZero())\n {\n // since rhs is zero this point does not need to be\n // modified\n }\n else\n {\n double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);\n if(isfinite(L))\n {\n double newX = L * L - m_x - rhs.m_x;\n m_y = L * (m_x - newX) - m_y;\n m_x = newX;\n }\n else\n {\n if(signbit(m_y) != signbit(rhs.m_y))\n {\n // in this case rhs == -lhs, the result should be 0\n *this = EllipticPoint();\n }\n else\n {\n // in this case rhs == lhs.\n Double();\n }\n }\n }\n\n return *this;\n }\n\n // subtract a point from this one (p -= q)\n EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept\n {\n *this+= -rhs;\n return *this;\n }\n \n // multiply the point by an integer (p *= 3)\n EllipticPoint& operator*=(int rhs) noexcept\n {\n EllipticPoint r;\n EllipticPoint p = *this;\n\n if(rhs < 0)\n {\n // change p * -rhs to -p * rhs\n rhs = -rhs;\n p = -p;\n }\n \n for (int i = 1; i <= rhs; i <<= 1) \n {\n if (i & rhs) r += p;\n p.Double();\n }\n\n *this = r;\n return *this;\n }\n};\n\n// add points (p + q)\ninline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n lhs += rhs;\n return lhs;\n}\n\n// subtract points (p - q)\ninline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept\n{\n lhs += -rhs;\n return lhs;\n}\n\n// multiply by an integer (p * 3)\ninline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept\n{\n lhs *= rhs;\n return lhs;\n}\n\n// multiply by an integer (3 * p)\ninline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept\n{\n rhs *= lhs;\n return rhs;\n}\n\n\n// print the point\nostream& operator<<(ostream& os, const EllipticPoint& pt)\n{\n if(pt.IsZero()) cout << \"(Zero)\\n\";\n else cout << \"(\" << pt.m_x << \", \" << pt.m_y << \")\\n\";\n return os;\n}\n\nint main(void) {\n const EllipticPoint a(1), b(2);\n cout << \"a = \" << a;\n cout << \"b = \" << b;\n const EllipticPoint c = a + b;\n cout << \"c = a + b = \" << c;\n cout << \"a + b - c = \" << a + b - c;\n cout << \"a + b - (b + a) = \" << a + b - (b + a) << \"\\n\";\n\n cout << \"a + a + a + a + a - 5 * a = \" << a + a + a + a + a - 5 * a;\n cout << \"a * 12345 = \" << a * 12345;\n cout << \"a * -12345 = \" << a * -12345;\n cout << \"a * 12345 + a * -12345 = \" << a * 12345 + a * -12345;\n cout << \"a * 12345 - (a * 12000 + a * 345) = \" << a * 12345 - (a * 12000 + a * 345);\n cout << \"a * 12345 - (a * 12001 + a * 345) = \" << a * 12345 - (a * 12000 + a * 344) << \"\\n\";\n\n const EllipticPoint zero;\n EllipticPoint g;\n cout << \"g = zero = \" << g;\n cout << \"g += a = \" << (g+=a);\n cout << \"g += zero = \" << (g+=zero);\n cout << \"g += b = \" << (g+=b);\n cout << \"b + b - b * 2 = \" << (b + b - b * 2) << \"\\n\";\n\n EllipticPoint special(0); // the point where the curve crosses the x-axis\n cout << \"special = \" << special; // this has the minimum possible value for x\n cout << \"special *= 2 = \" << (special*=2); // doubling it gives zero\n \n return 0;\n}"} {"title": "Empty string", "language": "C++", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "#include \n\n// ...\n\n\n // empty string declaration\nstd::string str; // (default constructed)\nstd::string str(); // (default constructor, no parameters)\nstd::string str{}; // (default initialized)\nstd::string str(\"\"); // (const char[] conversion)\nstd::string str{\"\"}; // (const char[] initializer list)\n\n\n\nif (str.empty()) { ... } // to test if string is empty\n\n// we could also use the following\nif (str.length() == 0) { ... }\nif (str == \"\") { ... }\n\n// make a std::string empty\nstr.clear(); // (builtin clear function)\nstr = \"\"; // replace contents with empty string\nstr = {}; // swap contents with temp string (empty),then destruct temp\n\n // swap with empty string\nstd::string tmp{}; // temp empty string \nstr.swap(tmp); // (builtin swap function)\nstd::swap(str, tmp); // swap contents with tmp\n\n\n// create an array of empty strings\nstd::string s_array[100]; // 100 initialized to \"\" (fixed size) \nstd::array arr; // 100 initialized to \"\" (fixed size)\nstd::vector(100,\"\"); // 100 initialized to \"\" (variable size, 100 starting size)\n\n// create empty string as default parameter\nvoid func( std::string& s = {} ); // {} generated default std:string instance\n"} {"title": "Entropy/Narcissist", "language": "C++", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\nstring readFile (string path) {\n string contents;\n string line;\n ifstream inFile(path);\n while (getline (inFile, line)) {\n contents.append(line);\n contents.append(\"\\n\");\n }\n inFile.close();\n return contents;\n}\n\ndouble entropy (string X) {\n const int MAXCHAR = 127;\n int N = X.length();\n int count[MAXCHAR];\n double count_i;\n char ch;\n double sum = 0.0;\n for (int i = 0; i < MAXCHAR; i++) count[i] = 0;\n for (int pos = 0; pos < N; pos++) {\n ch = X[pos];\n count[(int)ch]++;\n }\n for (int n_i = 0; n_i < MAXCHAR; n_i++) {\n count_i = count[n_i];\n if (count_i > 0) sum -= count_i / N * log2(count_i / N);\n }\n return sum;\n}\n\nint main () {\n cout<\n#include \n#include \n#include \n\ntemplate \nstd::vector equilibrium(T first, T last)\n{\n typedef typename std::iterator_traits::value_type value_t;\n\n value_t left = 0;\n value_t right = std::accumulate(first, last, value_t(0));\n std::vector result;\n\n for (size_t index = 0; first != last; ++first, ++index)\n {\n right -= *first;\n if (left == right)\n {\n result.push_back(index);\n }\n left += *first;\n }\n return result;\n}\n\ntemplate \nvoid print(const T& value)\n{\n std::cout << value << \"\\n\";\n}\n\nint main() \n{\n const int data[] = { -7, 1, 5, 2, -4, 3, 0 };\n\n std::vector indices(equilibrium(data, data + 7));\n\n std::for_each(indices.begin(), indices.end(), print);\n}"} {"title": "Erd\u0151s-Nicolas numbers", "language": "C++ from ALGOL 68", "task": "Definition\nAn perfect but is equal to the sum of its first '''k''' divisors (arranged in ascending order and including one) for some value of '''k''' greater than one.\n\n;Examples\n24 is an Erdos-Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.\n\n6 is not an Erdos-Nicolas number because it is perfect (1 + 2 + 3 = 6).\n\n48 is not an Erdos-Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.\n\n;Task\n\nFind and show here the first 8 Erdos-Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.\n\n;Stretch\nDo the same for any further Erdos-Nicolas numbers which you have the patience for.\n\n;Note\nAs all known Erdos-Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.\n\n;Reference\n* OEIS:A194472 - Erdos-Nicolas numbers\n\n", "solution": "#include \n#include \n#include \n\nint main() {\n const int max_number = 100000000;\n std::vector dsum(max_number + 1, 1);\n std::vector dcount(max_number + 1, 1);\n for (int i = 2; i <= max_number; ++i) {\n for (int j = i + i; j <= max_number; j += i) {\n if (dsum[j] == j) {\n std::cout << std::setw(8) << j\n << \" equals the sum of its first \" << dcount[j]\n << \" divisors\\n\";\n }\n dsum[j] += i;\n ++dcount[j];\n }\n }\n}"} {"title": "Esthetic numbers", "language": "C++ from D", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::string to(int n, int b) {\n static auto BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n std::stringstream ss;\n while (n > 0) {\n auto rem = n % b;\n n = n / b;\n ss << BASE[rem];\n }\n\n auto fwd = ss.str();\n return std::string(fwd.rbegin(), fwd.rend());\n}\n\nuint64_t uabs(uint64_t a, uint64_t b) {\n if (a < b) {\n return b - a;\n }\n return a - b;\n}\n\nbool isEsthetic(uint64_t n, uint64_t b) {\n if (n == 0) {\n return false;\n }\n auto i = n % b;\n n /= b;\n while (n > 0) {\n auto j = n % b;\n if (uabs(i, j) != 1) {\n return false;\n }\n n /= b;\n i = j;\n }\n return true;\n}\n\nvoid listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {\n std::vector esths;\n const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {\n auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {\n if (i >= n && i <= m) {\n esths.push_back(i);\n }\n if (i == 0 || i > m) {\n return;\n }\n auto d = i % 10;\n auto i1 = i * 10 + d - 1;\n auto i2 = i1 + 2;\n if (d == 0) {\n dfs_ref(n, m, i2, dfs_ref);\n } else if (d == 9) {\n dfs_ref(n, m, i1, dfs_ref);\n } else {\n dfs_ref(n, m, i1, dfs_ref);\n dfs_ref(n, m, i2, dfs_ref);\n }\n };\n dfs_impl(n, m, i, dfs_impl);\n };\n\n for (int i = 0; i < 10; i++) {\n dfs(n2, m2, i);\n }\n auto le = esths.size();\n printf(\"Base 10: %d esthetic numbers between %llu and %llu:\\n\", le, n, m);\n if (all) {\n for (size_t c = 0; c < esths.size(); c++) {\n auto esth = esths[c];\n printf(\"%llu \", esth);\n if ((c + 1) % perLine == 0) {\n printf(\"\\n\");\n }\n }\n printf(\"\\n\");\n } else {\n for (int c = 0; c < perLine; c++) {\n auto esth = esths[c];\n printf(\"%llu \", esth);\n }\n printf(\"\\n............\\n\");\n for (size_t i = le - perLine; i < le; i++) {\n auto esth = esths[i];\n printf(\"%llu \", esth);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\nint main() {\n for (int b = 2; b <= 16; b++) {\n printf(\"Base %d: %dth to %dth esthetic numbers:\\n\", b, 4 * b, 6 * b);\n for (int n = 1, c = 0; c < 6 * b; n++) {\n if (isEsthetic(n, b)) {\n c++;\n if (c >= 4 * b) {\n std::cout << to(n, b) << ' ';\n }\n }\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n\n // the following all use the obvious range limitations for the numbers in question\n listEsths(1000, 1010, 9999, 9898, 16, true);\n listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);\n listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);\n listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);\n listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);\n return 0;\n}"} {"title": "Euler's identity", "language": "C++", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "#include \n#include \n\nint main() {\n std::cout << std::exp(std::complex(0.0, M_PI)) + 1.0 << std::endl;\n return 0;\n}"} {"title": "Euler's sum of powers conjecture", "language": "C++", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nbool find()\n{\n const auto MAX = 250;\n vector pow5(MAX);\n for (auto i = 1; i < MAX; i++)\n pow5[i] = (double)i * i * i * i * i;\n for (auto x0 = 1; x0 < MAX; x0++) {\n for (auto x1 = 1; x1 < x0; x1++) {\n for (auto x2 = 1; x2 < x1; x2++) {\n for (auto x3 = 1; x3 < x2; x3++) {\n auto sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3];\n if (binary_search(pow5.begin(), pow5.end(), sum))\n {\n cout << x0 << \" \" << x1 << \" \" << x2 << \" \" << x3 << \" \" << pow(sum, 1.0 / 5.0) << endl;\n return true;\n }\n }\n }\n }\n }\n // not found\n return false;\n}\n\nint main(void)\n{\n int tm = clock();\n if (!find())\n cout << \"Nothing found!\\n\";\n cout << \"time=\" << (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC) << \" milliseconds\\r\\n\";\n return 0;\n}"} {"title": "Even or odd", "language": "C++", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "template < typename T >\nconstexpr inline bool isEven( const T& v )\n{\n return isEven( int( v ) );\n}\n\ntemplate <>\nconstexpr inline bool isEven< int >( const int& v )\n{\n return (v & 1) == 0;\n}\n\ntemplate < typename T >\nconstexpr inline bool isOdd( const T& v )\n{\n return !isEven(v);\n}\n"} {"title": "Evolutionary algorithm", "language": "C++", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::string allowed_chars = \" ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n// class selection contains the fitness function, encapsulates the\n// target string and allows access to it's length. The class is only\n// there for access control, therefore everything is static. The\n// string target isn't defined in the function because that way the\n// length couldn't be accessed outside.\nclass selection\n{\npublic:\n // this function returns 0 for the destination string, and a\n // negative fitness for a non-matching string. The fitness is\n // calculated as the negated sum of the circular distances of the\n // string letters with the destination letters.\n static int fitness(std::string candidate)\n {\n assert(target.length() == candidate.length());\n\n int fitness_so_far = 0;\n\n for (int i = 0; i < target.length(); ++i)\n {\n int target_pos = allowed_chars.find(target[i]);\n int candidate_pos = allowed_chars.find(candidate[i]);\n int diff = std::abs(target_pos - candidate_pos);\n fitness_so_far -= std::min(diff, int(allowed_chars.length()) - diff);\n }\n\n return fitness_so_far;\n }\n\n // get the target string length\n static int target_length() { return target.length(); }\nprivate:\n static std::string target;\n};\n\nstd::string selection::target = \"METHINKS IT IS LIKE A WEASEL\";\n\n// helper function: cyclically move a character through allowed_chars\nvoid move_char(char& c, int distance)\n{\n while (distance < 0)\n distance += allowed_chars.length();\n int char_pos = allowed_chars.find(c);\n c = allowed_chars[(char_pos + distance) % allowed_chars.length()];\n}\n\n// mutate the string by moving the characters by a small random\n// distance with the given probability\nstd::string mutate(std::string parent, double mutation_rate)\n{\n for (int i = 0; i < parent.length(); ++i)\n if (std::rand()/(RAND_MAX + 1.0) < mutation_rate)\n {\n int distance = std::rand() % 3 + 1;\n if(std::rand()%2 == 0)\n move_char(parent[i], distance);\n else\n move_char(parent[i], -distance);\n }\n return parent;\n}\n\n// helper function: tell if the first argument is less fit than the\n// second\nbool less_fit(std::string const& s1, std::string const& s2)\n{\n return selection::fitness(s1) < selection::fitness(s2);\n}\n\nint main()\n{\n int const C = 100;\n\n std::srand(time(0));\n\n std::string parent;\n for (int i = 0; i < selection::target_length(); ++i)\n {\n parent += allowed_chars[std::rand() % allowed_chars.length()];\n }\n\n int const initial_fitness = selection::fitness(parent);\n\n for(int fitness = initial_fitness;\n fitness < 0;\n fitness = selection::fitness(parent))\n {\n std::cout << parent << \": \" << fitness << \"\\n\";\n double const mutation_rate = 0.02 + (0.9*fitness)/initial_fitness;\n std::vector childs;\n childs.reserve(C+1);\n\n childs.push_back(parent);\n for (int i = 0; i < C; ++i)\n childs.push_back(mutate(parent, mutation_rate));\n\n parent = *std::max_element(childs.begin(), childs.end(), less_fit);\n }\n std::cout << \"final string: \" << parent << \"\\n\";\n}"} {"title": "Execute HQ9+", "language": "C++", "task": "Implement a ''' [[HQ9+]] ''' interpreter or compiler.\n\n", "solution": "void runCode(string code)\n{\n int c_len = code.length();\n unsigned accumulator=0;\n int bottles;\n for(int i=0;i 0 );\n break;\n\n case '+':\n //Am I the only one finding this one weird? :o\n accumulator++;\n break;\n }\n }\n};"} {"title": "Exponentiation order", "language": "C++", "task": "This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.\n\n(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)\n\n\n;Task requirements\nShow the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nUsing whatever operator or syntax your language supports (if any), show the results in three lines (with identification):\n \n::::* 5**3**2 \n::::* (5**3)**2\n::::* 5**(3**2)\n\n\nIf there are other methods (or formats) of multiple exponentiations, show them as well. \n\n\n;See also:\n* MathWorld entry: exponentiation\n\n\n;Related tasks:\n* exponentiation operator\n* arbitrary-precision integers (included)\n* [[Exponentiation with infix operators in (or operating on) the base]]\n\n", "solution": "#include \n#include \n\nenum my_int {};\ninline my_int operator^(my_int a, my_int b) { return static_cast(pow(a,b)); }\n\nint main() {\n my_int x = 5, y = 3, z = 2;\n std::cout << \"(5 ^ 3) ^ 2 = \" << ((x^y)^z) << std::endl;\n std::cout << \"5 ^ (3 ^ 2) = \"<< (x^(y^z));\n\t\n return EXIT_SUCCESS;\n}"} {"title": "FASTA format", "language": "C++", "task": "In FASTA. \n\nA FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.\n\n\n;Task:\nWrite a program that reads a FASTA file such as:\n\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n", "solution": "#include \n#include \n\nint main( int argc, char **argv ){\n if( argc <= 1 ){\n std::cerr << \"Usage: \"<' ){ // Identifier marker\n if( !name.empty() ){ // Print out what we read from the last entry\n std::cout << name << \" : \" << content << std::endl;\n name.clear();\n }\n if( !line.empty() ){\n name = line.substr(1);\n }\n content.clear();\n } else if( !name.empty() ){\n if( line.find(' ') != std::string::npos ){ // Invalid sequence--no spaces allowed\n name.clear();\n content.clear();\n } else {\n content += line;\n }\n }\n }\n if( !name.empty() ){ // Print out what we read from the last entry\n std::cout << name << \" : \" << content << std::endl;\n }\n \n return 0;\n}"} {"title": "Factorial primes", "language": "C++", "task": "Definition\nA factorial.\n\nIn other words a non-negative integer '''n''' corresponds to a factorial prime if either '''n'''! - 1 or '''n'''! + 1 is prime. \n\n;Examples\n4 corresponds to the factorial prime 4! - 1 = 23.\n\n5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime.\n\n;Task\nFind and show here the first 10 factorial primes. As well as the prime itself show the factorial number '''n''' to which it corresponds and whether 1 is to be added or subtracted. \n\nAs 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!.\n\n;Stretch\nIf your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes.\n\nAs it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function.\n\nIf a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has.\n\n;Reference\n* OEIS:A088054 - Factorial primes\n\n;Related task\n* Sequence of primorial primes\n\n", "solution": "#include \n#include \n\n#include \n\nusing big_int = mpz_class;\n\nstd::string to_string(const big_int& num, size_t n) {\n std::string str = num.get_str();\n size_t len = str.size();\n if (len > n) {\n str = str.substr(0, n / 2) + \"...\" + str.substr(len - n / 2);\n str += \" (\";\n str += std::to_string(len);\n str += \" digits)\";\n }\n return str;\n}\n\nbool is_probably_prime(const big_int& n) {\n return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;\n}\n\nint main() {\n big_int f = 1;\n for (int i = 0, n = 1; i < 31; ++n) {\n f *= n;\n if (is_probably_prime(f - 1)) {\n ++i;\n std::cout << std::setw(2) << i << \": \" << std::setw(3) << n\n << \"! - 1 = \" << to_string(f - 1, 40) << '\\n';\n }\n if (is_probably_prime(f + 1)) {\n ++i;\n std::cout << std::setw(2) << i << \": \" << std::setw(3) << n\n << \"! + 1 = \" << to_string(f + 1, 40) << '\\n';\n }\n }\n}"} {"title": "Factorions", "language": "C++ from C", "task": "Definition:\nA factorion is a natural number that equals the sum of the factorials of its digits. \n\n\n;Example: \n'''145''' is a factorion in base '''10''' because:\n\n 1! + 4! + 5! = 1 + 24 + 120 = 145 \n\n\n\nIt can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''.\n\n\n;Task:\nWrite a program in your language to demonstrate, by calculating and printing out the factorions, that:\n:* There are '''3''' factorions in base '''9'''\n:* There are '''4''' factorions in base '''10'''\n:* There are '''5''' factorions in base '''11''' \n:* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''')\n\n\n;See also:\n:* '''Wikipedia article'''\n:* '''OEIS:A014080 - Factorions in base 10'''\n:* '''OEIS:A193163 - Factorions in base n'''\n\n", "solution": "#include \n\nclass factorion_t {\npublic:\n factorion_t() {\n f[0] = 1u;\n for (uint n = 1u; n < 12u; n++)\n f[n] = f[n - 1] * n;\n }\n\n bool operator()(uint i, uint b) const {\n uint sum = 0;\n for (uint j = i; j > 0u; j /= b)\n sum += f[j % b];\n return sum == i;\n }\n\nprivate:\n ulong f[12]; //< cache factorials from 0 to 11\n};\n\nint main() {\n factorion_t factorion;\n for (uint b = 9u; b <= 12u; ++b) {\n std::cout << \"factorions for base \" << b << ':';\n for (uint i = 1u; i < 1500000u; ++i)\n if (factorion(i, b))\n std::cout << ' ' << i;\n std::cout << std::endl;\n }\n return 0;\n}"} {"title": "Fairshare between two and more", "language": "C++ from C", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "#include \n#include \n\nint turn(int base, int n) {\n int sum = 0;\n while (n != 0) {\n int rem = n % base;\n n = n / base;\n sum += rem;\n }\n return sum % base;\n}\n\nvoid fairshare(int base, int count) {\n printf(\"Base %2d:\", base);\n for (int i = 0; i < count; i++) {\n int t = turn(base, i);\n printf(\" %2d\", t);\n }\n printf(\"\\n\");\n}\n\nvoid turnCount(int base, int count) {\n std::vector cnt(base, 0);\n\n for (int i = 0; i < count; i++) {\n int t = turn(base, i);\n cnt[t]++;\n }\n\n int minTurn = INT_MAX;\n int maxTurn = INT_MIN;\n int portion = 0;\n for (int i = 0; i < base; i++) {\n if (cnt[i] > 0) {\n portion++;\n }\n if (cnt[i] < minTurn) {\n minTurn = cnt[i];\n }\n if (cnt[i] > maxTurn) {\n maxTurn = cnt[i];\n }\n }\n\n printf(\" With %d people: \", base);\n if (0 == minTurn) {\n printf(\"Only %d have a turn\\n\", portion);\n } else if (minTurn == maxTurn) {\n printf(\"%d\\n\", minTurn);\n } else {\n printf(\"%d or %d\\n\", minTurn, maxTurn);\n }\n}\n\nint main() {\n fairshare(2, 25);\n fairshare(3, 25);\n fairshare(5, 25);\n fairshare(11, 25);\n\n printf(\"How many times does each get a turn in 50000 iterations?\\n\");\n turnCount(191, 50000);\n turnCount(1377, 50000);\n turnCount(49999, 50000);\n turnCount(50000, 50000);\n turnCount(50001, 50000);\n\n return 0;\n}"} {"title": "Farey sequence", "language": "C++", "task": "The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.\n\nThe ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. \n\n\nEach Farey sequence:\n:::* starts with the value '''0''' (zero), denoted by the fraction \\frac{0}{1} \n:::* ends with the value '''1''' (unity), denoted by the fraction \\frac{1}{1}.\n\n\nThe Farey sequences of orders '''1''' to '''5''' are:\n\n:::: {\\bf\\it{F}}_1 = \\frac{0}{1}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_2 = \\frac{0}{1}, \\frac{1}{2}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_3 = \\frac{0}{1}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_4 = \\frac{0}{1}, \\frac{1}{4}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{3}{4}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_5 = \\frac{0}{1}, \\frac{1}{5}, \\frac{1}{4}, \\frac{1}{3}, \\frac{2}{5}, \\frac{1}{2}, \\frac{3}{5}, \\frac{2}{3}, \\frac{3}{4}, \\frac{4}{5}, \\frac{1}{1}\n\n;Task\n* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).\n* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.\n* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length (the number of fractions) of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 x n2 / \\pi2 \n\n;See also:\n* OEIS sequence A006842 numerators of Farey series of order 1, 2, *** \n* OEIS sequence A006843 denominators of Farey series of order 1, 2, *** \n* OEIS sequence A005728 number of fractions in Farey series of order n \n* MathWorld entry Farey sequence\n* Wikipedia entry Farey sequence\n\n", "solution": "#include \n\nstruct fraction {\n fraction(int n, int d) : numerator(n), denominator(d) {}\n int numerator;\n int denominator;\n};\n\nstd::ostream& operator<<(std::ostream& out, const fraction& f) {\n out << f.numerator << '/' << f.denominator;\n return out;\n}\n\nclass farey_sequence {\npublic:\n explicit farey_sequence(int n) : n_(n), a_(0), b_(1), c_(1), d_(n) {}\n fraction next() {\n // See https://en.wikipedia.org/wiki/Farey_sequence#Next_term\n fraction result(a_, b_);\n int k = (n_ + b_)/d_;\n int next_c = k * c_ - a_;\n int next_d = k * d_ - b_;\n a_ = c_;\n b_ = d_;\n c_ = next_c;\n d_ = next_d;\n return result;\n }\n bool has_next() const { return a_ <= n_; }\nprivate:\n int n_, a_, b_, c_, d_;\n};\n\nint main() {\n for (int n = 1; n <= 11; ++n) {\n farey_sequence seq(n);\n std::cout << n << \": \" << seq.next();\n while (seq.has_next())\n std::cout << ' ' << seq.next();\n std::cout << '\\n';\n }\n for (int n = 100; n <= 1000; n += 100) {\n int count = 0;\n for (farey_sequence seq(n); seq.has_next(); seq.next())\n ++count;\n std::cout << n << \": \" << count << '\\n';\n }\n return 0;\n}"} {"title": "Farey sequence", "language": "C++17", "task": "The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.\n\nThe ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. \n\n\nEach Farey sequence:\n:::* starts with the value '''0''' (zero), denoted by the fraction \\frac{0}{1} \n:::* ends with the value '''1''' (unity), denoted by the fraction \\frac{1}{1}.\n\n\nThe Farey sequences of orders '''1''' to '''5''' are:\n\n:::: {\\bf\\it{F}}_1 = \\frac{0}{1}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_2 = \\frac{0}{1}, \\frac{1}{2}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_3 = \\frac{0}{1}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_4 = \\frac{0}{1}, \\frac{1}{4}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{3}{4}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_5 = \\frac{0}{1}, \\frac{1}{5}, \\frac{1}{4}, \\frac{1}{3}, \\frac{2}{5}, \\frac{1}{2}, \\frac{3}{5}, \\frac{2}{3}, \\frac{3}{4}, \\frac{4}{5}, \\frac{1}{1}\n\n;Task\n* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).\n* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.\n* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length (the number of fractions) of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 x n2 / \\pi2 \n\n;See also:\n* OEIS sequence A006842 numerators of Farey series of order 1, 2, *** \n* OEIS sequence A006843 denominators of Farey series of order 1, 2, *** \n* OEIS sequence A005728 number of fractions in Farey series of order n \n* MathWorld entry Farey sequence\n* Wikipedia entry Farey sequence\n\n", "solution": "#include \n#include \n#include \n\nstruct farey_sequence: public std::list> {\n explicit farey_sequence(uint n) : order(n) {\n push_back(std::pair(0, 1));\n uint a = 0, b = 1, c = 1, d = n;\n while (c <= n) {\n const uint k = (n + b) / d;\n const uint next_c = k * c - a;\n const uint next_d = k * d - b;\n a = c;\n b = d;\n c = next_c;\n d = next_d;\n push_back(std::pair(a, b));\n }\n }\n\n const uint order;\n};\n\nstd::ostream& operator<<(std::ostream &out, const farey_sequence &s) {\n out << s.order << \":\";\n for (const auto &f : s)\n out << ' ' << f.first << '/' << f.second;\n return out;\n}\n\nint main() {\n for (uint i = 1u; i <= 11u; ++i)\n std::cout << farey_sequence(i) << std::endl;\n for (uint i = 100u; i <= 1000u; i += 100u) {\n const auto s = farey_sequence(i);\n std::cout << s.order << \": \" << s.size() << \" items\" << std::endl;\n }\n\n return EXIT_SUCCESS;\n}"} {"title": "Fast Fourier transform", "language": "C++", "task": "Calculate the FFT (Fast Fourier Transform) of an input sequence.\n\nThe most general case allows for complex numbers at the input \nand results in a sequence of equal length, again of complex numbers. \nIf you need to restrict yourself to real numbers, the output should \nbe the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. \n\nThe classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "#include \n#include \n#include \n\nconst double PI = 3.141592653589793238460;\n\ntypedef std::complex Complex;\ntypedef std::valarray CArray;\n\n// Cooley\u2013Tukey FFT (in-place, divide-and-conquer)\n// Higher memory requirements and redundancy although more intuitive\nvoid fft(CArray& x)\n{\n const size_t N = x.size();\n if (N <= 1) return;\n\n // divide\n CArray even = x[std::slice(0, N/2, 2)];\n CArray odd = x[std::slice(1, N/2, 2)];\n\n // conquer\n fft(even);\n fft(odd);\n\n // combine\n for (size_t k = 0; k < N/2; ++k)\n {\n Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];\n x[k ] = even[k] + t;\n x[k+N/2] = even[k] - t;\n }\n}\n\n// Cooley-Tukey FFT (in-place, breadth-first, decimation-in-frequency)\n// Better optimized but less intuitive\n// !!! Warning : in some cases this code make result different from not optimased version above (need to fix bug)\n// The bug is now fixed @2017/05/30 \nvoid fft(CArray &x)\n{\n\t// DFT\n\tunsigned int N = x.size(), k = N, n;\n\tdouble thetaT = 3.14159265358979323846264338328L / N;\n\tComplex phiT = Complex(cos(thetaT), -sin(thetaT)), T;\n\twhile (k > 1)\n\t{\n\t\tn = k;\n\t\tk >>= 1;\n\t\tphiT = phiT * phiT;\n\t\tT = 1.0L;\n\t\tfor (unsigned int l = 0; l < k; l++)\n\t\t{\n\t\t\tfor (unsigned int a = l; a < N; a += n)\n\t\t\t{\n\t\t\t\tunsigned int b = a + k;\n\t\t\t\tComplex t = x[a] - x[b];\n\t\t\t\tx[a] += x[b];\n\t\t\t\tx[b] = t * T;\n\t\t\t}\n\t\t\tT *= phiT;\n\t\t}\n\t}\n\t// Decimate\n\tunsigned int m = (unsigned int)log2(N);\n\tfor (unsigned int a = 0; a < N; a++)\n\t{\n\t\tunsigned int b = a;\n\t\t// Reverse bits\n\t\tb = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1));\n\t\tb = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2));\n\t\tb = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4));\n\t\tb = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8));\n\t\tb = ((b >> 16) | (b << 16)) >> (32 - m);\n\t\tif (b > a)\n\t\t{\n\t\t\tComplex t = x[a];\n\t\t\tx[a] = x[b];\n\t\t\tx[b] = t;\n\t\t}\n\t}\n\t//// Normalize (This section make it not working correctly)\n\t//Complex f = 1.0 / sqrt(N);\n\t//for (unsigned int i = 0; i < N; i++)\n\t//\tx[i] *= f;\n}\n\n// inverse fft (in-place)\nvoid ifft(CArray& x)\n{\n // conjugate the complex numbers\n x = x.apply(std::conj);\n\n // forward fft\n fft( x );\n\n // conjugate the complex numbers again\n x = x.apply(std::conj);\n\n // scale the numbers\n x /= x.size();\n}\n\nint main()\n{\n const Complex test[] = { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0 };\n CArray data(test, 8);\n\n // forward fft\n fft(data);\n\n std::cout << \"fft\" << std::endl;\n for (int i = 0; i < 8; ++i)\n {\n std::cout << data[i] << std::endl;\n }\n\n // inverse fft\n ifft(data);\n\n std::cout << std::endl << \"ifft\" << std::endl;\n for (int i = 0; i < 8; ++i)\n {\n std::cout << data[i] << std::endl;\n }\n return 0;\n}"} {"title": "Feigenbaum constant calculation", "language": "C++ from C", "task": "Calculate the Feigenbaum constant. \n\n\n;See:\n:* Details in the Wikipedia article: Feigenbaum constant.\n\n", "solution": "#include \n\nint main() {\n const int max_it = 13;\n const int max_it_j = 10;\n double a1 = 1.0, a2 = 0.0, d1 = 3.2;\n\n std::cout << \" i d\\n\";\n for (int i = 2; i <= max_it; ++i) {\n double a = a1 + (a1 - a2) / d1;\n for (int j = 1; j <= max_it_j; ++j) {\n double x = 0.0;\n double y = 0.0;\n for (int k = 1; k <= 1 << i; ++k) {\n y = 1.0 - 2.0*y*x;\n x = a - x * x;\n }\n a -= x / y;\n }\n double d = (a1 - a2) / (a - a1);\n printf(\"%2d %.8f\\n\", i, d);\n d1 = d;\n a2 = a1;\n a1 = a;\n }\n\n return 0;\n}"} {"title": "Fibonacci n-step number sequences", "language": "C++", "task": "These number series are an expansion of the ordinary [[Fibonacci sequence]] where:\n# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2\n# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3\n# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...\n# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \\sum_{i=1}^{(n)} {F_{k-i}^{(n)}}\n\nFor small values of n, Greek numeric prefixes are sometimes used to individually name each series.\n\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Fibonacci n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Series name !! Values\n|-\n| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\n|-\n| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\n|-\n| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\n|-\n| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\n|-\n| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\n|-\n| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\n|-\n| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\n|-\n| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\n|-\n| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n|}\n\nAllied sequences can be generated where the initial values are changed:\n: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.\n\n\n\n;Task:\n# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\n\n;Related tasks:\n* [[Fibonacci sequence]]\n* Wolfram Mathworld\n* [[Hofstadter Q sequence]]\n* [[Leonardo numbers]]\n\n\n;Also see:\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers\n\n", "solution": "#include \n#include \n\n// This class forms a simple 'generator', where operator() returns the next\n// element in the series. It uses a small sliding window buffer to minimize\n// storage overhead.\nclass nacci_t\n{\n std::vector< int > history;\n unsigned windex; // sliding window index\n unsigned rindex; // result index\n int running_sum; // sum of values in sliding window\n\n public:\n\n nacci_t( unsigned int order, int a0 = 1, int a1 = 1 )\n : history( order + 1 ), windex( 0 ), rindex( order - 1 ), \n running_sum( a0 + a1 )\n {\n // intialize sliding window\n history[order - 1] = a0;\n history[order - 0] = a1;\n }\n\n int operator()() \n {\n int result = history[ rindex ]; // get 'nacci number to return\n running_sum -= history[ windex ]; // old 'nacci falls out of window\n\n history[ windex ] = running_sum; // new 'nacci enters the window\n running_sum += running_sum; // new 'nacci added to the sum\n\n if ( ++windex == history.size() ) windex = 0;\n if ( ++rindex == history.size() ) rindex = 0;\n\n return result;\n }\n};\n\nint main()\n{\n for ( unsigned int i = 2; i <= 10; ++i )\n {\n nacci_t nacci( i ); // fibonacci sequence \n\n std::cout << \"nacci( \" << i << \" ): \";\n\n for ( int j = 0; j < 10; ++j )\n std::cout << \" \" << nacci();\n\n std::cout << std::endl;\n }\n\n for ( unsigned int i = 2; i <= 10; ++i )\n {\n nacci_t lucas( i, 2, 1 ); // Lucas sequence \n\n std::cout << \"lucas( \" << i << \" ): \";\n\n for ( int j = 0; j < 10; ++j )\n std::cout << \" \" << lucas();\n\n std::cout << std::endl;\n }\n}\n"} {"title": "Fibonacci word", "language": "C++", "task": "The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:\n\n Define F_Word1 as '''1'''\n Define F_Word2 as '''0'''\n Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''\n Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2\n\n\n;Task:\nPerform the above steps for n = 37.\n\nYou may display the first few but not the larger values of n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for F_Words '''1''' to '''37''' which shows:\n::* The number of characters in the word\n::* The word's [[Entropy]]\n\n\n;Related tasks: \n* Fibonacci word/fractal\n* [[Entropy]]\n* [[Entropy/Narcissist]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\ndouble log2( double number ) {\n return ( log( number ) / log( 2 ) ) ;\n}\n\ndouble find_entropy( std::string & fiboword ) {\n std::map frequencies ;\n std::for_each( fiboword.begin( ) , fiboword.end( ) ,\n\t [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; \n int numlen = fiboword.length( ) ;\n double infocontent = 0 ;\n for ( std::pair p : frequencies ) {\n double freq = static_cast( p.second ) / numlen ;\n infocontent += freq * log2( freq ) ;\n }\n infocontent *= -1 ;\n return infocontent ;\n}\n\nvoid printLine( std::string &fiboword , int n ) {\n std::cout << std::setw( 5 ) << std::left << n ;\n std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;\n std::cout << \" \" << std::setw( 16 ) << std::setprecision( 13 ) \n << std::left << find_entropy( fiboword ) ;\n std::cout << \"\\n\" ;\n}\n\nint main( ) {\n std::cout << std::setw( 5 ) << std::left << \"N\" ;\n std::cout << std::setw( 12 ) << std::right << \"length\" ;\n std::cout << \" \" << std::setw( 16 ) << std::left << \"entropy\" ; \n std::cout << \"\\n\" ;\n std::string firststring ( \"1\" ) ;\n int n = 1 ;\n printLine( firststring , n ) ;\n std::string secondstring( \"0\" ) ;\n n++ ;\n printLine( secondstring , n ) ;\n while ( n < 37 ) {\n std::string resultstring = firststring + secondstring ;\n firststring.assign( secondstring ) ;\n secondstring.assign( resultstring ) ;\n n++ ;\n printLine( resultstring , n ) ;\n }\n return 0 ;\n}"} {"title": "File extension is in extensions list", "language": "C++", "task": "Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the [[Extract file extension]] task.\n\n\n;Related tasks: \n* [[Extract file extension]]\n* [[String matching]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nbool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {\n const size_t n1 = str.length();\n const size_t n2 = suffix.length();\n if (n1 < n2)\n return false;\n return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),\n [](char c1, char c2) {\n return std::tolower(static_cast(c1))\n == std::tolower(static_cast(c2));\n });\n}\n\nbool filenameHasExtension(const std::string& filename,\n const std::vector& extensions) {\n return std::any_of(extensions.begin(), extensions.end(),\n [&filename](const std::string& extension) {\n return endsWithIgnoreCase(filename, \".\" + extension);\n });\n}\n\nvoid test(const std::string& filename,\n const std::vector& extensions) {\n std::cout << std::setw(20) << std::left << filename\n << \": \" << std::boolalpha\n << filenameHasExtension(filename, extensions) << '\\n';\n}\n\nint main() {\n const std::vector extensions{\"zip\", \"rar\", \"7z\",\n \"gz\", \"archive\", \"A##\", \"tar.bz2\"};\n test(\"MyData.a##\", extensions);\n test(\"MyData.tar.Gz\", extensions);\n test(\"MyData.gzip\", extensions);\n test(\"MyData.7z.backup\", extensions);\n test(\"MyData...\", extensions);\n test(\"MyData\", extensions);\n test(\"MyData_v1.0.tar.bz2\", extensions);\n test(\"MyData_v1.0.bz2\", extensions);\n return 0;\n}"} {"title": "File size distribution", "language": "C++", "task": "Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.\n\n\nMy suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.\n\nDon't forget that empty files may exist, to serve as a marker.\n\n\nIs your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nvoid file_size_distribution(const std::filesystem::path& directory) {\n constexpr size_t n = 9;\n constexpr std::array sizes = { 0, 1000, 10000,\n 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };\n std::array count = { 0 };\n size_t files = 0;\n std::uintmax_t total_size = 0;\n std::filesystem::recursive_directory_iterator iter(directory);\n for (const auto& dir_entry : iter) {\n if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {\n std::uintmax_t file_size = dir_entry.file_size();\n total_size += file_size;\n auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);\n size_t index = std::distance(sizes.begin(), i);\n ++count[index];\n ++files;\n }\n }\n std::cout << \"File size distribution for \" << directory << \":\\n\";\n for (size_t i = 0; i <= n; ++i) {\n if (i == n)\n std::cout << \"> \" << sizes[i - 1];\n else\n std::cout << std::setw(16) << sizes[i];\n std::cout << \" bytes: \" << count[i] << '\\n';\n }\n std::cout << \"Number of files: \" << files << '\\n';\n std::cout << \"Total file size: \" << total_size << \" bytes\\n\";\n}\n\nint main(int argc, char** argv) {\n std::cout.imbue(std::locale(\"\"));\n try {\n const char* directory(argc > 1 ? argv[1] : \".\");\n std::filesystem::path path(directory);\n if (!is_directory(path)) {\n std::cerr << directory << \" is not a directory.\\n\";\n return EXIT_FAILURE;\n }\n file_size_distribution(path);\n } catch (const std::exception& ex) {\n std::cerr << ex.what() << '\\n';\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}"} {"title": "Find duplicate files", "language": "C++", "task": "In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. \n\n\n;Task:\nCreate a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.\n\nThe program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data. \n\nSpecify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements. \n\nIdentify hard links (filenames referencing the same content) in the output if applicable for the filesystem. \n\nFor extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.\n\n", "solution": "#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\"dependencies/xxhash.hpp\" // https://github.com/RedSpah/xxhash_cpp\n\n/**\n* Find ranges (neighbouring elements) of the same value within [begin, end[ and\n* call callback for each such range\n* @param begin start of container\n* @param end end of container (1 beyond last element)\n* @param function returns value for each iterator V(*T&)\n* @param callback void(start, end, value)\n* @return number of range\n*/\ntemplate\nsize_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {\n size_t partitions = 0;\n while (begin != end) {\n auto const& value = getvalue(*begin);\n auto current = begin;\n while (++current != end && getvalue(*current) == value);\n callback(begin, current, value);\n ++partitions;\n begin = current;\n }\n return partitions;\n}\n\nnamespace bi = boost::iostreams;\nnamespace fs = boost::filesystem;\n\nstruct file_entry {\npublic:\n explicit file_entry(fs::directory_entry const & entry) \n : path_{entry.path()}, size_{fs::file_size(entry)}\n {}\n auto size() const { return size_; }\n auto const& path() const { return path_; }\n auto get_hash() {\n if (!hash_)\n hash_ = compute_hash();\n return *hash_;\n }\nprivate:\n xxh::hash64_t compute_hash() {\n bi::mapped_file_source source;\n source.open(this->path());\n if (!source.is_open()) {\n std::cerr << \"Cannot open \" << path() << std::endl;\n throw std::runtime_error(\"Cannot open file\");\n }\n xxh::hash_state64_t hash_stream;\n hash_stream.update(source.data(), size_);\n return hash_stream.digest();\n }\nprivate:\n fs::wpath path_;\n uintmax_t size_;\n std::optional hash_;\n};\n\nusing vector_type = std::vector;\nusing iterator_type = vector_type::iterator;\n\nauto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {\n size_t found = 0, ignored = 0;\n if (!fs::is_directory(path)) {\n std::cerr << path << \" is not a directory!\" << std::endl;\n }\n else {\n std::cerr << \"Searching \" << path << std::endl;\n\n for (auto& e : fs::recursive_directory_iterator(path)) {\n ++found;\n if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)\n file_vector.emplace_back(e);\n else ++ignored;\n }\n }\n return std::make_tuple(found, ignored);\n}\n\nint main(int argn, char* argv[])\n{\n vector_type files;\n for (auto i = 1; i < argn; ++i) {\n fs::wpath path(argv[i]);\n auto [found, ignored] = find_files_in_dir(path, files);\n std::cerr << boost::format{\n \" %1$6d files found\\n\"\n \" %2$6d files ignored\\n\"\n \" %3$6d files added\\n\" } % found % ignored % (found - ignored) \n << std::endl;\n }\n\n std::cerr << \"Found \" << files.size() << \" regular files\" << std::endl;\n // sort files in descending order by file size\n std::sort(std::execution::par_unseq, files.begin(), files.end()\n , [](auto const& a, auto const& b) { return a.size() > b.size(); }\n );\n for_each_adjacent_range(\n std::begin(files)\n , std::end(files)\n , [](vector_type::value_type const& f) { return f.size(); }\n , [](auto start, auto end, auto file_size) {\n // Files with same size\n size_t nr_of_files = std::distance(start, end);\n if (nr_of_files > 1) {\n // sort range start-end by hash\n std::sort(start, end, [](auto& a, auto& b) { \n auto const& ha = a.get_hash();\n auto const& hb = b.get_hash();\n auto const& pa = a.path();\n auto const& pb = b.path();\n return std::tie(ha, pa) < std::tie(hb, pb); \n });\n for_each_adjacent_range(\n start\n , end\n , [](vector_type::value_type& f) { return f.get_hash(); }\n , [file_size](auto hstart, auto hend, auto hash) {\n // Files with same size and same hash are assumed to be identical\n // could resort to compare files byte-by-byte now\n size_t hnr_of_files = std::distance(hstart, hend);\n if (hnr_of_files > 1) {\n std::cout << boost::format{ \"%1$3d files with hash %3$016x and size %2$d\\n\" } \n % hnr_of_files % file_size % hash;\n std::for_each(hstart, hend, [hash, file_size](auto& e) {\n std::cout << '\\t' << e.path() << '\\n';\n }\n );\n }\n }\n );\n }\n }\n );\n \n return 0;\n}\n\n"} {"title": "Find if a point is within a triangle", "language": "C++ from C", "task": "Find if a point is within a triangle.\n\n\n;Task:\n \n::* Assume points are on a plane defined by (x, y) real number coordinates.\n\n::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. \n\n::* You may use any algorithm. \n\n::* Bonus: explain why the algorithm you chose works.\n\n\n;Related tasks:\n* [[Determine_if_two_triangles_overlap]]\n\n\n;Also see:\n:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]\n:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]\n:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]\n:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]\n\n", "solution": "#include \n\nconst double EPS = 0.001;\nconst double EPS_SQUARE = EPS * EPS;\n\ndouble side(double x1, double y1, double x2, double y2, double x, double y) {\n return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);\n}\n\nbool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;\n double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;\n double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;\n return checkSide1 && checkSide2 && checkSide3;\n}\n\nbool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n double xMin = std::min(x1, std::min(x2, x3)) - EPS;\n double xMax = std::max(x1, std::max(x2, x3)) + EPS;\n double yMin = std::min(y1, std::min(y2, y3)) - EPS;\n double yMax = std::max(y1, std::max(y2, y3)) + EPS;\n return !(x < xMin || xMax < x || y < yMin || yMax < y);\n}\n\ndouble distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {\n double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;\n if (dotProduct < 0) {\n return (x - x1) * (x - x1) + (y - y1) * (y - y1);\n } else if (dotProduct <= 1) {\n double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);\n return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;\n } else {\n return (x - x2) * (x - x2) + (y - y2) * (y - y2);\n }\n}\n\nbool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {\n return false;\n }\n if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n return true;\n }\n if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {\n return true;\n }\n if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {\n return true;\n }\n if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {\n return true;\n }\n return false;\n}\n\nvoid printPoint(double x, double y) {\n std::cout << '(' << x << \", \" << y << ')';\n}\n\nvoid printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {\n std::cout << \"Triangle is [\";\n printPoint(x1, y1);\n std::cout << \", \";\n printPoint(x2, y2);\n std::cout << \", \";\n printPoint(x3, y3);\n std::cout << \"]\\n\";\n}\n\nvoid test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {\n printTriangle(x1, y1, x2, y2, x3, y3);\n std::cout << \"Point \";\n printPoint(x, y);\n std::cout << \" is within triangle? \";\n if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {\n std::cout << \"true\\n\";\n } else {\n std::cout << \"false\\n\";\n }\n}\n\nint main() {\n test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);\n test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);\n test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);\n std::cout << '\\n';\n\n test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);\n std::cout << '\\n';\n\n test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);\n std::cout << '\\n';\n\n return 0;\n}"} {"title": "Find limit of recursion", "language": "C++", "task": "{{selection|Short Circuit|Console Program Basics}}\n\n \n\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "#include \n \nvoid recurse(unsigned int i)\n{\n std::cout<\n#include \n\nclass Vector3D {\npublic:\n\tVector3D(double x, double y, double z) {\n\t\tthis->x = x;\n\t\tthis->y = y;\n\t\tthis->z = z;\n\t}\n\n\tdouble dot(const Vector3D& rhs) const {\n\t\treturn x * rhs.x + y * rhs.y + z * rhs.z;\n\t}\n\n\tVector3D operator-(const Vector3D& rhs) const {\n\t\treturn Vector3D(x - rhs.x, y - rhs.y, z - rhs.z);\n\t}\n\n\tVector3D operator*(double rhs) const {\n\t\treturn Vector3D(rhs*x, rhs*y, rhs*z);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream&, const Vector3D&);\n\nprivate:\n\tdouble x, y, z;\n};\n\nstd::ostream & operator<<(std::ostream & os, const Vector3D &f) {\n\tstd::stringstream ss;\n\tss << \"(\" << f.x << \", \" << f.y << \", \" << f.z << \")\";\n\treturn os << ss.str();\n}\n\nVector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) {\n\tVector3D diff = rayPoint - planePoint;\n\tdouble prod1 = diff.dot(planeNormal);\n\tdouble prod2 = rayVector.dot(planeNormal);\n\tdouble prod3 = prod1 / prod2;\n\treturn rayPoint - rayVector * prod3;\n}\n\nint main() {\n\tVector3D rv = Vector3D(0.0, -1.0, -1.0);\n\tVector3D rp = Vector3D(0.0, 0.0, 10.0);\n\tVector3D pn = Vector3D(0.0, 0.0, 1.0);\n\tVector3D pp = Vector3D(0.0, 0.0, 5.0);\n\tVector3D ip = intersectPoint(rv, rp, pn, pp);\n\n\tstd::cout << \"The ray intersects the plane at \" << ip << std::endl;\n\n\treturn 0;\n}"} {"title": "Find the intersection of two lines", "language": "C++", "task": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]\n\n;Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though (4,0) and (6,10) . \nThe 2nd line passes though (0,3) and (10,7) .\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\n/** Calculate determinant of matrix:\n\t[a b]\n\t[c d]\n*/\ninline double Det(double a, double b, double c, double d)\n{\n\treturn a*d - b*c;\n}\n\n/// Calculate intersection of two lines.\n///\\return true if found, false if not found or error\nbool LineLineIntersect(double x1, double y1, // Line 1 start\n\tdouble x2, double y2, // Line 1 end\n\tdouble x3, double y3, // Line 2 start\n\tdouble x4, double y4, // Line 2 end\n\tdouble &ixOut, double &iyOut) // Output \n{\n\tdouble detL1 = Det(x1, y1, x2, y2);\n\tdouble detL2 = Det(x3, y3, x4, y4);\n\tdouble x1mx2 = x1 - x2;\n\tdouble x3mx4 = x3 - x4;\n\tdouble y1my2 = y1 - y2;\n\tdouble y3my4 = y3 - y4;\n\n\tdouble denom = Det(x1mx2, y1my2, x3mx4, y3my4);\n\tif(denom == 0.0) // Lines don't seem to cross\n\t{\n\t\tixOut = NAN;\n\t\tiyOut = NAN;\n\t\treturn false;\n\t}\n\n\tdouble xnom = Det(detL1, x1mx2, detL2, x3mx4);\n\tdouble ynom = Det(detL1, y1my2, detL2, y3my4);\n\tixOut = xnom / denom;\t\n\tiyOut = ynom / denom;\n\tif(!isfinite(ixOut) || !isfinite(iyOut)) // Probably a numerical issue\n\t\treturn false;\n\n\treturn true; //All OK\n}\n\nint main()\n{\n\t// **Simple crossing diagonal lines**\n\n\t// Line 1\n\tdouble x1=4.0, y1=0.0;\n\tdouble x2=6.0, y2=10.0;\n\t\n\t// Line 2\n\tdouble x3=0.0, y3=3.0;\n\tdouble x4=10.0, y4=7.0;\n\n\tdouble ix = -1.0, iy = -1.0;\n\tbool result = LineLineIntersect(x1, y1, x2, y2, x3, y3, x4, y4, ix, iy);\n\tcout << \"result \" << result << \",\" << ix << \",\" << iy << endl;\n\n\tdouble eps = 1e-6;\n\tassert(result == true);\n\tassert(fabs(ix - 5.0) < eps);\n\tassert(fabs(iy - 5.0) < eps);\n return 0;\n}"} {"title": "Find the last Sunday of each month", "language": "C++", "task": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n\n;Related tasks\n* [[Day of the week]]\n* [[Five weekends]]\n* [[Last Friday of each month]]\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nclass lastSunday\n{\npublic:\n lastSunday()\n {\n\tm[0] = \"JANUARY: \"; m[1] = \"FEBRUARY: \"; m[2] = \"MARCH: \"; m[3] = \"APRIL: \"; \n\tm[4] = \"MAY: \"; m[5] = \"JUNE: \"; m[6] = \"JULY: \"; m[7] = \"AUGUST: \"; \n\tm[8] = \"SEPTEMBER: \"; m[9] = \"OCTOBER: \"; m[10] = \"NOVEMBER: \"; m[11] = \"DECEMBER: \"; \n }\n\n void findLastSunday( int y )\n {\n\tyear = y;\n\tisleapyear();\n\n\tint days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },\n\t\td;\n\tfor( int i = 0; i < 12; i++ )\n\t{\n\t d = days[i];\n\t while( true )\n\t {\n\t\tif( !getWeekDay( i, d ) ) break;\n\t\td--;\n\t }\n\t lastDay[i] = d;\n\t}\n\n\tdisplay();\n }\n\nprivate:\n void isleapyear()\n {\n\tisleap = false;\n\tif( !( year % 4 ) )\n\t{\n\t if( year % 100 ) isleap = true;\n\t else if( !( year % 400 ) ) isleap = true;\n\t}\n }\n\n void display()\n {\n\tsystem( \"cls\" );\n\tcout << \" YEAR \" << year << endl << \"=============\" << endl;\n\tfor( int x = 0; x < 12; x++ )\n\t cout << m[x] << lastDay[x] << endl;\n\n\tcout << endl << endl;\n }\n\n int getWeekDay( int m, int d )\n {\n\tint y = year;\n\n\tint f = y + d + 3 * m - 1;\n\tm++;\n\tif( m < 3 ) y--;\n\telse f -= int( .4 * m + 2.3 );\n\n\tf += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 );\n\tf %= 7;\n\n\treturn f;\n }\n\n int lastDay[12], year;\n string m[12];\n bool isleap;\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n int y;\n lastSunday ls;\n\n while( true )\n {\n\tsystem( \"cls\" );\n\tcout << \"Enter the year( yyyy ) --- ( 0 to quit ): \"; \n\tcin >> y;\n\tif( !y ) return 0;\n\n\tls.findLastSunday( y );\n\n\tsystem( \"pause\" );\n }\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Find the missing permutation", "language": "C++", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nstatic const std::string GivenPermutations[] = {\n \"ABCD\",\"CABD\",\"ACDB\",\"DACB\",\n \"BCDA\",\"ACBD\",\"ADCB\",\"CDAB\",\n \"DABC\",\"BCAD\",\"CADB\",\"CDBA\",\n \"CBAD\",\"ABDC\",\"ADBC\",\"BDCA\",\n \"DCBA\",\"BACD\",\"BADC\",\"BDAC\",\n \"CBDA\",\"DBCA\",\"DCAB\"\n};\nstatic const size_t NumGivenPermutations = sizeof(GivenPermutations) / sizeof(*GivenPermutations);\n\nint main()\n{\n std::vector permutations;\n std::string initial = \"ABCD\";\n permutations.push_back(initial);\n\n while(true)\n {\n std::string p = permutations.back();\n std::next_permutation(p.begin(), p.end());\n if(p == permutations.front())\n break;\n permutations.push_back(p);\n }\n\n std::vector missing;\n std::set given_permutations(GivenPermutations, GivenPermutations + NumGivenPermutations);\n std::set_difference(permutations.begin(), permutations.end(), given_permutations.begin(),\n given_permutations.end(), std::back_inserter(missing));\n std::copy(missing.begin(), missing.end(), std::ostream_iterator(std::cout, \"\\n\"));\n return 0;\n}"} {"title": "First-class functions/Use numbers analogously", "language": "C++", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": "#include \n#include \n\nint main()\n{\n double x = 2.0;\n double xi = 0.5;\n double y = 4.0;\n double yi = 0.25;\n double z = x + y;\n double zi = 1.0 / ( x + y );\n\n const std::array values{x, y, z};\n const std::array inverses{xi, yi, zi};\n\n auto multiplier = [](double a, double b)\n {\n return [=](double m){return a * b * m;};\n };\n\n for(size_t i = 0; i < values.size(); ++i)\n {\n auto new_function = multiplier(values[i], inverses[i]);\n double value = new_function(i + 1.0);\n std::cout << value << \"\\n\"; \n }\n}\n"} {"title": "First perfect square in base n with n unique digits", "language": "C++ from C#", "task": "Find the first perfect square in a given base '''N''' that has at least '''N''' digits and\nexactly '''N''' ''significant unique'' digits when expressed in base '''N'''.\n\nE.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').\n\nYou may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.\n\n;Task\n\n* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.\n\n* (optional) Do the same for bases '''13''' through '''16'''.\n\n* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)\n\n\n;See also:\n\n;* OEIS A260182: smallest square that is pandigital in base n.\n\n;Related task\n\n;* [[Casting out nines]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst int maxBase = 16; // maximum base tabulated\nint base, bmo, tc; // globals: base, base minus one, test count\nconst string chars = \"0123456789ABCDEF\"; // characters to use for the different bases\nunsigned long long full; // for allIn() testing\n\n// converts base 10 to string representation of the current base\nstring toStr(const unsigned long long ull) {\n\tunsigned long long u = ull; string res = \"\"; while (u > 0) {\n\t\tlldiv_t result1 = lldiv(u, base); res = chars[(int)result1.rem] + res;\n\t\tu = (unsigned long long)result1.quot;\n\t} return res;\n}\n\n// converts string to base 10\nunsigned long long to10(string s) {\n\tunsigned long long res = 0; for (char i : s) res = res * base + chars.find(i); return res;\n}\n\n// determines whether all characters are present\nbool allIn(const unsigned long long ull) {\n\tunsigned long long u, found; u = ull; found = 0; while (u > 0) {\n\t\tlldiv_t result1 = lldiv(u, base); found |= (unsigned long long)1 << result1.rem;\n\t\tu = result1.quot;\n\t} return found == full;\n}\n\n// returns the minimum value string, optionally inserting extra digit\nstring fixup(int n) {\n\tstring res = chars.substr(0, base); if (n > 0) res = res.insert(n, chars.substr(n, 1));\n\treturn \"10\" + res.substr(2);\n}\n\n// perform the calculations for one base\nvoid doOne() {\n\tbmo = base - 1; tc = 0; unsigned long long sq, rt, dn, d;\n\tint id = 0, dr = (base & 1) == 1 ? base >> 1 : 0, inc = 1, sdr[maxBase] = { 0 };\n\tfull = ((unsigned long long)1 << base) - 1;\n\tint rc = 0; for (int i = 0; i < bmo; i++) {\n\t\tsdr[i] = (i * i) % bmo; if (sdr[i] == dr) rc++; if (sdr[i] == 0) sdr[i] += bmo;\n\t}\n\tif (dr > 0) {\n\t\tid = base; for (int i = 1; i <= dr; i++)\n\t\t\tif (sdr[i] >= dr) if (id > sdr[i]) id = sdr[i]; id -= dr;\n\t}\n\tsq = to10(fixup(id)); rt = (unsigned long long)sqrt(sq) + 1; sq = rt * rt;\n\tdn = (rt << 1) + 1; d = 1; if (base > 3 && rc > 0) {\n\t\twhile (sq % bmo != dr) { rt += 1; sq += dn; dn += 2; } // alligns sq to dr\n\t\tinc = bmo / rc; if (inc > 1) { dn += rt * (inc - 2) - 1; d = inc * inc; }\n\t\tdn += dn + d;\n\t} d <<= 1;\n\tdo { if (allIn(sq)) break; sq += dn; dn += d; tc++; } while (true);\n\trt += tc * inc;\n\tcout << setw(4) << base << setw(3) << inc << \" \" << setw(2)\n\t\t<< (id > 0 ? chars.substr(id, 1) : \" \") << setw(10) << toStr(rt) << \" \"\n\t\t<< setw(20) << left << toStr(sq) << right << setw(12) << tc << endl;\n}\n\nint main() {\n\tcout << \"base inc id root sqr test count\" << endl;\n\tauto st = chrono::system_clock::now();\n\tfor (base = 2; base <= maxBase; base++) doOne();\n\tchrono::duration et = chrono::system_clock::now() - st;\n\tcout << \"\\nComputation time was \" << et.count() * 1000 << \" milliseconds\" << endl;\n\treturn 0;\n}"} {"title": "First power of 2 that has leading decimal digits of 12", "language": "C++ from Pascal", "task": "(This task is taken from a ''Project Euler'' problem.)\n\n(All numbers herein are expressed in base ten.)\n\n\n'''27 = 128''' and '''7''' is\nthe first power of '''2''' whose leading decimal digits are '''12'''.\n\nThe next power of '''2''' whose leading decimal digits\nare '''12''' is '''80''',\n'''280 = 1208925819614629174706176'''.\n\n\nDefine ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest\nvalue of ''' ''j'' ''' such that the base ten representation\nof '''2''j''''' begins with the digits of ''' ''L'' '''.\n\n So ''p''(12, 1) = 7 and\n ''p''(12, 2) = 80\n\n\nYou are also given that:\n ''p''(123, 45) = 12710\n\n\n;Task:\n::* find: \n:::::* ''' ''p''(12, 1) ''' \n:::::* ''' ''p''(12, 2) ''' \n:::::* ''' ''p''(123, 45) ''' \n:::::* ''' ''p''(123, 12345) ''' \n:::::* ''' ''p''(123, 678910) ''' \n::* display the results here, on this page.\n\n", "solution": "// a mini chrestomathy solution\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace chrono;\n\n// translated from java example\nunsigned int js(int l, int n) {\n unsigned int res = 0, f = 1; \n double lf = log(2) / log(10), ip;\n for (int i = l; i > 10; i /= 10) f *= 10;\n while (n > 0)\n if ((int)(f * pow(10, modf(++res * lf, &ip))) == l) n--;\n return res;\n}\n\n// translated from go integer example (a.k.a. go translation of pascal alternative example)\nunsigned int gi(int ld, int n) {\n string Ls = to_string(ld);\n unsigned int res = 0, count = 0; unsigned long long f = 1;\n for (int i = 1; i <= 18 - Ls.length(); i++) f *= 10;\n const unsigned long long ten18 = 1e18; unsigned long long probe = 1;\n do {\n probe <<= 1; res++; if (probe >= ten18) {\n do {\n if (probe >= ten18) probe /= 10;\n if (probe / f == ld) if (++count >= n) { count--; break; }\n probe <<= 1; res++;\n } while (1);\n }\n string ps = to_string(probe);\n if (ps.substr(0, min(Ls.length(), ps.length())) == Ls) if (++count >= n) break;\n } while (1);\n return res;\n}\n\n// translated from pascal alternative example\nunsigned int pa(int ld, int n) {\n const double L_float64 = pow(2, 64);\n const unsigned long long Log10_2_64 = (unsigned long long)(L_float64 * log(2) / log(10));\n double Log10Num; unsigned long long LmtUpper, LmtLower, Frac64;\n int res = 0, dgts = 1, cnt;\n for (int i = ld; i >= 10; i /= 10) dgts *= 10;\n Log10Num = log((ld + 1.0) / dgts) / log(10);\n // '316' was a limit\n if (Log10Num >= 0.5) {\n LmtUpper = (ld + 1.0) / dgts < 10.0 ? (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2) : 0;\n Log10Num = log((double)ld / dgts) / log(10);\n LmtLower = (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2);\n } else {\n LmtUpper = (unsigned long long)(Log10Num * L_float64); \n LmtLower = (unsigned long long)(log((double)ld / dgts) / log(10) * L_float64);\n }\n cnt = 0; Frac64 = 0; if (LmtUpper != 0) {\n do {\n res++; Frac64 += Log10_2_64;\n if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper))\n if (++cnt >= n) break;\n } while (1);\n } else { // '999..'\n do {\n res++; Frac64 += Log10_2_64;\n if (Frac64 >= LmtLower) if (++cnt >= n) break;\n } while (1);\n };\n return res;\n}\n\nint params[] = { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 };\n\nvoid doOne(string name, unsigned int (*func)(int a, int b)) {\n printf(\"%s version:\\n\", name.c_str());\n auto start = steady_clock::now();\n for (int i = 0; i < size(params); i += 2)\n printf(\"p(%3d, %6d) = %'11u\\n\", params[i], params[i + 1], func(params[i], params[i + 1]));\n printf(\"Took %f seconds\\n\\n\", duration(steady_clock::now() - start).count());\n}\n\nint main() {\n setlocale(LC_ALL, \"\"); \n doOne(\"java simple\", js);\n doOne(\"go integer\", gi);\n doOne(\"pascal alternative\", pa);\n}"} {"title": "Fivenum", "language": "C++ from D", "task": "Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, there are variations among statistical packages for the whiskers.\n\n", "solution": "#include \n#include \n#include \n#include \n\n/////////////////////////////////////////////////////////////////////////////\n// The following is taken from https://cpplove.blogspot.com/2012/07/printing-tuples.html\n\n// Define a type which holds an unsigned integer value \ntemplate struct int_ {};\n\ntemplate \nstd::ostream& print_tuple(std::ostream& out, const Tuple& t, int_) {\n out << std::get< std::tuple_size::value - Pos >(t) << \", \";\n return print_tuple(out, t, int_());\n}\n\ntemplate \nstd::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) {\n return out << std::get::value - 1>(t);\n}\n\ntemplate \nstd::ostream& operator<<(std::ostream& out, const std::tuple& t) {\n out << '(';\n print_tuple(out, t, int_());\n return out << ')';\n}\n\n/////////////////////////////////////////////////////////////////////////////\n\ntemplate \ndouble median(RI beg, RI end) {\n if (beg == end) throw std::runtime_error(\"Range cannot be empty\");\n auto len = end - beg;\n auto m = len / 2;\n if (len % 2 == 1) {\n return *(beg + m);\n }\n\n return (beg[m - 1] + beg[m]) / 2.0;\n}\n\ntemplate \nauto fivenum(C& c) {\n std::sort(c.begin(), c.end());\n\n auto cbeg = c.cbegin();\n auto cend = c.cend();\n\n auto len = cend - cbeg;\n auto m = len / 2;\n auto lower = (len % 2 == 1) ? m : m - 1;\n double r2 = median(cbeg, cbeg + lower + 1);\n double r3 = median(cbeg, cend);\n double r4 = median(cbeg + lower + 1, cend);\n\n return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1));\n}\n\nint main() {\n using namespace std;\n vector> cs = {\n { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 },\n { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 },\n {\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,\n -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n }\n };\n\n for (auto & c : cs) {\n cout << fivenum(c) << endl;\n }\n\n return 0;\n}"} {"title": "Fixed length records", "language": "C++", "task": "Fixed length read/write\n\nBefore terminals, computers commonly used punch card readers or paper tape input.\n\nA common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.\n\nThese input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.\n\nThese devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).\n\n;Task:\nWrite a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. \n\nSamples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.\n\n'''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.\n\nThese fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''.\n\n;Sample data:\nTo create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size.\n\nLine 1...1.........2.........3.........4.........5.........6.........7.........8\nLine 2\nLine 3\nLine 4\n\nLine 6\nLine 7\n Indented line 8............................................................\nLine 9 RT MARGIN\nprompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input.\n\nprompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines.\n\n\n;Bonus round:\nForth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).\n\nWrite a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.\n\nAlso demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.\n\nThe COBOL example uses forth.txt and forth.blk filenames.\n\n", "solution": "#include \n#include \n#include \n#include \n\nvoid reverse(std::istream& in, std::ostream& out) {\n constexpr size_t record_length = 80;\n char record[record_length];\n while (in.read(record, record_length)) {\n std::reverse(std::begin(record), std::end(record));\n out.write(record, record_length);\n }\n out.flush();\n}\n\nint main(int argc, char** argv) {\n std::ifstream in(\"infile.dat\", std::ios_base::binary);\n if (!in) {\n std::cerr << \"Cannot open input file\\n\";\n return EXIT_FAILURE;\n }\n std::ofstream out(\"outfile.dat\", std::ios_base::binary);\n if (!out) {\n std::cerr << \"Cannot open output file\\n\";\n return EXIT_FAILURE;\n }\n try {\n in.exceptions(std::ios_base::badbit);\n out.exceptions(std::ios_base::badbit);\n reverse(in, out);\n } catch (const std::exception& ex) {\n std::cerr << \"I/O error: \" << ex.what() << '\\n';\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}"} {"title": "Flatten a list", "language": "C++", "task": "Write a function to flatten the nesting in an arbitrary list of values. \n\nYour program should work on the equivalent of this list:\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\nWhere the correct result would be the list:\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n;Related task:\n* [[Tree traversal]]\n\n", "solution": "#include \n#include \n\n// *******************\n// * the list parser *\n// *******************\n\nvoid skipwhite(char const** s)\n{\n while (**s && std::isspace((unsigned char)**s))\n {\n ++*s;\n }\n}\n\nanylist create_anylist_i(char const** s)\n{\n anylist result;\n skipwhite(s);\n if (**s != '[')\n throw \"Not a list\";\n ++*s;\n while (true)\n {\n skipwhite(s);\n if (!**s)\n throw \"Error\";\n else if (**s == ']')\n {\n ++*s;\n return result;\n }\n else if (**s == '[')\n result.push_back(create_anylist_i(s));\n else if (std::isdigit((unsigned char)**s))\n {\n int i = 0;\n while (std::isdigit((unsigned char)**s))\n {\n i = 10*i + (**s - '0');\n ++*s;\n }\n result.push_back(i);\n }\n else\n throw \"Error\";\n\n skipwhite(s);\n if (**s != ',' && **s != ']')\n throw \"Error\";\n if (**s == ',')\n ++*s;\n }\n}\n\nanylist create_anylist(char const* i)\n{\n return create_anylist_i(&i);\n}\n\n// *************************\n// * printing nested lists *\n// *************************\n\nvoid print_list(anylist const& list);\n\nvoid print_item(boost::any const& a)\n{\n if (a.type() == typeid(int))\n std::cout << boost::any_cast(a);\n else if (a.type() == typeid(anylist))\n print_list(boost::any_cast(a));\n else\n std::cout << \"???\";\n}\n\nvoid print_list(anylist const& list)\n{\n std::cout << '[';\n anylist::const_iterator iter = list.begin();\n while (iter != list.end())\n {\n print_item(*iter);\n ++iter;\n if (iter != list.end())\n std::cout << \", \";\n }\n std::cout << ']';\n}\n\n// ***************************\n// * The actual test program *\n// ***************************\n\nint main()\n{\n anylist list =\n create_anylist(\"[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]\");\n print_list(list);\n std::cout << \"\\n\";\n flatten(list);\n print_list(list);\n std::cout << \"\\n\";\n}"} {"title": "Flipping bits game", "language": "C++", "task": "The game:\nGiven an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.\n\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered \ncolumns at once (as one move).\n\nIn an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.\n\n\n;Task:\nCreate a program to score for the Flipping bits game.\n# The game should create an original random target configuration and a starting configuration.\n# Ensure that the starting position is ''never'' the target position.\n# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).\n# The number of moves taken so far should be shown.\n\n\nShow an example of a short game here, on this page, for a '''3x3''' array of bits.\n\n", "solution": "#include \n#include \n#include \n\ntypedef unsigned char byte;\nusing namespace std;\n\nclass flip\n{\npublic:\n flip() { field = 0; target = 0; }\n void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }\n\nprivate:\n void gameLoop()\n {\n\tint moves = 0;\n\twhile( !solved() )\n\t{\n\t display(); string r; cout << \"Enter rows letters and/or column numbers: \"; cin >> r;\n\t for( string::iterator i = r.begin(); i != r.end(); i++ )\n\t {\n\t\tbyte ii = ( *i );\n\t\tif( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }\n\t\telse if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }\n\t }\n\t}\n\tcout << endl << endl << \"** Well done! **\" << endl << \"Used \" << moves << \" moves.\" << endl << endl;\n }\n\n void display()\n { system( \"cls\" ); output( \"TARGET:\", target ); output( \"YOU:\", field ); }\n\n void output( string t, byte* f )\n {\n\tcout << t << endl;\n\tcout << \" \"; for( int x = 0; x < wid; x++ ) cout << \" \" << static_cast( x + '1' ); cout << endl;\n\tfor( int y = 0; y < hei; y++ )\n\t{\n\t cout << static_cast( y + 'a' ) << \" \";\n\t for( int x = 0; x < wid; x++ )\n\t\tcout << static_cast( f[x + y * wid] + 48 ) << \" \";\n\t cout << endl;\n\t}\n\tcout << endl << endl;\n }\n\n bool solved()\n {\n\tfor( int y = 0; y < hei; y++ )\n\t for( int x = 0; x < wid; x++ )\n\t\tif( target[x + y * wid] != field[x + y * wid] ) return false;\n\treturn true;\n }\n\n void createTarget()\n {\n\tfor( int y = 0; y < hei; y++ )\n\t for( int x = 0; x < wid; x++ )\n\t\tif( frnd() < .5f ) target[x + y * wid] = 1;\n\t else target[x + y * wid] = 0;\n\tmemcpy( field, target, wid * hei );\n }\n\n void flipCol( int c )\n { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }\n\t\n void flipRow( int r )\n { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }\n\n void calcStartPos()\n {\n\tint flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;\n\tfor( int x = 0; x < flips; x++ )\n\t{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }\n }\n\n void createField()\n {\n if( field ){ delete [] field; delete [] target; }\n int t = wid * hei; field = new byte[t]; target = new byte[t];\n\tmemset( field, 0, t ); memset( target, 0, t ); createTarget();\n\twhile( true ) { calcStartPos(); if( !solved() ) break; }\n }\n\n float frnd() { return static_cast( rand() ) / static_cast( RAND_MAX ); }\n\n byte* field, *target; int wid, hei;\n};\n\nint main( int argc, char* argv[] )\n{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( \"pause\" ); }\n"} {"title": "Floyd's triangle", "language": "C++", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nclass floyds_tri\n{\npublic:\n floyds_tri() { lastLineLen = 0; }\n ~floyds_tri() { killArray(); }\n\n void create( int rows )\n {\n\t_rows = rows;\n\tcalculateLastLineLen();\n\tdisplay();\n }\n\nprivate:\n void killArray()\n {\n\tif( lastLineLen ) \n\t delete [] lastLineLen;\n }\n\n void calculateLastLineLen()\n {\n\tkillArray();\n\tlastLineLen = new BYTE[_rows];\n\n\tint s = 1 + ( _rows * ( _rows - 1 ) ) / 2;\n\n\tfor( int x = s, ix = 0; x < s + _rows; x++, ix++ )\n\t{\n\t ostringstream cvr;\n\t cvr << x;\n\t lastLineLen[ix] = static_cast( cvr.str().size() );\n\t}\n }\n\n void display()\n {\n\tcout << endl << \"Floyd\\'s Triangle - \" << _rows << \" rows\" << endl << \"===============================================\" << endl;\n\tint number = 1;\n\tfor( int r = 0; r < _rows; r++ )\n\t{\n\t for( int c = 0; c <= r; c++ )\n\t {\n\t\tostringstream cvr;\n\t\tcvr << number++;\n\t\tstring str = cvr.str();\n\t\twhile( str.length() < lastLineLen[c] )\n\t\t str = \" \" + str;\n\t\tcout << str << \" \";\n\t }\n\t cout << endl;\n\t}\n }\n\n int _rows;\n BYTE* lastLineLen;\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n floyds_tri t;\n int s;\n while( true )\n {\n\tcout << \"Enter the size of the triangle ( 0 to QUIT ): \"; cin >> s;\n\tif( !s ) return 0;\n\tif( s > 0 ) t.create( s );\n\n\tcout << endl << endl;\n\tsystem( \"pause\" );\n }\n\n return 0;\n}\n//--------------------------------------------------------------------------------------------------"} {"title": "Four is magic", "language": "C++", "task": "Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* [[Four is the number of_letters in the ...]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Summarize and say sequence]]\n:* [[Spelling of ordinal numbers]]\n:* [[De Bruijn sequences]]\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef std::uint64_t integer;\n\nconst char* small[] = {\n \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"\n};\n\nconst char* tens[] = {\n \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"\n};\n\nstruct named_number {\n const char* name_;\n integer number_;\n};\n\nconst named_number named_numbers[] = {\n { \"hundred\", 100 },\n { \"thousand\", 1000 },\n { \"million\", 1000000 },\n { \"billion\", 1000000000 },\n { \"trillion\", 1000000000000 },\n { \"quadrillion\", 1000000000000000ULL },\n { \"quintillion\", 1000000000000000000ULL }\n};\n\nconst named_number& get_named_number(integer n) {\n constexpr size_t names_len = std::size(named_numbers);\n for (size_t i = 0; i + 1 < names_len; ++i) {\n if (n < named_numbers[i + 1].number_)\n return named_numbers[i];\n }\n return named_numbers[names_len - 1];\n}\n\nstd::string cardinal(integer n) {\n std::string result;\n if (n < 20)\n result = small[n];\n else if (n < 100) {\n result = tens[n/10 - 2];\n if (n % 10 != 0) {\n result += \"-\";\n result += small[n % 10];\n }\n } else {\n const named_number& num = get_named_number(n);\n integer p = num.number_;\n result = cardinal(n/p);\n result += \" \";\n result += num.name_;\n if (n % p != 0) {\n result += \" \";\n result += cardinal(n % p);\n }\n }\n return result;\n}\n\ninline char uppercase(char ch) {\n return static_cast(std::toupper(static_cast(ch)));\n}\n\nstd::string magic(integer n) {\n std::string result;\n for (unsigned int i = 0; ; ++i) {\n std::string text(cardinal(n));\n if (i == 0)\n text[0] = uppercase(text[0]);\n result += text;\n if (n == 4) {\n result += \" is magic.\";\n break;\n }\n integer len = text.length();\n result += \" is \";\n result += cardinal(len);\n result += \", \";\n n = len;\n }\n return result;\n}\n\nvoid test_magic(integer n) {\n std::cout << magic(n) << '\\n';\n}\n\nint main() {\n test_magic(5);\n test_magic(13);\n test_magic(78);\n test_magic(797);\n test_magic(2739);\n test_magic(4000);\n test_magic(7893);\n test_magic(93497412);\n test_magic(2673497412U);\n test_magic(10344658531277200972ULL);\n return 0;\n}"} {"title": "Four is the number of letters in the ...", "language": "C++", "task": "The '''Four is ...''' sequence is based on the counting of the number of\nletters in the words of the (never-ending) sentence:\n Four is the number of letters in the first word of this sentence, two in the second,\n three in the third, six in the fourth, two in the fifth, seven in the sixth, *** \n\n\n;Definitions and directives:\n:* English is to be used in spelling numbers.\n:* '''Letters''' are defined as the upper- and lowercase letters in the Latin alphabet ('''A-->Z''' and '''a-->z''').\n:* Commas are not counted, nor are hyphens (dashes or minus signs).\n:* '''twenty-three''' has eleven letters.\n:* '''twenty-three''' is considered one word (which is hyphenated).\n:* no ''' ''and'' ''' words are to be used when spelling a (English) word for a number.\n:* The American version of numbers will be used here in this task (as opposed to the British version).\n '''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\n;Task:\n:* Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first '''N''' words in the never-ending sentence. For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:\n '''4 2 3 6 2 7'''\n:* Only construct as much as is needed for the never-ending sentence.\n:* Write a driver (invoking routine) to show the number of letters in the Nth word, ''as well as'' showing the Nth word itself.\n:* After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.\n:* Show all output here.\n\n\n;Test cases:\n Display the first 201 numbers in the sequence (and the total number of characters in the sentence).\n Display the number of letters (and the word itself) of the 1,000th word.\n Display the number of letters (and the word itself) of the 10,000th word.\n Display the number of letters (and the word itself) of the 100,000th word.\n Display the number of letters (and the word itself) of the 1,000,000th word.\n Display the number of letters (and the word itself) of the 10,000,000th word (optional).\n\n\n;Related tasks:\n:* [[Four is magic]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Self-referential sequence]]\n:* [[Spelling of ordinal numbers]]\n\n\n;Also see:\n:* See the OEIS sequence A72425 \"Four is the number of letters...\".\n:* See the OEIS sequence A72424 \"Five's the number of letters...\"\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nstruct number_names {\n const char* cardinal;\n const char* ordinal;\n};\n\nconst number_names small[] = {\n { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n const char* cardinal;\n const char* ordinal;\n uint64_t number;\n};\n\nconst named_number named_numbers[] = {\n { \"hundred\", \"hundredth\", 100 },\n { \"thousand\", \"thousandth\", 1000 },\n { \"million\", \"millionth\", 1000000 },\n { \"billion\", \"biliionth\", 1000000000 },\n { \"trillion\", \"trillionth\", 1000000000000 },\n { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(uint64_t n) {\n constexpr size_t names_len = std::size(named_numbers);\n for (size_t i = 0; i + 1 < names_len; ++i) {\n if (n < named_numbers[i + 1].number)\n return named_numbers[i];\n }\n return named_numbers[names_len - 1];\n}\n\nsize_t append_number_name(std::vector& result, uint64_t n, bool ordinal) {\n size_t count = 0;\n if (n < 20) {\n result.push_back(get_name(small[n], ordinal));\n count = 1;\n }\n else if (n < 100) {\n if (n % 10 == 0) {\n result.push_back(get_name(tens[n/10 - 2], ordinal));\n } else {\n std::string name(get_name(tens[n/10 - 2], false));\n name += \"-\";\n name += get_name(small[n % 10], ordinal);\n result.push_back(name);\n }\n count = 1;\n } else {\n const named_number& num = get_named_number(n);\n uint64_t p = num.number;\n count += append_number_name(result, n/p, false);\n if (n % p == 0) {\n result.push_back(get_name(num, ordinal));\n ++count;\n } else {\n result.push_back(get_name(num, false));\n ++count;\n count += append_number_name(result, n % p, ordinal);\n }\n }\n return count;\n}\n\nsize_t count_letters(const std::string& str) {\n size_t letters = 0;\n for (size_t i = 0, n = str.size(); i < n; ++i) {\n if (isalpha(static_cast(str[i])))\n ++letters;\n }\n return letters;\n}\n\nstd::vector sentence(size_t count) {\n static const char* words[] = {\n \"Four\", \"is\", \"the\", \"number\", \"of\", \"letters\", \"in\", \"the\",\n \"first\", \"word\", \"of\", \"this\", \"sentence,\"\n };\n std::vector result;\n result.reserve(count + 10);\n size_t n = std::size(words);\n for (size_t i = 0; i < n && i < count; ++i) {\n result.push_back(words[i]);\n }\n for (size_t i = 1; count > n; ++i) {\n n += append_number_name(result, count_letters(result[i]), false);\n result.push_back(\"in\");\n result.push_back(\"the\");\n n += 2;\n n += append_number_name(result, i + 1, true);\n result.back() += ',';\n }\n return result;\n}\n\nsize_t sentence_length(const std::vector& words) {\n size_t n = words.size();\n if (n == 0)\n return 0;\n size_t length = n - 1;\n for (size_t i = 0; i < n; ++i)\n length += words[i].size();\n return length;\n}\n\nint main() {\n std::cout.imbue(std::locale(\"\"));\n size_t n = 201;\n auto result = sentence(n);\n std::cout << \"Number of letters in first \" << n << \" words in the sequence:\\n\";\n for (size_t i = 0; i < n; ++i) {\n if (i != 0)\n std::cout << (i % 25 == 0 ? '\\n' : ' ');\n std::cout << std::setw(2) << count_letters(result[i]);\n }\n std::cout << '\\n';\n std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n for (n = 1000; n <= 10000000; n *= 10) {\n result = sentence(n);\n const std::string& word = result[n - 1];\n std::cout << \"The \" << n << \"th word is '\" << word << \"' and has \"\n << count_letters(word) << \" letters. \";\n std::cout << \"Sentence length: \" << sentence_length(result) << '\\n';\n }\n return 0;\n}"} {"title": "Function prototype", "language": "C++", "task": "Some languages provide the facility to declare functions and subroutines through the use of function prototyping. \n\n\n;Task:\nDemonstrate the methods available for declaring prototypes within the language. The provided solutions should include:\n\n* An explanation of any placement restrictions for prototype declarations\n* A prototype declaration for a function that does not require arguments\n* A prototype declaration for a function that requires two arguments\n* A prototype declaration for a function that utilizes varargs\n* A prototype declaration for a function that utilizes optional arguments\n* A prototype declaration for a function that utilizes named parameters\n* Example of prototype declarations for subroutines or procedures (if these differ from functions)\n* An explanation and example of any special forms of prototyping not covered by the above\n\n\nLanguages that do not provide function prototyping facilities should be omitted from this task.\n\n", "solution": "int noargs(); // Declare a function with no arguments that returns an integer\nint twoargs(int a,int b); // Declare a function with two arguments that returns an integer\nint twoargs(int ,int); // Parameter names are optional in a prototype definition\nint anyargs(...); // An ellipsis is used to declare a function that accepts varargs\nint atleastoneargs(int, ...); // One mandatory integer argument followed by varargs\ntemplate T declval(T); //A function template\ntemplate tuple make_tuple(T...); //Function template using parameter pack (since c++11)\n"} {"title": "Fusc sequence", "language": "C++ from C#", "task": "Definitions:\nThe '''fusc''' integer sequence is defined as:\n::* fusc(0) = 0\n::* fusc(1) = 1\n::* for '''n'''>1, the '''n'''th term is defined as:\n::::* if '''n''' is even; fusc(n) = fusc(n/2)\n::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).\n\n\n\n;An observation:\n:::::* fusc(A) = fusc(B)\n\nwhere '''A''' is some non-negative integer expressed in binary, and\nwhere '''B''' is the binary value of '''A''' reversed.\n\n\n\nFusc numbers are also known as:\n::* fusc function (named by Dijkstra, 1982)\n::* Stern's Diatomic series (although it starts with unity, not zero)\n::* Stern-Brocot sequence (although it starts with unity, not zero)\n\n\n\n;Task:\n::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.\n::* show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* show all numbers with commas (if appropriate).\n::* show all output here.\n\n\n;Related task:\n::* RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* the MathWorld entry: Stern's Diatomic Series.\n::* the OEIS entry: A2487.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nconst int n = 61;\nstd::vector l{ 0, 1 };\n\nint fusc(int n) {\n if (n < l.size()) return l[n];\n int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];\n l.push_back(f);\n return f;\n}\n\nint main() {\n bool lst = true;\n int w = -1;\n int c = 0;\n int t;\n std::string res;\n std::cout << \"First \" << n << \" numbers in the fusc sequence:\\n\";\n for (int i = 0; i < INT32_MAX; i++) {\n int f = fusc(i);\n if (lst) {\n if (i < 61) {\n std::cout << f << ' ';\n } else {\n lst = false;\n std::cout << \"\\nPoints in the sequence where an item has more digits than any previous items:\\n\";\n std::cout << std::setw(11) << \"Index\\\\\" << \" \" << std::left << std::setw(9) << \"/Value\\n\";\n std::cout << res << '\\n';\n res = \"\";\n }\n }\n std::stringstream ss;\n ss << f;\n t = ss.str().length();\n ss.str(\"\");\n ss.clear();\n if (t > w) {\n w = t;\n res += (res == \"\" ? \"\" : \"\\n\");\n ss << std::setw(11) << i << \" \" << std::left << std::setw(9) << f;\n res += ss.str();\n if (!lst) {\n std::cout << res << '\\n';\n res = \"\";\n }\n if (++c > 5) {\n break;\n }\n }\n }\n return 0;\n}"} {"title": "Gapful numbers", "language": "C++", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''187'''. \n\n\nAbout 7.46% of positive integers are ''gapful''. \n\n\n;Task:\n:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page\n:* Show the first '''30''' gapful numbers\n:* Show the first '''15''' gapful numbers >= '''1,000,000'''\n:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''\n\n\n;Related tasks:\n:* Harshad or Niven series.\n:* palindromic gapful numbers.\n:* largest number divisible by its digits.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n:* numbersaplenty gapful numbers\n\n", "solution": "#include \n\nbool gapful(int n) {\n int m = n;\n while (m >= 10)\n m /= 10;\n return n % ((n % 10) + 10 * (m % 10)) == 0;\n}\n\nvoid show_gapful_numbers(int n, int count) {\n std::cout << \"First \" << count << \" gapful numbers >= \" << n << \":\\n\";\n for (int i = 0; i < count; ++n) {\n if (gapful(n)) {\n if (i != 0)\n std::cout << \", \";\n std::cout << n;\n ++i;\n }\n }\n std::cout << '\\n';\n}\n\nint main() {\n show_gapful_numbers(100, 30);\n show_gapful_numbers(1000000, 15);\n show_gapful_numbers(1000000000, 10);\n return 0;\n}"} {"title": "Gauss-Jordan matrix inversion", "language": "C++", "task": "Invert matrix '''A''' using Gauss-Jordan method.\n\n'''A''' being an '''n''' x '''n''' matrix.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ntemplate class matrix {\npublic:\n matrix(size_t rows, size_t columns)\n : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n matrix(size_t rows, size_t columns, scalar_type value)\n : rows_(rows), columns_(columns), elements_(rows * columns, value) {}\n\n matrix(size_t rows, size_t columns, std::initializer_list values)\n : rows_(rows), columns_(columns), elements_(rows * columns) {\n assert(values.size() <= rows_ * columns_);\n std::copy(values.begin(), values.end(), elements_.begin());\n }\n\n size_t rows() const { return rows_; }\n size_t columns() const { return columns_; }\n\n scalar_type& operator()(size_t row, size_t column) {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n const scalar_type& operator()(size_t row, size_t column) const {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\nprivate:\n size_t rows_;\n size_t columns_;\n std::vector elements_;\n};\n\ntemplate \nmatrix product(const matrix& a,\n const matrix& b) {\n assert(a.columns() == b.rows());\n size_t arows = a.rows();\n size_t bcolumns = b.columns();\n size_t n = a.columns();\n matrix c(arows, bcolumns);\n for (size_t i = 0; i < arows; ++i) {\n for (size_t j = 0; j < n; ++j) {\n for (size_t k = 0; k < bcolumns; ++k)\n c(i, k) += a(i, j) * b(j, k);\n }\n }\n return c;\n}\n\ntemplate \nvoid swap_rows(matrix& m, size_t i, size_t j) {\n size_t columns = m.columns();\n for (size_t column = 0; column < columns; ++column)\n std::swap(m(i, column), m(j, column));\n}\n\n// Convert matrix to reduced row echelon form\ntemplate \nvoid rref(matrix& m) {\n size_t rows = m.rows();\n size_t columns = m.columns();\n for (size_t row = 0, lead = 0; row < rows && lead < columns; ++row, ++lead) {\n size_t i = row;\n while (m(i, lead) == 0) {\n if (++i == rows) {\n i = row;\n if (++lead == columns)\n return;\n }\n }\n swap_rows(m, i, row);\n if (m(row, lead) != 0) {\n scalar_type f = m(row, lead);\n for (size_t column = 0; column < columns; ++column)\n m(row, column) /= f;\n }\n for (size_t j = 0; j < rows; ++j) {\n if (j == row)\n continue;\n scalar_type f = m(j, lead);\n for (size_t column = 0; column < columns; ++column)\n m(j, column) -= f * m(row, column);\n }\n }\n}\n\ntemplate \nmatrix inverse(const matrix& m) {\n assert(m.rows() == m.columns());\n size_t rows = m.rows();\n matrix tmp(rows, 2 * rows, 0);\n for (size_t row = 0; row < rows; ++row) {\n for (size_t column = 0; column < rows; ++column)\n tmp(row, column) = m(row, column);\n tmp(row, row + rows) = 1;\n }\n rref(tmp);\n matrix inv(rows, rows);\n for (size_t row = 0; row < rows; ++row) {\n for (size_t column = 0; column < rows; ++column)\n inv(row, column) = tmp(row, column + rows);\n }\n return inv;\n}\n\ntemplate \nvoid print(std::ostream& out, const matrix& m) {\n size_t rows = m.rows(), columns = m.columns();\n out << std::fixed << std::setprecision(4);\n for (size_t row = 0; row < rows; ++row) {\n for (size_t column = 0; column < columns; ++column) {\n if (column > 0)\n out << ' ';\n out << std::setw(7) << m(row, column);\n }\n out << '\\n';\n }\n}\n\nint main() {\n matrix m(3, 3, {2, -1, 0, -1, 2, -1, 0, -1, 2});\n std::cout << \"Matrix:\\n\";\n print(std::cout, m);\n auto inv(inverse(m));\n std::cout << \"Inverse:\\n\";\n print(std::cout, inv);\n std::cout << \"Product of matrix and inverse:\\n\";\n print(std::cout, product(m, inv));\n std::cout << \"Inverse of inverse:\\n\";\n print(std::cout, inverse(inv));\n return 0;\n}"} {"title": "Gaussian elimination", "language": "C++ from Go", "task": "Solve '''Ax=b''' using Gaussian elimination then backwards substitution. \n\n'''A''' being an '''n''' by '''n''' matrix. \n\nAlso, '''x''' and '''b''' are '''n''' by '''1''' vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* the Wikipedia entry: Gaussian elimination\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate class matrix {\npublic:\n matrix(size_t rows, size_t columns)\n : rows_(rows), columns_(columns), elements_(rows * columns) {}\n\n matrix(size_t rows, size_t columns,\n const std::initializer_list>& values)\n : rows_(rows), columns_(columns), elements_(rows * columns) {\n assert(values.size() <= rows_);\n auto i = elements_.begin();\n for (const auto& row : values) {\n assert(row.size() <= columns_);\n std::copy(begin(row), end(row), i);\n i += columns_;\n }\n }\n\n size_t rows() const { return rows_; }\n size_t columns() const { return columns_; }\n\n const scalar_type& operator()(size_t row, size_t column) const {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\n scalar_type& operator()(size_t row, size_t column) {\n assert(row < rows_);\n assert(column < columns_);\n return elements_[row * columns_ + column];\n }\nprivate:\n size_t rows_;\n size_t columns_;\n std::vector elements_;\n};\n\ntemplate \nvoid swap_rows(matrix& m, size_t i, size_t j) {\n size_t columns = m.columns();\n for (size_t k = 0; k < columns; ++k)\n std::swap(m(i, k), m(j, k));\n}\n\ntemplate \nstd::vector gauss_partial(const matrix& a0,\n const std::vector& b0) {\n size_t n = a0.rows();\n assert(a0.columns() == n);\n assert(b0.size() == n);\n // make augmented matrix\n matrix a(n, n + 1);\n for (size_t i = 0; i < n; ++i) {\n for (size_t j = 0; j < n; ++j)\n a(i, j) = a0(i, j);\n a(i, n) = b0[i];\n }\n // WP algorithm from Gaussian elimination page\n // produces row echelon form\n for (size_t k = 0; k < n; ++k) {\n // Find pivot for column k\n size_t max_index = k;\n scalar_type max_value = 0;\n for (size_t i = k; i < n; ++i) {\n // compute scale factor = max abs in row\n scalar_type scale_factor = 0;\n for (size_t j = k; j < n; ++j)\n scale_factor = std::max(std::abs(a(i, j)), scale_factor);\n if (scale_factor == 0)\n continue;\n // scale the abs used to pick the pivot\n scalar_type abs = std::abs(a(i, k))/scale_factor;\n if (abs > max_value) {\n max_index = i;\n max_value = abs;\n }\n }\n if (a(max_index, k) == 0)\n throw std::runtime_error(\"matrix is singular\");\n if (k != max_index)\n swap_rows(a, k, max_index);\n for (size_t i = k + 1; i < n; ++i) {\n scalar_type f = a(i, k)/a(k, k);\n for (size_t j = k + 1; j <= n; ++j)\n a(i, j) -= a(k, j) * f;\n a(i, k) = 0;\n }\n }\n // now back substitute to get result\n std::vector x(n);\n for (size_t i = n; i-- > 0; ) {\n x[i] = a(i, n);\n for (size_t j = i + 1; j < n; ++j)\n x[i] -= a(i, j) * x[j];\n x[i] /= a(i, i);\n }\n return x;\n}\n\nint main() {\n matrix a(6, 6, {\n {1.00, 0.00, 0.00, 0.00, 0.00, 0.00},\n {1.00, 0.63, 0.39, 0.25, 0.16, 0.10},\n {1.00, 1.26, 1.58, 1.98, 2.49, 3.13},\n {1.00, 1.88, 3.55, 6.70, 12.62, 23.80},\n {1.00, 2.51, 6.32, 15.88, 39.90, 100.28},\n {1.00, 3.14, 9.87, 31.01, 97.41, 306.02}\n });\n std::vector b{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02};\n std::vector x{-0.01, 1.602790394502114, -1.6132030599055613,\n 1.2454941213714368, -0.4909897195846576, 0.065760696175232};\n std::vector y(gauss_partial(a, b));\n std::cout << std::setprecision(16);\n const double epsilon = 1e-14;\n for (size_t i = 0; i < y.size(); ++i) {\n assert(std::abs(x[i] - y[i]) <= epsilon);\n std::cout << y[i] << '\\n';\n }\n return 0;\n}"} {"title": "Generate Chess960 starting position", "language": "C++", "task": "Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:\n\n* as in the standard chess game, all eight white pawns must be placed on the second rank.\n* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:\n** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)\n** the King must be between two rooks (with any number of other pieces between them all)\n* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)\n\n\nWith those constraints there are '''960''' possible starting positions, thus the name of the variant.\n\n\n;Task:\nThe purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nnamespace\n{\n void placeRandomly(char* p, char c)\n {\n\tint loc = rand() % 8;\n\tif (!p[loc])\n\t p[loc] = c;\n\telse\n\t placeRandomly(p, c); // try again\n }\n int placeFirst(char* p, char c, int loc = 0)\n {\n\twhile (p[loc]) ++loc;\n\tp[loc] = c;\n return loc;\n }\n\n string startPos()\n {\n\tchar p[8]; memset( p, 0, 8 );\n\n\t// bishops on opposite color\n\tp[2 * (rand() % 4)] = 'B';\n\tp[2 * (rand() % 4) + 1] = 'B';\n\n\t// queen knight knight, anywhere\n\tfor (char c : \"QNN\")\n\t placeRandomly(p, c);\n\n\t// rook king rook, in that order\n\tplaceFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));\n\n\treturn string(p, 8);\n }\n} // leave local\n\nnamespace chess960\n{\n void generate( int c )\n {\n\tfor( int x = 0; x < c; x++ )\n\t cout << startPos() << \"\\n\";\n }\n}\n\nint main( int argc, char* argv[] )\n{\n srand( time( NULL ) );\n chess960::generate( 10 );\n cout << \"\\n\\n\";\n return system( \"pause\" );\n}\n"} {"title": "Generate random chess position", "language": "C++", "task": "Generate a random chess position in FEN format. \n\nThe position does not have to be realistic or even balanced, but it must comply to the following rules:\n:* there is one and only one king of each color (one black king and one white king);\n:* the kings must not be placed on adjacent squares;\n:* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);\n:* including the kings, up to 32 pieces of either color can be placed. \n:* There is no requirement for material balance between sides. \n:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. \n:* it is white's turn.\n:* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1).\n\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.\n\n", "solution": "#include \n#include \n#include \n#include \n\nclass chessBoard {\npublic:\n void generateRNDBoard( int brds ) {\n int a, b, i; char c;\n for( int cc = 0; cc < brds; cc++ ) {\n memset( brd, 0, 64 );\n std::string pieces = \"PPPPPPPPNNBBRRQKppppppppnnbbrrqk\";\n random_shuffle( pieces.begin(), pieces.end() );\n\n while( pieces.length() ) {\n i = rand() % pieces.length(); c = pieces.at( i );\n while( true ) {\n a = rand() % 8; b = rand() % 8;\n if( brd[a][b] == 0 ) {\n if( c == 'P' && !b || c == 'p' && b == 7 || \n ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;\n break;\n }\n }\n brd[a][b] = c;\n pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );\n }\n print();\n }\n }\nprivate:\n bool search( char c, int a, int b ) {\n for( int y = -1; y < 2; y++ ) {\n for( int x = -1; x < 2; x++ ) {\n if( !x && !y ) continue;\n if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {\n if( brd[a + x][b + y] == c ) return true;\n }\n }\n }\n return false;\n }\n void print() {\n int e = 0;\n for( int y = 0; y < 8; y++ ) {\n for( int x = 0; x < 8; x++ ) {\n if( brd[x][y] == 0 ) e++;\n else {\n if( e > 0 ) { std::cout << e; e = 0; }\n std::cout << brd[x][y];\n }\n }\n if( e > 0 ) { std::cout << e; e = 0; } \n if( y < 7 ) std::cout << \"/\";\n }\n std::cout << \" w - - 0 1\\n\\n\";\n\n for( int y = 0; y < 8; y++ ) {\n for( int x = 0; x < 8; x++ ) {\n if( brd[x][y] == 0 ) std::cout << \".\";\n else std::cout << brd[x][y];\n }\n std::cout << \"\\n\";\n }\n\n std::cout << \"\\n\\n\";\n }\n char brd[8][8];\n};\nint main( int argc, char* argv[] ) {\n srand( ( unsigned )time( 0 ) );\n chessBoard c;\n c.generateRNDBoard( 2 );\n return 0;\n}\n"} {"title": "Generator/Exponential", "language": "C++", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "#include \nusing namespace std;\n\ntemplate\nclass Generator\n{\npublic:\n virtual T operator()() = 0;\n};\n\n// Does nothing unspecialized\ntemplate\nclass PowersGenerator: Generator {};\n\n// Specialize with other types, or provide a generic version of pow\ntemplate\nclass PowersGenerator: Generator\n{\npublic:\n int i;\n PowersGenerator() { i = 1; }\n virtual int operator()() \n { \n int o = 1; \n for(int j = 0; j < P; ++j) o *= i; \n ++i;\n return o; \n }\n};\n\n// Only works with non-decreasing generators\ntemplate\nclass Filter: Generator\n{\npublic:\n G gen;\n F filter;\n T lastG, lastF;\n\n Filter() { lastG = gen(); lastF = filter(); }\n\n virtual T operator()() \n {\n while(lastG >= lastF)\n {\n if(lastG == lastF)\n lastG = gen();\n lastF = filter();\n }\n\n T out = lastG;\n lastG = gen();\n return out;\n }\n};\n\nint main()\n{\n Filter, PowersGenerator> gen;\n\n for(int i = 0; i < 20; ++i)\n gen();\n\n for(int i = 20; i < 30; ++i)\n cout << i << \": \" << gen() << endl;\n}"} {"title": "Get system command output", "language": "C++", "task": "Task\nExecute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). \n\n;Related task\n* Execute a system command\n\n", "solution": "#include \n#include \n\nstd::string execute(const std::string& command) {\n system((command + \" > temp.txt\").c_str());\n\n std::ifstream ifs(\"temp.txt\");\n std::string ret{ std::istreambuf_iterator(ifs), std::istreambuf_iterator() };\n ifs.close(); // must close the inout stream so the file can be cleaned up\n if (std::remove(\"temp.txt\") != 0) {\n perror(\"Error deleting temporary file\");\n }\n return ret;\n}\n\nint main() {\n std::cout << execute(\"whoami\") << '\\n';\n}"} {"title": "Giuga numbers", "language": "C++", "task": "Definition\nA '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors\n'''f''' divide (n/f - 1) exactly.\n\nAll known Giuga numbers are even though it is not known for certain that there are no odd examples. \n\n;Example\n30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:\n* 30/2 - 1 = 14 is divisible by 2\n* 30/3 - 1 = 9 is divisible by 3\n* 30/5 - 1 = 5 is divisible by 5\n\n;Task\nDetermine and show here the first four Giuga numbers.\n\n;Stretch\nDetermine the fifth Giuga number and any more you have the patience for.\n\n;References\n\n* Wikipedia: Giuga number\n* OEIS:A007850 - Giuga numbers\n\n", "solution": "#include \n\n// Assumes n is even with exactly one factor of 2.\nbool is_giuga(unsigned int n) {\n unsigned int m = n / 2;\n auto test_factor = [&m, n](unsigned int p) -> bool {\n if (m % p != 0)\n return true;\n m /= p;\n return m % p != 0 && (n / p - 1) % p == 0;\n };\n if (!test_factor(3) || !test_factor(5))\n return false;\n static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};\n for (unsigned int p = 7, i = 0; p * p <= m; ++i) {\n if (!test_factor(p))\n return false;\n p += wheel[i & 7];\n }\n return m == 1 || (n / m - 1) % m == 0;\n}\n\nint main() {\n std::cout << \"First 5 Giuga numbers:\\n\";\n // n can't be 2 or divisible by 4\n for (unsigned int i = 0, n = 6; i < 5; n += 4) {\n if (is_giuga(n)) {\n std::cout << n << '\\n';\n ++i;\n }\n }\n}"} {"title": "Giuga numbers", "language": "C++ from Wren", "task": "Definition\nA '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors\n'''f''' divide (n/f - 1) exactly.\n\nAll known Giuga numbers are even though it is not known for certain that there are no odd examples. \n\n;Example\n30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:\n* 30/2 - 1 = 14 is divisible by 2\n* 30/3 - 1 = 9 is divisible by 3\n* 30/5 - 1 = 5 is divisible by 5\n\n;Task\nDetermine and show here the first four Giuga numbers.\n\n;Stretch\nDetermine the fifth Giuga number and any more you have the patience for.\n\n;References\n\n* Wikipedia: Giuga number\n* OEIS:A007850 - Giuga numbers\n\n", "solution": "#include \n\n#include \n#include \n#include \n#include \n\nusing rational = boost::rational;\n\nbool is_prime(uint64_t n) {\n if (n < 2)\n return false;\n if (n % 2 == 0)\n return n == 2;\n if (n % 3 == 0)\n return n == 3;\n for (uint64_t p = 5; p * p <= n; p += 4) {\n if (n % p == 0)\n return false;\n p += 2;\n if (n % p == 0)\n return false;\n }\n return true;\n}\n\nuint64_t next_prime(uint64_t n) {\n while (!is_prime(n))\n ++n;\n return n;\n}\n\nstd::vector divisors(uint64_t n) {\n std::vector div{1};\n for (uint64_t i = 2; i * i <= n; ++i) {\n if (n % i == 0) {\n div.push_back(i);\n if (i * i != n)\n div.push_back(n / i);\n }\n }\n div.push_back(n);\n sort(div.begin(), div.end());\n return div;\n}\n\nvoid giuga_numbers(uint64_t n) {\n std::cout << \"n = \" << n << \":\";\n std::vector p(n, 0);\n std::vector s(n, 0);\n p[2] = 2;\n p[1] = 2;\n s[1] = rational(1, 2);\n for (uint64_t t = 2; t > 1;) {\n p[t] = next_prime(p[t] + 1);\n s[t] = s[t - 1] + rational(1, p[t]);\n if (s[t] == 1 || s[t] + rational(n - t, p[t]) <= rational(1)) {\n --t;\n } else if (t < n - 2) {\n ++t;\n uint64_t c = s[t - 1].numerator();\n uint64_t d = s[t - 1].denominator();\n p[t] = std::max(p[t - 1], c / (d - c));\n } else {\n uint64_t c = s[n - 2].numerator();\n uint64_t d = s[n - 2].denominator();\n uint64_t k = d * d + c - d;\n auto div = divisors(k);\n uint64_t count = (div.size() + 1) / 2;\n for (uint64_t i = 0; i < count; ++i) {\n uint64_t h = div[i];\n if ((h + d) % (d - c) == 0 && (k / h + d) % (d - c) == 0) {\n uint64_t r1 = (h + d) / (d - c);\n uint64_t r2 = (k / h + d) / (d - c);\n if (r1 > p[n - 2] && r2 > p[n - 2] && r1 != r2 &&\n is_prime(r1) && is_prime(r2)) {\n std::cout << ' ' << d * r1 * r2;\n }\n }\n }\n }\n }\n std::cout << '\\n';\n}\n\nint main() {\n for (uint64_t n = 3; n < 7; ++n)\n giuga_numbers(n);\n}"} {"title": "Globally replace text in several files", "language": "C++", "task": "Replace every occurring instance of a piece of text in a group of text files with another one. \n\n\nFor this task we want to replace the text \"'''Goodbye London!'''\" with \"'''Hello New York!'''\" for a list of files.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nint main( int argc , char *argv[ ] ) {\n boost::regex to_be_replaced( \"Goodbye London\\\\s*!\" ) ;\n std::string replacement( \"Hello New York!\" ) ;\n for ( int i = 1 ; i < argc ; i++ ) {\n std::ifstream infile ( argv[ i ] ) ;\n if ( infile ) {\n\t std::string filetext( (std::istreambuf_iterator( infile )) ,\n\t std::istreambuf_iterator( ) ) ;\n\t std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ;\n\t infile.close( ) ;\n\t std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ;\n\t if ( outfile.is_open( ) ) { \n\t outfile << changed ;\n\t outfile.close( ) ;\n\t }\n }\n else \n\t std::cout << \"Can't find file \" << argv[ i ] << \" !\\n\" ;\n }\n return 0 ;\n}"} {"title": "Gray code", "language": "C++", "task": "Karnaugh maps in order from left to right or top to bottom.\nCreate functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* Converting Between Gray and Binary Codes. It includes step-by-step animations.\n\n", "solution": "#include \n#include \n#include \n#include \n\nuint32_t gray_encode(uint32_t b)\n{\n return b ^ (b >> 1);\n}\n\nuint32_t gray_decode(uint32_t g)\n{\n for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)\n {\n if (g & bit) g ^= bit >> 1;\n }\n return g;\n}\n\nstd::string to_binary(int value) // utility function\n{\n const std::bitset<32> bs(value);\n const std::string str(bs.to_string());\n const size_t pos(str.find('1'));\n return pos == std::string::npos ? \"0\" : str.substr(pos);\n}\n\nint main()\n{\n std::cout << \"Number\\tBinary\\tGray\\tDecoded\\n\";\n for (uint32_t n = 0; n < 32; ++n)\n {\n uint32_t g = gray_encode(n);\n assert(gray_decode(g) == n);\n\n std::cout << n << \"\\t\" << to_binary(n) << \"\\t\" << to_binary(g) << \"\\t\" << g << \"\\n\";\n }\n}"} {"title": "Greatest subsequential sum", "language": "C++", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "#include // for std::pair\n#include // for std::iterator_traits\n#include // for std::cout\n#include // for output operator and std::endl\n#include // for std::copy\n#include // for std::output_iterator\n\n// Function template max_subseq\n//\n// Given a sequence of integers, find a subsequence which maximizes\n// the sum of its elements, that is, the elements of no other single\n// subsequence add up to a value larger than this one.\n//\n// Requirements:\n// * ForwardIterator is a forward iterator\n// * ForwardIterator's value_type is less-than comparable and addable\n// * default-construction of value_type gives the neutral element\n// (zero)\n// * operator+ and operator< are compatible (i.e. if a>zero and\n// b>zero, then a+b>zero, and if a\n std::pair\n max_subseq(ForwardIterator begin, ForwardIterator end)\n{\n typedef typename std::iterator_traits::value_type\n value_type;\n\n ForwardIterator seq_begin = begin, seq_end = seq_begin;\n value_type seq_sum = value_type();\n ForwardIterator current_begin = begin;\n value_type current_sum = value_type();\n\n value_type zero = value_type();\n\n for (ForwardIterator iter = begin; iter != end; ++iter)\n {\n value_type value = *iter;\n if (zero < value)\n {\n if (current_sum < zero)\n {\n current_sum = zero;\n current_begin = iter;\n }\n }\n else\n {\n if (seq_sum < current_sum)\n {\n seq_begin = current_begin;\n seq_end = iter;\n seq_sum = current_sum;\n }\n }\n current_sum += value;\n }\n\n if (seq_sum < current_sum)\n {\n seq_begin = current_begin;\n seq_end = end;\n seq_sum = current_sum;\n }\n\n return std::make_pair(seq_begin, seq_end);\n}\n\n// the test array\nint array[] = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 };\n\n// function template to find the one-past-end pointer to the array\ntemplate int* end(T (&arr)[N]) { return arr+N; }\n\nint main()\n{\n // find the subsequence\n std::pair seq = max_subseq(array, end(array));\n\n // output it\n std::copy(seq.first, seq.second, std::ostream_iterator(std::cout, \" \"));\n std::cout << std::endl;\n\n return 0;\n}"} {"title": "Greyscale bars/Display", "language": "C++", "task": "The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. \n\nFor the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)\n\nFor the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).\n\nHalfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.\n\n", "solution": "#include \n#include \"greytones.h\"\n\nMyWidget::MyWidget( ) {\n setGeometry( 0, 0 , 640 , 480 ) ;\n}\n\nvoid MyWidget::paintEvent ( QPaintEvent * ) {\n QBrush myBrush( Qt::SolidPattern ) ;\n QPainter myPaint( this ) ;\n int run = 0 ; //how often have we run through the loop ?\n int colorcomp = 0 ;\n for ( int columncount = 8 ; columncount < 128 ; columncount *= 2 ) {\n int colorgap = 255 / columncount ;\n int columnwidth = 640 / columncount ; // 640 being the window width\n int columnheight = 480 / 4 ; //we're looking at quarters\n if ( run % 2 == 0 ) { //we start with black columns \n\t colorcomp = 0 ;\n }\n else { //we start with white columns \n\t colorcomp = 255 ;\n\t colorgap *= -1 ; //we keep subtracting color values \n }\n int ystart = 0 + columnheight * run ; //determines the y coordinate of the first column per row\n int xstart = 0 ;\n for ( int i = 0 ; i < columncount ; i++ ) {\n\t myBrush.setColor( QColor( colorcomp, colorcomp , colorcomp ) ) ;\n\t myPaint.fillRect( xstart , ystart , columnwidth , columnheight , myBrush ) ;\n\t xstart += columnwidth ;\n\t colorcomp += colorgap ; //we choose the next color \n }\n run++ ;\n }\n}"} {"title": "Hailstone sequence", "language": "C++", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "#include \n#include \n#include \n\nstd::vector hailstone(int i)\n{\n std::vector v;\n while(true){ \n v.push_back(i);\n if (1 == i) break; \n i = (i % 2) ? (3 * i + 1) : (i / 2);\n }\n return v;\n}\n\nstd::pair find_longest_hailstone_seq(int n)\n{\n std::pair maxseq(0, 0);\n int l; \n for(int i = 1; i < n; ++i){\n l = hailstone(i).size(); \n if (l > maxseq.second) maxseq = std::make_pair(i, l);\n } \n return maxseq;\n}\n\nint main () {\n\n// Use the routine to show that the hailstone sequence for the number 27 \n std::vector h27;\n h27 = hailstone(27); \n// has 112 elements \n int l = h27.size();\n std::cout << \"length of hailstone(27) is \" << l;\n// starting with 27, 82, 41, 124 and \n std::cout << \" first four elements of hailstone(27) are \";\n std::cout << h27[0] << \" \" << h27[1] << \" \" \n << h27[2] << \" \" << h27[3] << std::endl;\n// ending with 8, 4, 2, 1\n std::cout << \" last four elements of hailstone(27) are \"\n << h27[l-4] << \" \" << h27[l-3] << \" \" \n << h27[l-2] << \" \" << h27[l-1] << std::endl;\n\n std::pair m = find_longest_hailstone_seq(100000); \n\n std::cout << \"the longest hailstone sequence under 100,000 is \" << m.first \n << \" with \" << m.second << \" elements.\" <\nint main()\n{\n throw std::runtime_error(\"boom\");\n}"} {"title": "Harshad or Niven series", "language": "C++", "task": "The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. \n\nFor example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.\n\nAssume that the series is defined as the numbers in increasing order.\n\n\n;Task:\nThe task is to create a function/method/procedure to generate successive members of the Harshad sequence. \n\nUse it to:\n::* list the first '''20''' members of the sequence, and\n::* list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* Increasing gaps between consecutive Niven numbers\n\n\n;See also\n* OEIS: A005349\n\n", "solution": "#include \n#include \n\nint sumDigits ( int number ) {\n int sum = 0 ;\n while ( number != 0 ) {\n sum += number % 10 ;\n number /= 10 ;\n }\n return sum ;\n}\n\nbool isHarshad ( int number ) {\n return number % ( sumDigits ( number ) ) == 0 ;\n}\n\nint main( ) {\n std::vector harshads ;\n int i = 0 ;\n while ( harshads.size( ) != 20 ) {\n i++ ;\n if ( isHarshad ( i ) ) \n\t harshads.push_back( i ) ;\n }\n std::cout << \"The first 20 Harshad numbers:\\n\" ;\n for ( int number : harshads )\n std::cout << number << \" \" ;\n std::cout << std::endl ;\n int start = 1001 ;\n while ( ! ( isHarshad ( start ) ) ) \n start++ ;\n std::cout << \"The smallest Harshad number greater than 1000 : \" << start << '\\n' ;\n return 0 ;\n}"} {"title": "Hash join", "language": "C++", "task": "{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing tab_t = std::vector>;\ntab_t tab1 {\n// Age Name\n {\"27\", \"Jonah\"}\n, {\"18\", \"Alan\"}\n, {\"28\", \"Glory\"}\n, {\"18\", \"Popeye\"}\n, {\"28\", \"Alan\"}\n};\n\ntab_t tab2 {\n// Character Nemesis\n {\"Jonah\", \"Whales\"}\n, {\"Jonah\", \"Spiders\"}\n, {\"Alan\", \"Ghosts\"}\n, {\"Alan\", \"Zombies\"}\n, {\"Glory\", \"Buffy\"}\n};\n\nstd::ostream& operator<<(std::ostream& o, const tab_t& t) {\n for(size_t i = 0; i < t.size(); ++i) {\n o << i << \":\";\n for(const auto& e : t[i]) \n o << '\\t' << e;\n o << std::endl;\n }\n return o;\n}\n\ntab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {\n std::unordered_multimap hashmap;\n // hash\n for(size_t i = 0; i < a.size(); ++i) {\n hashmap.insert(std::make_pair(a[i][columna], i));\n }\n // map\n tab_t result;\n for(size_t i = 0; i < b.size(); ++i) {\n auto range = hashmap.equal_range(b[i][columnb]);\n for(auto it = range.first; it != range.second; ++it) {\n tab_t::value_type row;\n row.insert(row.end() , a[it->second].begin() , a[it->second].end());\n row.insert(row.end() , b[i].begin() , b[i].end());\n result.push_back(std::move(row));\n }\n }\n return result;\n}\n\nint main(int argc, char const *argv[])\n{\n using namespace std;\n int ret = 0;\n cout << \"Table A: \" << endl << tab1 << endl;\n cout << \"Table B: \" << endl << tab2 << endl;\n auto tab3 = Join(tab1, 1, tab2, 0);\n cout << \"Joined tables: \" << endl << tab3 << endl;\n return ret;\n}\n\n"} {"title": "Haversine formula", "language": "C++", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "#define _USE_MATH_DEFINES\n\n#include \n#include \n\nconst static double EarthRadiusKm = 6372.8;\n\ninline double DegreeToRadian(double angle)\n{\n\treturn M_PI * angle / 180.0;\n}\n\nclass Coordinate\n{\npublic:\n\tCoordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude)\n\t{}\n\n\tdouble Latitude() const\n\t{\n\t\treturn myLatitude;\n\t}\n\n\tdouble Longitude() const\n\t{\n\t\treturn myLongitude;\n\t}\n\nprivate:\n\n\tdouble myLatitude;\n\tdouble myLongitude;\n};\n\ndouble HaversineDistance(const Coordinate& p1, const Coordinate& p2)\n{\n\tdouble latRad1 = DegreeToRadian(p1.Latitude());\n\tdouble latRad2 = DegreeToRadian(p2.Latitude());\n\tdouble lonRad1 = DegreeToRadian(p1.Longitude());\n\tdouble lonRad2 = DegreeToRadian(p2.Longitude());\n\n\tdouble diffLa = latRad2 - latRad1;\n\tdouble doffLo = lonRad2 - lonRad1;\n\n\tdouble computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2)));\n\treturn 2 * EarthRadiusKm * computation;\n}\n\nint main()\n{\n\tCoordinate c1(36.12, -86.67);\n\tCoordinate c2(33.94, -118.4);\n\n\tstd::cout << \"Distance = \" << HaversineDistance(c1, c2) << std::endl;\n\treturn 0;\n}\n"} {"title": "Hello world/Line printer", "language": "C++", "task": "Cause a line printer attached to the computer to print a line containing the message: Hello World! \n\n\n;Note:\nA line printer is not the same as standard output. \n\nA line printer was an older-style printer which prints one line at a time to a continuous ream of paper. \n\nWith some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).\n\n", "solution": "#include \n#include \n\nint main(){\n std::ofstream lprFile;\n lprFile.open( \"/dev/lp0\" );\n lprFile << \"Hello World!\\n\";\n lprFile.close();\n return 0;\n}"} {"title": "Hello world/Newbie", "language": "C++", "task": "Guide a new user of a language through the steps necessary \nto install the programming language and selection of a text editor if needed, \nto run the languages' example in the [[Hello world/Text]] task.\n* Assume the language-newbie is a programmer in another language.\n* Assume the language-newbie is competent in installing software for the platform.\n* Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).\n* Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).\n* Remember to state where to view the output.\n* If particular IDE's or editors are required that are not standard, then point to/explain their installation too.\n\n\n;Note:\n* If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.\n* You may use sub-headings if giving instructions for multiple platforms.\n\n", "solution": "#include \nint main() {\n using namespace std;\n cout << \"Hello, World!\" << endl;\n return 0;\n}"} {"title": "Here document", "language": "C++11", "task": "A ''here document'' (or \"heredoc\") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. \n\nDepending on the language being used, a ''here document'' is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string. \n\nThe text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.\n\n\n;Task:\nDemonstrate the use of ''here documents'' within the language.\n\n;Related task:\n* [[Documentation]]\n\n", "solution": "#include // Only for cout to demonstrate\n\nint main()\n{\n std::cout <<\nR\"EOF( A raw string begins with R, then a double-quote (\"), then an optional\nidentifier (here I've used \"EOF\"), then an opening parenthesis ('('). If you\nuse an identifier, it cannot be longer than 16 characters, and it cannot\ncontain a space, either opening or closing parentheses, a backslash, a tab, a\nvertical tab, a form feed, or a newline.\n\n It ends with a closing parenthesis (')'), the identifer (if you used one),\nand a double-quote.\n\n All characters are okay in a raw string, no escape sequences are necessary\nor recognized, and all whitespace is preserved.\n)EOF\";\n}"} {"title": "Heronian triangles", "language": "C++17", "task": "Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere ''s'' is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''Heronian triangles'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.\n\nDefine a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor \nof all three sides is '''1''' (unity). \n\nThis will exclude, for example, triangle '''6, 8, 10.'''\n\n\n;Task:\n# Create a named function/method/procedure/... that implements Hero's formula.\n# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.\n# Show the count of how many triangles are found.\n# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths\n# Show the first ten ordered triangles in a table of sides, perimeter, and area.\n# Show a similar ordered table for those triangles with area = 210\n\n\nShow all output here.\n\n'''Note''': when generating triangles it may help to restrict a <= b <= c\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n#include \n\nstruct Triangle {\n int a{};\n int b{};\n int c{};\n\n [[nodiscard]] constexpr auto perimeter() const noexcept { return a + b + c; }\n\n [[nodiscard]] constexpr auto area() const noexcept {\n const auto p_2 = static_cast(perimeter()) / 2;\n const auto area_sq = p_2 * (p_2 - a) * (p_2 - b) * (p_2 - c);\n return std::sqrt(area_sq);\n }\n};\n\n\nauto generate_triangles(int side_limit = 200) {\n std::vector result;\n for(int a = 1; a <= side_limit; ++a)\n for(int b = 1; b <= a; ++b)\n for(int c = a + 1 - b; c <= b; ++c) // skip too-small values of c, which will violate triangle inequality\n {\n Triangle t{ a, b, c };\n const auto t_area = t.area();\n if (t_area == 0) continue;\n if (std::floor(t_area) == std::ceil(t_area) && std::gcd(a, std::gcd(b, c)) == 1)\n result.push_back(t);\n }\n return result;\n}\n\nbool compare(const Triangle& lhs, const Triangle& rhs) noexcept {\n return std::make_tuple(lhs.area(), lhs.perimeter(), std::max(lhs.a, std::max(lhs.b, lhs.c))) <\n std::make_tuple(rhs.area(), rhs.perimeter(), std::max(rhs.a, std::max(rhs.b, rhs.c)));\n}\n\nstruct area_compare {\n [[nodiscard]] constexpr bool operator()(const Triangle& t, int i) const noexcept { return t.area() < i; }\n [[nodiscard]] constexpr bool operator()(int i, const Triangle& t) const noexcept { return i < t.area(); }\n};\n\nint main() {\n auto tri = generate_triangles();\n std::cout << \"There are \" << tri.size() << \" primitive Heronian triangles with sides up to 200\\n\\n\";\n\n std::cout << \"First ten when ordered by increasing area, then perimeter, then maximum sides:\\n\";\n std::sort(tri.begin(), tri.end(), compare);\n std::cout << \"area\\tperimeter\\tsides\\n\";\n for(int i = 0; i < 10; ++i)\n std::cout << tri[i].area() << '\\t' << tri[i].perimeter() << \"\\t\\t\" <<\n tri[i].a << 'x' << tri[i].b << 'x' << tri[i].c << '\\n';\n\n std::cout << \"\\nAll with area 210 subject to the previous ordering:\\n\";\n auto range = std::equal_range(tri.begin(), tri.end(), 210, area_compare());\n std::cout << \"area\\tperimeter\\tsides\\n\";\n for(auto it = range.first; it != range.second; ++it)\n std::cout << (*it).area() << '\\t' << (*it).perimeter() << \"\\t\\t\" <<\n it->a << 'x' << it->b << 'x' << it->c << '\\n';\n}"} {"title": "Hofstadter-Conway $10,000 sequence", "language": "C++", "task": "The definition of the sequence is colloquially described as:\n* Starting with the list [1,1],\n* Take the last number in the list so far: 1, I'll call it x.\n* Count forward x places from the beginning of the list to find the first number to add (1)\n* Count backward x places from the end of the list to find the second number to add (1)\n* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* This would then produce [1,1,2] where 2 is the third element of the sequence.\n\nNote that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.\n\nA less wordy description of the sequence is:\n a(1)=a(2)=1\n a(n)=a(a(n-1))+a(n-a(n-1))\n\nThe sequence begins:\n 1, 1, 2, 2, 3, 4, 4, 4, 5, ...\n\nInteresting features of the sequence are that:\n* a(n)/n tends to 0.5 as n grows towards infinity.\n* a(n)/n where n is a power of 2 is 0.5\n* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.\n\na(n) / n for n in 1..256 \n\n\nThe sequence is so named because John Conway offered a prize of $10,000 to the first person who could\nfind the first position, p in the sequence where \n |a(n)/n| < 0.55 for all n > p\nIt was later found that Hofstadter had also done prior work on the sequence.\n\nThe 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20\n# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20\n\n\n\n;Also see:\n* Conways Challenge Sequence, Mallows' own account.\n* Mathworld Article.\n\n", "solution": "#include \n#include \n\nint hcseq(int n)\n{\n static std::deque seq(2, 1);\n while (seq.size() < n)\n {\n int x = seq.back();\n seq.push_back(seq[x-1] + seq[seq.size()-x]);\n }\n return seq[n-1];\n}\n\nint main()\n{\n int pow2 = 1;\n for (int i = 0; i < 20; ++i)\n {\n int pow2next = 2*pow2;\n double max = 0;\n for (int n = pow2; n < pow2next; ++n)\n {\n double anon = hcseq(n)/double(n);\n if (anon > max)\n max = anon;\n }\n std::cout << \"maximum of a(n)/n between 2^\" << i\n << \" (\" << pow2 << \") and 2^\" << i+1\n << \" (\" << pow2next << \") is \" << max << \"\\n\";\n pow2 = pow2next;\n }\n}\n"} {"title": "Hofstadter Figure-Figure sequences", "language": "C++ 11, 14, 17", "task": "These two sequences of positive integers are defined as:\n:::: \\begin{align}\nR(1)&=1\\ ;\\ S(1)=2 \\\\\nR(n)&=R(n-1)+S(n-1), \\quad n>1.\n\\end{align}\n\nThe sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).\n\nSequence R starts: \n 1, 3, 7, 12, 18, ...\nSequence S starts: \n 2, 4, 5, 6, 8, ...\n\n\n;Task:\n# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).\n# No maximum value for '''n''' should be assumed.\n# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69\n# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.\n\n\n;References:\n* Sloane's A005228 and A030124.\n* Wolfram MathWorld\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\n\nunsigned hofstadter(unsigned rlistSize, unsigned slistSize)\n{\n auto n = rlistSize > slistSize ? rlistSize : slistSize;\n auto rlist = new vector { 1, 3, 7 };\n auto slist = new vector { 2, 4, 5, 6 };\n auto list = rlistSize > 0 ? rlist : slist;\n auto target_size = rlistSize > 0 ? rlistSize : slistSize;\n\n while (list->size() > target_size) list->pop_back();\n\n while (list->size() < target_size)\n {\n auto lastIndex = rlist->size() - 1;\n auto lastr = (*rlist)[lastIndex];\n auto r = lastr + (*slist)[lastIndex];\n rlist->push_back(r);\n for (auto s = lastr + 1; s < r && list->size() < target_size;)\n slist->push_back(s++);\n }\n\n auto v = (*list)[n - 1];\n delete rlist;\n delete slist;\n return v;\n}\n\nostream& operator<<(ostream& os, const set& s)\n{\n cout << '(' << s.size() << \"):\";\n auto i = 0;\n for (auto c = s.begin(); c != s.end();)\n {\n if (i++ % 20 == 0) os << endl;\n os << setw(5) << *c++;\n }\n return os;\n}\n\nint main(int argc, const char* argv[])\n{\n const auto v1 = atoi(argv[1]);\n const auto v2 = atoi(argv[2]);\n set r, s;\n for (auto n = 1; n <= v2; n++)\n {\n if (n <= v1)\n r.insert(hofstadter(n, 0));\n s.insert(hofstadter(0, n));\n }\n cout << \"R\" << r << endl;\n cout << \"S\" << s << endl;\n\n int m = max(*r.rbegin(), *s.rbegin());\n for (auto n = 1; n <= m; n++)\n if (r.count(n) == s.count(n))\n clog << \"integer \" << n << \" either in both or neither set\" << endl;\n\n return 0;\n}"} {"title": "Hofstadter Q sequence", "language": "C++", "task": "The Hofstadter Q sequence is defined as:\n:: \\begin{align}\nQ(1)&=Q(2)=1, \\\\\nQ(n)&=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)\\big), \\quad n>2.\n\\end{align}\n\n\nIt is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.\n\n\n;Task:\n* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 \n* Confirm and display that the 1000th term is: 502\n\n\n;Optional extra credit\n* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.\n* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.\n(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).\n\n", "solution": "#include \n \nint main() {\n const int size = 100000;\n int hofstadters[size] = { 1, 1 }; \n for (int i = 3 ; i < size; i++) \n hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +\n hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];\n std::cout << \"The first 10 numbers are: \";\n for (int i = 0; i < 10; i++) \n std::cout << hofstadters[ i ] << ' ';\n std::cout << std::endl << \"The 1000'th term is \" << hofstadters[ 999 ] << \" !\" << std::endl;\n int less_than_preceding = 0;\n for (int i = 0; i < size - 1; i++)\n if (hofstadters[ i + 1 ] < hofstadters[ i ]) \n\t less_than_preceding++;\n std::cout << \"In array of size: \" << size << \", \";\n std::cout << less_than_preceding << \" times a number was preceded by a greater number!\" << std::endl;\n return 0;\n}"} {"title": "Horner's rule for polynomial evaluation", "language": "C++", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.\n\nCf. [[Formal power series]]\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\ndouble horner(vector v, double x)\n{\n double s = 0;\n \n for( vector::const_reverse_iterator i = v.rbegin(); i != v.rend(); i++ )\n s = s*x + *i;\n return s;\n}\n\nint main()\n{\n double c[] = { -19, 7, -4, 6 };\n vector v(c, c + sizeof(c)/sizeof(double));\n cout << horner(v, 3.0) << endl;\n return 0;\n}"} {"title": "ISBN13 check digit", "language": "C++ from C", "task": "Validate the check digit of an ISBN-13 code:\n::* Multiply every other digit by '''3'''.\n::* Add these numbers and the other digits.\n::* Take the remainder of this number after division by '''10'''.\n::* If it is '''0''', the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* 978-0596528126 (good)\n::::* 978-0596528120 (bad)\n::::* 978-1788399081 (good)\n::::* 978-1788399083 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* for details: 13-digit ISBN method of validation. (installs cookies.)\n\n", "solution": "#include \n\nbool check_isbn13(std::string isbn) {\n int count = 0;\n int sum = 0;\n\n for (auto ch : isbn) {\n /* skip hyphens or spaces */\n if (ch == ' ' || ch == '-') {\n continue;\n }\n if (ch < '0' || ch > '9') {\n return false;\n }\n if (count & 1) {\n sum += 3 * (ch - '0');\n } else {\n sum += ch - '0';\n }\n count++;\n }\n\n if (count != 13) {\n return false;\n }\n return sum % 10 == 0;\n}\n\nint main() {\n auto isbns = { \"978-1734314502\", \"978-1734314509\", \"978-1788399081\", \"978-1788399083\" };\n for (auto isbn : isbns) {\n std::cout << isbn << \": \" << (check_isbn13(isbn) ? \"good\" : \"bad\") << '\\n';\n }\n\n return 0;\n}"} {"title": "I before E except after C", "language": "C++", "task": "The phrase \"I before E, except after C\" is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# ''\"I before E when not preceded by C\"''\n:::# ''\"E before I when preceded by C\"''\n\n\nIf both sub-phrases are plausible then the original phrase can be said to be plausible.\n\nSomething is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).\n \n\n;Stretch goal:\nAs a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.\n\n\n''Show your output here as well as your program.''\n\n\n\n\n;cf.:\n* Schools to rethink 'i before e' - BBC news, 20 June 2009\n* I Before E Except After C - QI Series 8 Ep 14, (humorous)\n* Companion website for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\nstruct Claim {\n Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() {\n }\n \n void add_pro(const std::string& pat) { \n propats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); \n }\n void add_against(const std::string& pat) { \n againstpats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); \n }\n bool plausible() const { return pro_ > against_*2; }\n void check(const char * buf, uint32_t len) {\n for (auto i = propats_.begin(), ii = propats_.end(); i != ii; ++i) {\n uint32_t pos = 0;\n boost::cmatch m;\n if (std::get<1>(*i) && pos > 0) continue;\n while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) {\n ++pro_;\n if (pos > 0) std::cerr << name_ << \" [pro] multiple matches in: \" << buf << \"\\n\";\n pos += m.position() + m.length();\n }\n }\n for (auto i = againstpats_.begin(), ii = againstpats_.end(); i != ii; ++i) {\n uint32_t pos = 0;\n boost::cmatch m;\n if (std::get<1>(*i) && pos > 0) continue;\n while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) {\n ++against_;\n if (pos > 0) std::cerr << name_ << \" [against] multiple matches in: \" << buf << \"\\n\";\n pos += m.position() + m.length();\n }\n }\n }\n friend std::ostream& operator<<(std::ostream& os, const Claim& c);\nprivate:\n std::string name_;\n uint32_t pro_;\n uint32_t against_;\n // tuple\n std::vector> propats_;\n std::vector> againstpats_;\n};\n\nstd::ostream& operator<<(std::ostream& os, const Claim& c) {\n os << c.name_ << \": matches: \" << c.pro_ << \" vs. counter matches: \" << c.against_ << \". \";\n os << \"Plausibility: \" << (c.plausible() ? \"yes\" : \"no\") << \".\";\n return os;\n}\n\n\nint main(int argc, char ** argv) {\n try {\n if (argc < 2) throw std::runtime_error(\"No input file.\");\n std::ifstream is(argv[1]);\n if (! is) throw std::runtime_error(\"Input file not valid.\");\n\n Claim ieclaim(\"[^c]ie\");\n ieclaim.add_pro(\"[^c]ie\");\n ieclaim.add_pro(\"^ie\");\n ieclaim.add_against(\"[^c]ei\");\n ieclaim.add_against(\"^ei\");\n\n Claim ceiclaim(\"cei\");\n ceiclaim.add_pro(\"cei\");\n ceiclaim.add_against(\"cie\");\n\n {\n const uint32_t MAXLEN = 32;\n char buf[MAXLEN];\n uint32_t longest = 0;\n while (is) {\n is.getline(buf, sizeof(buf));\n if (is.gcount() <= 0) break;\n else if (is.gcount() > longest) longest = is.gcount();\n ieclaim.check(buf, is.gcount());\n ceiclaim.check(buf, is.gcount());\n }\n if (longest >= MAXLEN) throw std::runtime_error(\"Buffer too small.\");\n }\n\n std::cout << ieclaim << \"\\n\";\n std::cout << ceiclaim << \"\\n\";\n std::cout << \"Overall plausibility: \" << (ieclaim.plausible() && ceiclaim.plausible() ? \"yes\" : \"no\") << \"\\n\";\n\n\n } catch (const std::exception& ex) {\n std::cerr << \"*** Error: \" << ex.what() << \"\\n\";\n return -1;\n }\n return 0;\n}\n"} {"title": "Imaginary base numbers", "language": "C++ from C#", "task": "Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. \n\n''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]''\n\nOther imaginary bases are possible too but are not as widely discussed and aren't specifically named.\n\n'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. \n\nAt a minimum, support quater-imaginary (base 2i).\n\nFor extra kudos, support positive or negative bases 2i through 6i (or higher).\n\nAs a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.\n\nSee Wikipedia: Quater-imaginary_base for more details. \n\nFor reference, here are some some decimal and complex numbers converted to quater-imaginary.\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1\n 1\n\n\n2\n 2\n\n\n3\n 3\n\n\n4\n 10300\n\n\n5\n 10301\n\n\n6\n 10302\n\n\n7\n 10303\n\n\n8\n 10200\n\n\n9\n 10201\n\n\n10\n 10202\n\n\n11\n 10203\n\n\n12\n 10100\n\n\n13\n 10101\n\n\n14\n 10102\n\n\n15\n 10103\n\n\n16\n 10000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1\n 103\n\n\n-2\n 102\n\n\n-3\n 101\n\n\n-4\n 100\n\n\n-5\n 203\n\n\n-6\n 202\n\n\n-7\n 201\n\n\n-8\n 200\n\n\n-9\n 303\n\n\n-10\n 302\n\n\n-11\n 301\n\n\n-12\n 300\n\n\n-13\n 1030003\n\n\n-14\n 1030002\n\n\n-15\n 1030001\n\n\n-16\n 1030000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1i\n10.2\n\n\n2i\n10.0\n\n\n3i\n20.2\n\n\n4i\n20.0\n\n\n5i\n30.2\n\n\n6i\n30.0\n\n\n7i\n103000.2\n\n\n8i\n103000.0\n\n\n9i\n103010.2\n\n\n10i\n103010.0\n\n\n11i\n103020.2\n\n\n12i\n103020.0\n\n\n13i\n103030.2\n\n\n14i\n103030.0\n\n\n15i\n102000.2\n\n\n16i\n102000.0\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1i\n0.2\n\n\n-2i\n1030.0\n\n\n-3i\n1030.2\n\n\n-4i\n1020.0\n\n\n-5i\n1020.2\n\n\n-6i\n1010.0\n\n\n-7i\n1010.2\n\n\n-8i\n1000.0\n\n\n-9i\n1000.2\n\n\n-10i\n2030.0\n\n\n-11i\n2030.2\n\n\n-12i\n2020.0\n\n\n-13i\n2020.2\n\n\n-14i\n2010.0\n\n\n-15i\n2010.2\n\n\n-16i\n2000.0\n\n\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::complex inv(const std::complex& c) {\n double denom = c.real() * c.real() + c.imag() * c.imag();\n return std::complex(c.real() / denom, -c.imag() / denom);\n}\n\nclass QuaterImaginary {\npublic:\n QuaterImaginary(const std::string& s) : b2i(s) {\n static std::string base(\"0123.\");\n\n if (b2i.empty()\n || std::any_of(s.cbegin(), s.cend(), [](char c) { return base.find(c) == std::string::npos; })\n || std::count(s.cbegin(), s.cend(), '.') > 1) {\n throw std::runtime_error(\"Invalid base 2i number\");\n }\n }\n\n QuaterImaginary& operator=(const QuaterImaginary& q) {\n b2i = q.b2i;\n return *this;\n }\n\n std::complex toComplex() const {\n int pointPos = b2i.find('.');\n int posLen = (pointPos != std::string::npos) ? pointPos : b2i.length();\n std::complex sum(0.0, 0.0);\n std::complex prod(1.0, 0.0);\n for (int j = 0; j < posLen; j++) {\n double k = (b2i[posLen - 1 - j] - '0');\n if (k > 0.0) {\n sum += prod * k;\n }\n prod *= twoI;\n }\n if (pointPos != -1) {\n prod = invTwoI;\n for (size_t j = posLen + 1; j < b2i.length(); j++) {\n double k = (b2i[j] - '0');\n if (k > 0.0) {\n sum += prod * k;\n }\n prod *= invTwoI;\n }\n }\n\n return sum;\n }\n\n friend std::ostream& operator<<(std::ostream&, const QuaterImaginary&);\n\nprivate:\n const std::complex twoI{ 0.0, 2.0 };\n const std::complex invTwoI = inv(twoI);\n\n std::string b2i;\n};\n\nstd::ostream& operator<<(std::ostream& os, const QuaterImaginary& q) {\n return os << q.b2i;\n}\n\n// only works properly if 'real' and 'imag' are both integral\nQuaterImaginary toQuaterImaginary(const std::complex& c) {\n if (c.real() == 0.0 && c.imag() == 0.0) return QuaterImaginary(\"0\");\n\n int re = (int)c.real();\n int im = (int)c.imag();\n int fi = -1;\n std::stringstream ss;\n while (re != 0) {\n int rem = re % -4;\n re /= -4;\n if (rem < 0) {\n rem = 4 + rem;\n re++;\n }\n ss << rem << 0;\n }\n if (im != 0) {\n double f = (std::complex(0.0, c.imag()) / std::complex(0.0, 2.0)).real();\n im = (int)ceil(f);\n f = -4.0 * (f - im);\n size_t index = 1;\n while (im != 0) {\n int rem = im % -4;\n im /= -4;\n if (rem < 0) {\n rem = 4 + rem;\n im++;\n }\n if (index < ss.str().length()) {\n ss.str()[index] = (char)(rem + 48);\n } else {\n ss << 0 << rem;\n }\n index += 2;\n }\n fi = (int)f;\n }\n\n auto r = ss.str();\n std::reverse(r.begin(), r.end());\n ss.str(\"\");\n ss.clear();\n ss << r;\n if (fi != -1) ss << '.' << fi;\n r = ss.str();\n r.erase(r.begin(), std::find_if(r.begin(), r.end(), [](char c) { return c != '0'; }));\n if (r[0] == '.')r = \"0\" + r;\n return QuaterImaginary(r);\n}\n\nint main() {\n using namespace std;\n\n for (int i = 1; i <= 16; i++) {\n complex c1(i, 0);\n QuaterImaginary qi = toQuaterImaginary(c1);\n complex c2 = qi.toComplex();\n cout << setw(8) << c1 << \" -> \" << setw(8) << qi << \" -> \" << setw(8) << c2 << \" \";\n c1 = -c1;\n qi = toQuaterImaginary(c1);\n c2 = qi.toComplex();\n cout << setw(8) << c1 << \" -> \" << setw(8) << qi << \" -> \" << setw(8) << c2 << endl;\n }\n cout << endl;\n\n for (int i = 1; i <= 16; i++) {\n complex c1(0, i);\n QuaterImaginary qi = toQuaterImaginary(c1);\n complex c2 = qi.toComplex();\n cout << setw(8) << c1 << \" -> \" << setw(8) << qi << \" -> \" << setw(8) << c2 << \" \";\n c1 = -c1;\n qi = toQuaterImaginary(c1);\n c2 = qi.toComplex();\n cout << setw(8) << c1 << \" -> \" << setw(8) << qi << \" -> \" << setw(8) << c2 << endl;\n }\n\n return 0;\n}"} {"title": "Increasing gaps between consecutive Niven numbers", "language": "C++", "task": "Note: '''Niven''' numbers are also called '''Harshad''' numbers.\n:::: They are also called '''multidigital''' numbers.\n\n\n'''Niven''' numbers are positive integers which are evenly divisible by the sum of its\ndigits (expressed in base ten).\n\n''Evenly divisible'' means ''divisible with no remainder''.\n\n\n;Task:\n:* find the gap (difference) of a Niven number from the previous Niven number\n:* if the gap is ''larger'' than the (highest) previous gap, then:\n:::* show the index (occurrence) of the gap (the 1st gap is '''1''')\n:::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''')\n:::* show the Niven number that starts the gap\n:::* show all numbers with comma separators where appropriate (optional)\n:::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864'''\n:* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number\n:* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer\n:* show all output here, on this page\n\n\n;Related task:\n:* Harshad or Niven series.\n\n\n;Also see:\n:* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers.\n:* (PDF) version of the (above) article by Doyon.\n\n", "solution": "#include \n#include \n#include \n\n// Returns the sum of the digits of n given the\n// sum of the digits of n - 1\nuint64_t digit_sum(uint64_t n, uint64_t sum) {\n ++sum;\n while (n > 0 && n % 10 == 0) {\n sum -= 9;\n n /= 10;\n }\n return sum;\n}\n\ninline bool divisible(uint64_t n, uint64_t d) {\n if ((d & 1) == 0 && (n & 1) == 1)\n return false;\n return n % d == 0;\n}\n\nint main() {\n // Print numbers with commas\n std::cout.imbue(std::locale(\"\"));\n\n uint64_t previous = 1, gap = 0, sum = 0;\n int niven_index = 0, gap_index = 1;\n\n std::cout << \"Gap index Gap Niven index Niven number\\n\";\n for (uint64_t niven = 1; gap_index <= 32; ++niven) {\n sum = digit_sum(niven, sum);\n if (divisible(niven, sum)) {\n if (niven > previous + gap) {\n gap = niven - previous;\n std::cout << std::setw(9) << gap_index++\n << std::setw(5) << gap\n << std::setw(15) << niven_index\n << std::setw(16) << previous << '\\n';\n }\n previous = niven;\n ++niven_index;\n }\n }\n return 0;\n}"} {"title": "Integer overflow", "language": "C++", "task": "Some languages support one or more integer types of the underlying processor.\n\nThis integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.\nThe integers supported by such a type can be ''signed'' or ''unsigned''.\n\nArithmetic for machine level integers can often be done by single CPU instructions.\nThis allows high performance and is the main reason to support machine level integers.\n\n\n;Definition:\nAn integer overflow happens when the result of a computation does not fit into the fixed size integer.\nThe result can be too small or too big to be representable in the fixed size integer.\n\n\n;Task:\nWhen a language has fixed size integer types, create a program that\ndoes arithmetic computations for the fixed size integers of the language.\n\nThese computations must be done such that the result would overflow.\n\nThe program should demonstrate what the following expressions do.\n\n\nFor 32-bit signed integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit signed integer\n|-\n| -(-2147483647-1)\n| 2147483648\n|-\n| 2000000000 + 2000000000\n| 4000000000\n|-\n| -2147483647 - 2147483647\n| -4294967294\n|-\n| 46341 * 46341\n| 2147488281\n|-\n| (-2147483647-1) / -1\n| 2147483648\n|}\n\nFor 64-bit signed integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit signed integer\n|-\n| -(-9223372036854775807-1)\n| 9223372036854775808\n|-\n| 5000000000000000000+5000000000000000000\n| 10000000000000000000\n|-\n| -9223372036854775807 - 9223372036854775807\n| -18446744073709551614\n|-\n| 3037000500 * 3037000500\n| 9223372037000250000\n|-\n| (-9223372036854775807-1) / -1\n| 9223372036854775808\n|}\n\nFor 32-bit unsigned integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit unsigned integer\n|-\n| -4294967295\n| -4294967295\n|-\n| 3000000000 + 3000000000\n| 6000000000\n|-\n| 2147483647 - 4294967295\n| -2147483648\n|-\n| 65537 * 65537\n| 4295098369\n|}\n\nFor 64-bit unsigned integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit unsigned integer\n|-\n| -18446744073709551615\n| -18446744073709551615\n|-\n| 10000000000000000000 + 10000000000000000000\n| 20000000000000000000\n|-\n| 9223372036854775807 - 18446744073709551615\n| -9223372036854775808\n|-\n| 4294967296 * 4294967296\n| 18446744073709551616\n|}\n\n\n;Notes:\n:* When the integer overflow does trigger an exception show how the exception is caught.\n:* When the integer overflow produces some value, print it.\n:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.\n:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.\n:* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.\n\n", "solution": "Same as C, except that if std::numeric_limits::is_modulo is true, then the type IntegerType uses modulo arithmetic (the behavior is defined), even if it is a signed type.\nA C++ program does not recognize a signed integer overflow and the program continues with wrong results.\n\n"} {"title": "Integer sequence", "language": "C++", "task": "Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.\n\nIf appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.\n\n", "solution": "// Using the proposed unbounded integer library\n\n#include \n#include \n\nint main()\n{\n try\n {\n auto i = std::experimental::seminumeric::integer{};\n \n while (true)\n std::cout << ++i << '\\n';\n }\n catch (...)\n {\n // Do nothing\n }\n}"} {"title": "Intersecting number wheels", "language": "C++ from D", "task": "A number wheel has:\n* A ''name'' which is an uppercase letter.\n* A set of ordered ''values'' which are either ''numbers'' or ''names''.\n\nA ''number'' is generated/yielded from a named wheel by:\n:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a \"wheel\":\n::1.a If the value is a number, yield it.\n::1.b If the value is a name, yield the next value from the named wheel\n::1.c Advance the position of this wheel.\n\nGiven the wheel\n: A: 1 2 3\nthe number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...\n\n'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the \nfirst named wheel is assumed to be the one that values are generated from.\n\n;Examples:\nGiven the wheels:\n A: 1 B 2\n B: 3 4\nThe series of numbers generated starts:\n 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...\n\nThe intersections of number wheels can be more complex, (and might loop forever),\nand wheels may be multiply connected. \n\n'''Note:''' If a named wheel is referenced more than \nonce by one or many other wheels, then there is only one position of the wheel \nthat is advanced by each and all references to it.\n\nE.g.\n A: 1 D D\n D: 6 7 8\n Generates:\n 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... \n\n;Task:\nGenerate and show the first twenty terms of the sequence of numbers generated \nfrom these groups:\n\n Intersecting Number Wheel group:\n A: 1 2 3\n \n Intersecting Number Wheel group:\n A: 1 B 2\n B: 3 4\n \n Intersecting Number Wheel group:\n A: 1 D D\n D: 6 7 8\n \n Intersecting Number Wheel group:\n A: 1 B C\n B: 3 4\n C: 5 B\n\nShow your output here, on this page.\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nstruct Wheel {\nprivate:\n std::vector values;\n size_t index;\n\npublic:\n Wheel() : index(0) {\n // empty\n }\n\n Wheel(std::initializer_list data) : values(data), index(0) {\n //values.assign(data);\n if (values.size() < 1) {\n throw new std::runtime_error(\"Not enough elements\");\n }\n }\n\n char front() {\n return values[index];\n }\n\n void popFront() {\n index = (index + 1) % values.size();\n }\n};\n\nstruct NamedWheel {\nprivate:\n std::map wheels;\n\npublic:\n void put(char c, Wheel w) {\n wheels[c] = w;\n }\n\n char front(char c) {\n char v = wheels[c].front();\n while ('A' <= v && v <= 'Z') {\n v = wheels[v].front();\n }\n return v;\n }\n\n void popFront(char c) {\n auto v = wheels[c].front();\n wheels[c].popFront();\n\n while ('A' <= v && v <= 'Z') {\n auto d = wheels[v].front();\n wheels[v].popFront();\n v = d;\n }\n }\n};\n\nvoid group1() {\n Wheel w({ '1', '2', '3' });\n for (size_t i = 0; i < 20; i++) {\n std::cout << ' ' << w.front();\n w.popFront();\n }\n std::cout << '\\n';\n}\n\nvoid group2() {\n Wheel a({ '1', 'B', '2' });\n Wheel b({ '3', '4' });\n\n NamedWheel n;\n n.put('A', a);\n n.put('B', b);\n\n for (size_t i = 0; i < 20; i++) {\n std::cout << ' ' << n.front('A');\n n.popFront('A');\n }\n std::cout << '\\n';\n}\n\nvoid group3() {\n Wheel a({ '1', 'D', 'D' });\n Wheel d({ '6', '7', '8' });\n\n NamedWheel n;\n n.put('A', a);\n n.put('D', d);\n\n for (size_t i = 0; i < 20; i++) {\n std::cout << ' ' << n.front('A');\n n.popFront('A');\n }\n std::cout << '\\n';\n}\n\nvoid group4() {\n Wheel a({ '1', 'B', 'C' });\n Wheel b({ '3', '4' });\n Wheel c({ '5', 'B' });\n\n NamedWheel n;\n n.put('A', a);\n n.put('B', b);\n n.put('C', c);\n\n for (size_t i = 0; i < 20; i++) {\n std::cout << ' ' << n.front('A');\n n.popFront('A');\n }\n std::cout << '\\n';\n}\n\nint main() {\n group1();\n group2();\n group3();\n group4();\n\n return 0;\n}"} {"title": "Inverted syntax", "language": "C++", "task": "'''Inverted syntax with conditional expressions'''\n\nIn traditional syntax conditional expressions are usually shown before the action within a statement or code block:\n\n IF raining=true THEN needumbrella=true \n\nIn inverted syntax, the action is listed before the conditional expression in the statement or code block:\n\n needumbrella=true IF raining=true \n\n'''Inverted syntax with assignment'''\n\nIn traditional syntax, assignments are usually expressed with the variable appearing before the expression:\n\n a = 6\n\nIn inverted syntax, the expression appears before the variable:\n 6 = a\n\n'''Task'''\n\nThe task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.\n", "solution": "class invertedAssign {\n int data;\npublic:\n invertedAssign(int data):data(data){}\n int getData(){return data;}\n void operator=(invertedAssign& other) const {\n other.data = this->data;\n }\n};\n\n\n#include \n\nint main(){\n invertedAssign a = 0;\n invertedAssign b = 42;\n std::cout << a.getData() << ' ' << b.getData() << '\\n';\n\n b = a;\n\n std::cout << a.getData() << ' ' << b.getData() << '\\n';\n}"} {"title": "Iterated digits squaring", "language": "C++", "task": "If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:\n15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89\n7 -> 49 -> 97 -> 130 -> 10 -> 1\n\nAn example in Python:\n\n>>> step = lambda x: sum(int(d) ** 2 for d in str(x))\n>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))\n>>> [iterate(x) for x in xrange(1, 20)]\n[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]\n\n\n;Task:\n: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.\nOr, for much less credit - (showing that your algorithm and/or language is slow):\n: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.\n\nThis problem derives from the Project Euler problem 92.\n\nFor a quick algorithm for this task see the talk page\n\n\n;Related tasks:\n* [[Combinations with repetitions]]\n* [[Digital root]]\n* [[Digital root/Multiplicative digital root]]\n\n", "solution": "#include \n\n// returns sum of squares of digits of n\nunsigned int sum_square_digits(unsigned int n) {\n int i,num=n,sum=0;\n // process digits one at a time until there are none left\n while (num > 0) {\n // peal off the last digit from the number\n int digit=num % 10;\n num=(num - digit)/10;\n // add it's square to the sum\n sum+=digit*digit;\n }\n return sum;\n}\nint main(void) {\n unsigned int i=0,result=0, count=0;\n for (i=1; i<=100000000; i++) {\n // if not 1 or 89, start the iteration\n if ((i != 1) || (i != 89)) {\n result = sum_square_digits(i);\n }\n // otherwise we're done already\n else {\n result = i;\n }\n // while we haven't reached 1 or 89, keep iterating\n while ((result != 1) && (result != 89)) {\n result = sum_square_digits(result);\n }\n if (result == 89) {\n count++;\n }\n }\n std::cout << count << std::endl;\n return 0;\n}\n"} {"title": "Jacobi symbol", "language": "C++", "task": "The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)\n* (a | p) 1 if a is a square (mod p)\n* (a | p) -1 if a is not a square (mod p)\n* (a | p) 0 if a 0 \n\nIf n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).\n\n;Task:\nCalculate the Jacobi symbol (a | n).\n\n;Reference:\n* Wikipedia article on Jacobi symbol.\n\n", "solution": "#include \n#include \n#include \n#include \n\nint jacobi(int n, int k) {\n assert(k > 0 && k % 2 == 1);\n n %= k;\n int t = 1;\n while (n != 0) {\n while (n % 2 == 0) {\n n /= 2;\n int r = k % 8;\n if (r == 3 || r == 5)\n t = -t;\n }\n std::swap(n, k);\n if (n % 4 == 3 && k % 4 == 3)\n t = -t;\n n %= k;\n }\n return k == 1 ? t : 0;\n}\n\nvoid print_table(std::ostream& out, int kmax, int nmax) {\n out << \"n\\\\k|\";\n for (int k = 0; k <= kmax; ++k)\n out << ' ' << std::setw(2) << k;\n out << \"\\n----\";\n for (int k = 0; k <= kmax; ++k)\n out << \"---\";\n out << '\\n';\n for (int n = 1; n <= nmax; n += 2) {\n out << std::setw(2) << n << \" |\";\n for (int k = 0; k <= kmax; ++k)\n out << ' ' << std::setw(2) << jacobi(k, n);\n out << '\\n';\n }\n}\n\nint main() {\n print_table(std::cout, 20, 21);\n return 0;\n}"} {"title": "Jaro similarity", "language": "C++ from C", "task": "The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match.\n\n\n;;Definition\n\nThe Jaro similarity d_j of two given strings s_1 and s_2 is\n\n: d_j = \\left\\{\n\n\\begin{array}{l l}\n 0 & \\text{if }m = 0\\\\\n \\frac{1}{3}\\left(\\frac{m}{|s_1|} + \\frac{m}{|s_2|} + \\frac{m-t}{m}\\right) & \\text{otherwise} \\end{array} \\right.\n\nWhere:\n\n* m is the number of ''matching characters'';\n* t is half the number of ''transpositions''.\n\n\nTwo characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \\left\\lfloor\\frac{\\max(|s_1|,|s_2|)}{2}\\right\\rfloor-1 characters.\n\nEach character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.\n\n\n;;Example\n\nGiven the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find:\n\n* m = 4\n* |s_1| = 6\n* |s_2| = 5\n* t = 0\n\n\nWe find a Jaro score of:\n\n: d_j = \\frac{1}{3}\\left(\\frac{4}{6} + \\frac{4}{5} + \\frac{4-0}{4}\\right) = 0.822\n\n\n;Task\n\nImplement the Jaro algorithm and show the similarity scores for each of the following pairs:\n\n* (\"MARTHA\", \"MARHTA\")\n* (\"DIXON\", \"DICKSONX\")\n* (\"JELLYFISH\", \"SMELLYFISH\")\n\n\n; See also\n* Jaro-Winkler distance on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n\ndouble jaro(const std::string s1, const std::string s2) {\n const uint l1 = s1.length(), l2 = s2.length();\n if (l1 == 0)\n return l2 == 0 ? 1.0 : 0.0;\n const uint match_distance = std::max(l1, l2) / 2 - 1;\n bool s1_matches[l1];\n bool s2_matches[l2];\n std::fill(s1_matches, s1_matches + l1, false);\n std::fill(s2_matches, s2_matches + l2, false);\n uint matches = 0;\n for (uint i = 0; i < l1; i++)\n {\n const int end = std::min(i + match_distance + 1, l2);\n for (int k = std::max(0u, i - match_distance); k < end; k++)\n if (!s2_matches[k] && s1[i] == s2[k])\n {\n s1_matches[i] = true;\n s2_matches[k] = true;\n matches++;\n break;\n }\n }\n if (matches == 0)\n return 0.0;\n double t = 0.0;\n uint k = 0;\n for (uint i = 0; i < l1; i++)\n if (s1_matches[i])\n {\n while (!s2_matches[k]) k++;\n if (s1[i] != s2[k]) t += 0.5;\n k++;\n }\n\n const double m = matches;\n return (m / l1 + m / l2 + (m - t) / m) / 3.0;\n}\n\nint main() {\n using namespace std;\n cout << jaro(\"MARTHA\", \"MARHTA\") << endl;\n cout << jaro(\"DIXON\", \"DICKSONX\") << endl;\n cout << jaro(\"JELLYFISH\", \"SMELLYFISH\") << endl;\n return 0;\n}"} {"title": "Jewels and stones", "language": "C++ from D", "task": "Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by this problem.\n\n\n\n", "solution": "#include \n#include \n\nint countJewels(const std::string& s, const std::string& j) {\n int count = 0;\n for (char c : s) {\n if (j.find(c) != std::string::npos) {\n count++;\n }\n }\n return count;\n}\n\nint main() {\n using namespace std;\n\n cout << countJewels(\"aAAbbbb\", \"aA\") << endl;\n cout << countJewels(\"ZZ\", \"z\") << endl;\n\n return 0;\n}"} {"title": "Julia set", "language": "C++", "task": "Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* Mandelbrot Set\n\n", "solution": "#include \n#include \n#include \n\nconst int BMP_SIZE = 600, ITERATIONS = 512;\nconst long double FCT = 2.85, hFCT = FCT / 2.0;\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n DWORD* bits() const { return ( DWORD* )pBits; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass julia {\npublic:\n void draw( std::complex k ) {\n bmp.create( BMP_SIZE, BMP_SIZE );\n DWORD* bits = bmp.bits();\n int res, pos;\n std::complex c, factor( FCT / BMP_SIZE, FCT / BMP_SIZE ) ;\n\n for( int y = 0; y < BMP_SIZE; y++ ) {\n pos = y * BMP_SIZE;\n\n c.imag( ( factor.imag() * y ) + -hFCT );\n\n for( int x = 0; x < BMP_SIZE; x++ ) {\n c.real( factor.real() * x + -hFCT );\n res = inSet( c, k );\n if( res ) {\n int n_res = res % 255;\n if( res < ( ITERATIONS >> 1 ) ) res = RGB( n_res << 2, n_res << 3, n_res << 4 );\n else res = RGB( n_res << 4, n_res << 2, n_res << 5 );\n }\n bits[pos++] = res;\n }\n }\n bmp.saveBitmap( \"./js.bmp\" );\n }\nprivate:\n int inSet( std::complex z, std::complex c ) {\n long double dist;//, three = 3.0;\n for( int ec = 0; ec < ITERATIONS; ec++ ) {\n z = z * z; z = z + c;\n dist = ( z.imag() * z.imag() ) + ( z.real() * z.real() );\n if( dist > 3 ) return( ec );\n }\n return 0;\n }\n myBitmap bmp;\n};\nint main( int argc, char* argv[] ) {\n std::complex c;\n long double factor = FCT / BMP_SIZE;\n c.imag( ( factor * 184 ) + -1.4 );\n c.real( ( factor * 307 ) + -2.0 );\n julia j; j.draw( c ); return 0; \n}\n"} {"title": "Jump anywhere", "language": "C++", "task": "Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.\n\nThis task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. \nFor the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. \nThis task provides a \"grab bag\" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!\n\n* Some languages can ''go to'' any global label in a program.\n* Some languages can break multiple function calls, also known as ''unwinding the call stack''.\n* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).\n\nThese jumps are not all alike. \nA simple ''goto'' never touches the call stack. \nA continuation saves the call stack, so you can continue a function call after it ends.\n\n\n;Task:\nUse your language to demonstrate the various types of jumps that it supports. \n\nBecause the possibilities vary by language, this task is not specific. \nYou have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\nint main(void) \n{\n cout << \"Find a solution to i = 2 * j - 7\\n\";\n pair answer;\n for(int i = 0; true; i++)\n {\n for(int j = 0; j < i; j++)\n {\n if( i == 2 * j - 7)\n {\n // use brute force and run until a solution is found\n answer = make_pair(i, j);\n goto loopexit;\n }\n }\n }\n \nloopexit:\n cout << answer.first << \" = 2 * \" << answer.second << \" - 7\\n\\n\"; \n \n // jumping out of nested loops is the main usage of goto in\n // C++. goto can be used in other places but there is usually\n // a better construct. goto is not allowed to jump across\n // initialized variables which limits where it can be used.\n // this is case where C++ is more restrictive than C.\n\n goto spagetti;\n \n int k;\n k = 9; // this is assignment, can be jumped over\n \n /* The line below won't compile because a goto is not allowed\n * to jump over an initialized value.\n int j = 9;\n */\n\nspagetti:\n \n cout << \"k = \" << k << \"\\n\"; // k was never initialized, accessing it is undefined behavior\n \n}"} {"title": "K-d tree", "language": "C++", "task": "{{wikipedia|K-d tree}}\n\nA k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). \nk-d trees are a special case of binary space partitioning trees.\n\nk-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. \nOtherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.\n\n'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets:\n\n# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)].\n# 1000 3-d points uniformly distributed in a 3-d cube.\n\nFor the Wikipedia example, find the nearest neighbor to point (9, 2)\nFor the random data, pick a random location and find the nearest neighbor.\n\nIn addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed.\n\nOutput should show the point searched for, the point found, \nthe distance to the point, and the number of nodes visited.\n\nThere are variant algorithms for constructing the tree. \nYou can use a simple median strategy or implement something more efficient. \nVariants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. \nYou do not have to implement these. \nThe requirement for this task is specifically the nearest single neighbor. \nAlso there are algorithms for inserting, deleting, and balancing k-d trees. \nThese are also not required for the task.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\n/**\n * Class for representing a point. coordinate_type must be a numeric type.\n */\ntemplate\nclass point {\npublic:\n point(std::array c) : coords_(c) {}\n point(std::initializer_list list) {\n size_t n = std::min(dimensions, list.size());\n std::copy_n(list.begin(), n, coords_.begin());\n }\n /**\n * Returns the coordinate in the given dimension.\n *\n * @param index dimension index (zero based)\n * @return coordinate in the given dimension\n */\n coordinate_type get(size_t index) const {\n return coords_[index];\n }\n /**\n * Returns the distance squared from this point to another\n * point.\n *\n * @param pt another point\n * @return distance squared from this point to the other point\n */\n double distance(const point& pt) const {\n double dist = 0;\n for (size_t i = 0; i < dimensions; ++i) {\n double d = get(i) - pt.get(i);\n dist += d * d;\n }\n return dist;\n }\nprivate:\n std::array coords_;\n};\n\ntemplate\nstd::ostream& operator<<(std::ostream& out, const point& pt) {\n out << '(';\n for (size_t i = 0; i < dimensions; ++i) {\n if (i > 0)\n out << \", \";\n out << pt.get(i);\n }\n out << ')';\n return out;\n}\n\n/**\n * C++ k-d tree implementation, based on the C version at rosettacode.org.\n */\ntemplate\nclass kdtree {\npublic:\n typedef point point_type;\nprivate:\n struct node {\n node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}\n coordinate_type get(size_t index) const {\n return point_.get(index);\n }\n double distance(const point_type& pt) const {\n return point_.distance(pt);\n }\n point_type point_;\n node* left_;\n node* right_;\n };\n node* root_ = nullptr;\n node* best_ = nullptr;\n double best_dist_ = 0;\n size_t visited_ = 0;\n std::vector nodes_;\n\n struct node_cmp {\n node_cmp(size_t index) : index_(index) {}\n bool operator()(const node& n1, const node& n2) const {\n return n1.point_.get(index_) < n2.point_.get(index_);\n }\n size_t index_;\n };\n\n node* make_tree(size_t begin, size_t end, size_t index) {\n if (end <= begin)\n return nullptr;\n size_t n = begin + (end - begin)/2;\n auto i = nodes_.begin();\n std::nth_element(i + begin, i + n, i + end, node_cmp(index));\n index = (index + 1) % dimensions;\n nodes_[n].left_ = make_tree(begin, n, index);\n nodes_[n].right_ = make_tree(n + 1, end, index);\n return &nodes_[n];\n }\n\n void nearest(node* root, const point_type& point, size_t index) {\n if (root == nullptr)\n return;\n ++visited_;\n double d = root->distance(point);\n if (best_ == nullptr || d < best_dist_) {\n best_dist_ = d;\n best_ = root;\n }\n if (best_dist_ == 0)\n return;\n double dx = root->get(index) - point.get(index);\n index = (index + 1) % dimensions;\n nearest(dx > 0 ? root->left_ : root->right_, point, index);\n if (dx * dx >= best_dist_)\n return;\n nearest(dx > 0 ? root->right_ : root->left_, point, index);\n }\npublic:\n kdtree(const kdtree&) = delete;\n kdtree& operator=(const kdtree&) = delete;\n /**\n * Constructor taking a pair of iterators. Adds each\n * point in the range [begin, end) to the tree.\n *\n * @param begin start of range\n * @param end end of range\n */\n template\n kdtree(iterator begin, iterator end) : nodes_(begin, end) {\n root_ = make_tree(0, nodes_.size(), 0);\n }\n \n /**\n * Constructor taking a function object that generates\n * points. The function object will be called n times\n * to populate the tree.\n *\n * @param f function that returns a point\n * @param n number of points to add\n */\n template\n kdtree(func&& f, size_t n) {\n nodes_.reserve(n);\n for (size_t i = 0; i < n; ++i)\n nodes_.push_back(f());\n root_ = make_tree(0, nodes_.size(), 0);\n }\n\n /**\n * Returns true if the tree is empty, false otherwise.\n */\n bool empty() const { return nodes_.empty(); }\n\n /**\n * Returns the number of nodes visited by the last call\n * to nearest().\n */\n size_t visited() const { return visited_; }\n\n /**\n * Returns the distance between the input point and return value\n * from the last call to nearest().\n */\n double distance() const { return std::sqrt(best_dist_); }\n\n /**\n * Finds the nearest point in the tree to the given point.\n * It is not valid to call this function if the tree is empty.\n *\n * @param pt a point\n * @return the nearest point in the tree to the given point\n */\n const point_type& nearest(const point_type& pt) {\n if (root_ == nullptr)\n throw std::logic_error(\"tree is empty\");\n best_ = nullptr;\n visited_ = 0;\n best_dist_ = 0;\n nearest(root_, pt, 0);\n return best_->point_;\n }\n};\n\nvoid test_wikipedia() {\n typedef point point2d;\n typedef kdtree tree2d;\n\n point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };\n\n tree2d tree(std::begin(points), std::end(points));\n point2d n = tree.nearest({ 9, 2 });\n\n std::cout << \"Wikipedia example data:\\n\";\n std::cout << \"nearest point: \" << n << '\\n';\n std::cout << \"distance: \" << tree.distance() << '\\n';\n std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\ntypedef point point3d;\ntypedef kdtree tree3d;\n\nstruct random_point_generator {\n random_point_generator(double min, double max)\n : engine_(std::random_device()()), distribution_(min, max) {}\n\n point3d operator()() {\n double x = distribution_(engine_);\n double y = distribution_(engine_);\n double z = distribution_(engine_);\n return point3d({x, y, z});\n }\n\n std::mt19937 engine_;\n std::uniform_real_distribution distribution_;\n};\n\nvoid test_random(size_t count) {\n random_point_generator rpg(0, 1);\n tree3d tree(rpg, count);\n point3d pt(rpg());\n point3d n = tree.nearest(pt);\n\n std::cout << \"Random data (\" << count << \" points):\\n\";\n std::cout << \"point: \" << pt << '\\n';\n std::cout << \"nearest point: \" << n << '\\n';\n std::cout << \"distance: \" << tree.distance() << '\\n';\n std::cout << \"nodes visited: \" << tree.visited() << '\\n';\n}\n\nint main() {\n try {\n test_wikipedia();\n std::cout << '\\n';\n test_random(1000);\n std::cout << '\\n';\n test_random(1000000);\n } catch (const std::exception& e) {\n std::cerr << e.what() << '\\n';\n }\n return 0;\n}"} {"title": "Kaprekar numbers", "language": "C++", "task": "A positive integer is a Kaprekar number if:\n* It is '''1''' (unity)\n* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. \nNote that a split resulting in a part consisting purely of 0s is not valid, \nas 0 is not considered positive.\n\n\n;Example Kaprekar numbers:\n* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.\n* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....\n\n\n;Example process:\n10000 (1002) splitting from left to right:\n* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.\n* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.\n\n\n;Task:\nGenerate and show all Kaprekar numbers less than 10,000. \n\n\n;Extra credit:\nOptionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.\n\n\n;Extra extra credit:\nThe concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); \nif you can, show that Kaprekar numbers exist in other bases too. \n\n\nFor this purpose, do the following:\n* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);\n* Display each of them in base 10 representation;\n* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. \n \nFor example, 225(10) is \"d4\" in base 17, its square \"a52g\", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g\n\n\n;Reference:\n* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version\n\n\n;Related task:\n* [[Casting out nines]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nlong string2long( const std::string & s ) {\n long result ;\n std::istringstream( s ) >> result ;\n return result ;\n}\n\nbool isKaprekar( long number ) {\n long long squarenumber = ((long long)number) * number ;\n std::ostringstream numberbuf ;\n numberbuf << squarenumber ;\n std::string numberstring = numberbuf.str( ) ;\n for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {\n std::string firstpart = numberstring.substr( 0 , i ) ,\n secondpart = numberstring.substr( i ) ;\n //we do not accept figures ending in a sequence of zeroes\n if ( secondpart.find_first_not_of( \"0\" ) == std::string::npos ) {\n\t return false ;\n }\n if ( string2long( firstpart ) + string2long( secondpart ) == number ) {\n\t return true ;\n }\n }\n return false ;\n}\n\nint main( ) {\n std::vector kaprekarnumbers ;\n kaprekarnumbers.push_back( 1 ) ;\n for ( int i = 2 ; i < 1000001 ; i++ ) {\n if ( isKaprekar( i ) ) \n\t kaprekarnumbers.push_back( i ) ;\n }\n std::vector::const_iterator svi = kaprekarnumbers.begin( ) ;\n std::cout << \"Kaprekar numbers up to 10000: \\n\" ;\n while ( *svi < 10000 ) {\n std::cout << *svi << \" \" ;\n svi++ ;\n }\n std::cout << '\\n' ;\n std::cout << \"All the Kaprekar numbers up to 1000000 :\\n\" ;\n std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,\n\t std::ostream_iterator( std::cout , \"\\n\" ) ) ;\n std::cout << \"There are \" << kaprekarnumbers.size( )\n << \" Kaprekar numbers less than one million!\\n\" ;\n return 0 ;\n}"} {"title": "Kernighans large earthquake problem", "language": "C++", "task": "Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.\n\n;Problem:\nYou are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.\n\nExample lines from the file would be lines like:\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n\n;Task:\n* Create a program or script invocation to find all the events with magnitude greater than 6\n* Assuming an appropriate name e.g. \"data.txt\" for the file:\n:# Either: Show how your program is invoked to process a data file of that name.\n:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).\n\n", "solution": "// Randizo was here!\n#include \n#include \n#include \nusing namespace std;\n\nint main()\n{\n ifstream file(\"../include/earthquake.txt\");\n\n int count_quake = 0;\n int column = 1;\n string value;\n double size_quake;\n string row = \"\";\n\n\n while(file >> value)\n {\n if(column == 3)\n {\n size_quake = stod(value);\n\n if(size_quake>6.0)\n {\n count_quake++;\n row += value + \"\\t\";\n cout << row << endl;\n }\n\n column = 1;\n row = \"\";\n }\n else\n {\n column++;\n row+=value + \"\\t\";\n }\n }\n\n cout << \"\\nNumber of quakes greater than 6 is \" << count_quake << endl;\n\n return 0;\n}"} {"title": "Keyboard input/Obtain a Y or N response", "language": "C++", "task": "Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. \n\nThe response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\nint main()\n{\n\tchar ch;\n\t_cputs( \"Yes or no?\" );\n\tdo\n\t{\n\t\tch = _getch();\n\t\tch = toupper( ch );\n\t} while(ch!='Y'&&ch!='N');\n\n\tif(ch=='N')\n\t{\n\t\tcout << \"You said no\" << endl;\n\t}\n\telse\n\t{\n\t\tcout << \"You said yes\" << endl;\n\t}\n\treturn 0;\n}\n"} {"title": "Knight's tour", "language": "C++11", "task": "Task\nProblem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be \"closed\"; that is, the knight need not end within a single move of its start position.\n\nInput and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntemplate\nclass Board \n{\npublic:\n array, 8> moves;\n array, N> data;\n\n Board() \n {\n moves[0] = make_pair(2, 1);\n moves[1] = make_pair(1, 2);\n moves[2] = make_pair(-1, 2);\n moves[3] = make_pair(-2, 1);\n moves[4] = make_pair(-2, -1);\n moves[5] = make_pair(-1, -2);\n moves[6] = make_pair(1, -2);\n moves[7] = make_pair(2, -1);\n }\n\n array sortMoves(int x, int y) const \n {\n array, 8> counts;\n for(int i = 0; i < 8; ++i) \n {\n int dx = get<0>(moves[i]);\n int dy = get<1>(moves[i]);\n\n int c = 0;\n for(int j = 0; j < 8; ++j) \n {\n int x2 = x + dx + get<0>(moves[j]);\n int y2 = y + dy + get<1>(moves[j]);\n\n if (x2 < 0 || x2 >= N || y2 < 0 || y2 >= N)\n continue;\n if(data[y2][x2] != 0)\n continue;\n\n c++;\n }\n\n counts[i] = make_tuple(c, i);\n }\n\n // Shuffle to randomly break ties\n random_shuffle(counts.begin(), counts.end());\n\n // Lexicographic sort\n sort(counts.begin(), counts.end());\n\n array out;\n for(int i = 0; i < 8; ++i)\n out[i] = get<1>(counts[i]);\n return out;\n }\n\n void solve(string start) \n {\n for(int v = 0; v < N; ++v)\n for(int u = 0; u < N; ++u)\n data[v][u] = 0;\n\n int x0 = start[0] - 'a';\n int y0 = N - (start[1] - '0');\n data[y0][x0] = 1;\n\n array>, N*N> order;\n order[0] = make_tuple(x0, y0, 0, sortMoves(x0, y0));\n\n int n = 0;\n while(n < N*N-1) \n {\n int x = get<0>(order[n]);\n int y = get<1>(order[n]);\n\n bool ok = false;\n for(int i = get<2>(order[n]); i < 8; ++i) \n {\n int dx = moves[get<3>(order[n])[i]].first;\n int dy = moves[get<3>(order[n])[i]].second;\n\n if(x+dx < 0 || x+dx >= N || y+dy < 0 || y+dy >= N)\n continue;\n if(data[y + dy][x + dx] != 0) \n continue;\n\n get<2>(order[n]) = i + 1;\n ++n;\n data[y+dy][x+dx] = n + 1;\n order[n] = make_tuple(x+dx, y+dy, 0, sortMoves(x+dx, y+dy));\n ok = true;\n break;\n }\n\n if(!ok) // Failed. Backtrack.\n {\n data[y][x] = 0;\n --n;\n }\n }\n }\n\n template\n friend ostream& operator<<(ostream &out, const Board &b);\n};\n\ntemplate\nostream& operator<<(ostream &out, const Board &b) \n{\n for (int v = 0; v < N; ++v) \n {\n for (int u = 0; u < N; ++u) \n {\n if (u != 0) out << \",\";\n out << setw(3) << b.data[v][u];\n }\n out << endl;\n }\n return out;\n}\n\nint main() \n{\n Board<5> b1;\n b1.solve(\"c3\");\n cout << b1 << endl;\n\n Board<8> b2;\n b2.solve(\"b5\");\n cout << b2 << endl;\n\n Board<31> b3; // Max size for <1000 squares\n b3.solve(\"a1\");\n cout << b3 << endl;\n return 0;\n}"} {"title": "Knuth's algorithm S", "language": "C++11", "task": "This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.\nThis means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change).\n\n\n;The algorithm:\n:* Select the first n items as the sample as they become available;\n:* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample.\n:* Repeat 2nd step for any subsequent items.\n\n\n;The Task:\n:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item.\n:* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S.\n:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:\n:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.\n:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9.\n\n\nNote: A class taking n and generating a callable instance/function might also be used.\n\n\n;Reference:\n* The Art of Computer Programming, Vol 2, 3.4.2 p.142\n\n\n;Related tasks: \n* [[One of n lines in a file]] \n* [[Accumulator factory]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ntemplate \nstd::function(T)> s_of_n_creator(int n) {\n std::vector sample;\n int i = 0;\n return [=](T item) mutable {\n i++;\n if (i <= n) {\n sample.push_back(item);\n } else if (std::rand() % i < n) {\n sample[std::rand() % n] = item;\n }\n return sample;\n };\n}\n\nint main() {\n std::srand(std::time(NULL));\n int bin[10] = {0};\n for (int trial = 0; trial < 100000; trial++) {\n auto s_of_n = s_of_n_creator(3);\n std::vector sample;\n for (int i = 0; i < 10; i++)\n sample = s_of_n(i);\n for (int s : sample)\n bin[s]++;\n }\n for (int x : bin)\n std::cout << x << std::endl;\n return 0;\n}"} {"title": "Koch curve", "language": "C++", "task": "Draw a Koch curve. See details: Koch curve\n\n", "solution": "// See https://en.wikipedia.org/wiki/Koch_snowflake\n#include \n#include \n#include \n\nconstexpr double sqrt3_2 = 0.86602540378444; // sqrt(3)/2\n\nstruct point {\n double x;\n double y;\n};\n\nstd::vector koch_next(const std::vector& points) {\n size_t size = points.size();\n std::vector output(4*(size - 1) + 1);\n double x0, y0, x1, y1;\n size_t j = 0;\n for (size_t i = 0; i + 1 < size; ++i) {\n x0 = points[i].x;\n y0 = points[i].y;\n x1 = points[i + 1].x;\n y1 = points[i + 1].y;\n double dy = y1 - y0;\n double dx = x1 - x0;\n output[j++] = {x0, y0};\n output[j++] = {x0 + dx/3, y0 + dy/3};\n output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};\n output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};\n }\n output[j] = {x1, y1};\n return output;\n}\n\nstd::vector koch_points(int size, int iterations) {\n double length = size * sqrt3_2 * 0.95;\n double x = (size - length)/2;\n double y = size/2 - length * sqrt3_2/3;\n std::vector points{\n {x, y},\n {x + length/2, y + length * sqrt3_2},\n {x + length, y},\n {x, y}\n };\n for (int i = 0; i < iterations; ++i)\n points = koch_next(points);\n return points;\n}\n\nvoid koch_curve_svg(std::ostream& out, int size, int iterations) {\n out << \"\\n\";\n out << \"\\n\";\n out << \"\\n\\n\";\n}\n\nint main() {\n std::ofstream out(\"koch_curve.svg\");\n if (!out) {\n std::cerr << \"Cannot open output file\\n\";\n return EXIT_FAILURE;\n }\n koch_curve_svg(out, 600, 5);\n return EXIT_SUCCESS;\n}"} {"title": "Kolakoski sequence", "language": "C++", "task": "The natural numbers, (excluding zero); with the property that:\n: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.\n\n;Example:\nThis is ''not'' a Kolakoski sequence:\n1,1,2,2,2,1,2,2,1,2,...\nIts sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:\n\n: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...\n\nThe above gives the RLE of:\n2, 3, 1, 2, 1, ...\n\nThe original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.\n\n;Creating a Kolakoski sequence:\n\nLets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....\n\n# We start the sequence s with the first item from the cycle c: 1\n# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. \nWe will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.\n\nWe started s with 1 and therefore s[k] states that it should appear only the 1 time.\n\nIncrement k\nGet the next item from c and append it to the end of sequence s. s will then become: 1, 2\nk was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2\nIncrement k\nAppend the next item from the cycle to the list: 1, 2,2, 1\nk is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1\nincrement k\n\n...\n\n'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.\n\n;Task:\n# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.\n# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.\n# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).\n# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 20 members of the sequence generated from (2, 1)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)\n# Check the sequence againt its RLE.\n(There are rules on generating Kolakoski sequences from this method that are broken by the last example)\n\n", "solution": "#include \n#include \n\nusing Sequence = std::vector;\n\nstd::ostream& operator<<(std::ostream& os, const Sequence& v) {\n os << \"[ \";\n for (const auto& e : v) {\n std::cout << e << \", \";\n }\n os << \"]\";\n return os;\n}\n\nint next_in_cycle(const Sequence& s, size_t i) {\n return s[i % s.size()];\n}\n\nSequence gen_kolakoski(const Sequence& s, int n) {\n Sequence seq;\n for (size_t i = 0; seq.size() < n; ++i) {\n const int next = next_in_cycle(s, i);\n Sequence nv(i >= seq.size() ? next : seq[i], next);\n seq.insert(std::end(seq), std::begin(nv), std::end(nv));\n }\n return { std::begin(seq), std::begin(seq) + n };\n}\n\nbool is_possible_kolakoski(const Sequence& s) {\n Sequence r;\n for (size_t i = 0; i < s.size();) {\n int count = 1;\n for (size_t j = i + 1; j < s.size(); ++j) {\n if (s[j] != s[i]) break;\n ++count;\n }\n r.push_back(count);\n i += count;\n }\n for (size_t i = 0; i < r.size(); ++i) if (r[i] != s[i]) return false;\n return true;\n}\n\nint main() {\n std::vector seqs = {\n { 1, 2 },\n { 2, 1 },\n { 1, 3, 1, 2 },\n { 1, 3, 2, 1 }\n };\n for (const auto& s : seqs) {\n auto kol = gen_kolakoski(s, s.size() > 2 ? 30 : 20);\n std::cout << \"Starting with: \" << s << \": \" << std::endl << \"Kolakoski sequence: \" \n << kol << std::endl << \"Possibly kolakoski? \" << is_possible_kolakoski(kol) << std::endl;\t\t\n }\n return 0;\n}"} {"title": "Kosaraju", "language": "C++ from D", "task": "{{wikipedia|Graph}}\n\n\nKosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.\n\nFor this task consider the directed graph with these connections:\n 0 -> 1\n 1 -> 2\n 2 -> 0\n 3 -> 1, 3 -> 2, 3 -> 4\n 4 -> 3, 4 -> 5\n 5 -> 2, 5 -> 6\n 6 -> 5\n 7 -> 4, 7 -> 6, 7 -> 7\n\nAnd report the kosaraju strongly connected component for each node.\n\n;References:\n* The article on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n#include \n\ntemplate\nstd::ostream& operator<<(std::ostream& os, const std::vector& v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << \"[\";\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n return os << \"]\";\n}\n\nstd::vector kosaraju(std::vector>& g) {\n // 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.\n auto size = g.size();\n std::vector vis(size); // all false by default\n std::vector l(size); // all zero by default\n auto x = size; // index for filling l in reverse order\n std::vector> t(size); // transpose graph\n\n // Recursive subroutine 'visit':\n std::function visit;\n visit = [&](int u) {\n if (!vis[u]) {\n vis[u] = true;\n for (auto v : g[u]) {\n visit(v);\n t[v].push_back(u); // construct transpose\n }\n l[--x] = u;\n }\n };\n\n // 2. For each vertex u of the graph do visit(u)\n for (int i = 0; i < g.size(); ++i) {\n visit(i);\n }\n std::vector c(size); // used for component assignment\n\n // Recursive subroutine 'assign':\n std::function assign;\n assign = [&](int u, int root) {\n if (vis[u]) { // repurpose vis to mean 'unassigned'\n vis[u] = false;\n c[u] = root;\n for (auto v : t[u]) {\n assign(v, root);\n }\n }\n };\n\n // 3: For each element u of l in order, do assign(u, u)\n for (auto u : l) {\n assign(u, u);\n }\n\n return c;\n}\n\nstd::vector> g = {\n {1},\n {2},\n {0},\n {1, 2, 4},\n {3, 5},\n {2, 6},\n {5},\n {4, 6, 7},\n};\n\nint main() {\n using namespace std;\n\n cout << kosaraju(g) << endl;\n\n return 0;\n}"} {"title": "Largest int from concatenated ints", "language": "C++", "task": "Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.\n\nUse the following two sets of integers as tests and show your program output here.\n\n:::::* {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* {54, 546, 548, 60}\n\n\n;Possible algorithms:\n# A solution could be found by trying all combinations and return the best. \n# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.\n# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.\n\n\n;See also:\n* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?\n* Constructing the largest number possible by rearranging a list\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::string findLargestConcat ( std::vector< int > & mynumbers ) {\n std::vector concatnumbers ;\n std::sort ( mynumbers.begin( ) , mynumbers.end( ) ) ;\n do {\n std::ostringstream numberstream ;\n for ( int i : mynumbers ) \n\t numberstream << i ;\n concatnumbers.push_back( numberstream.str( ) ) ;\n } while ( std::next_permutation( mynumbers.begin( ) ,\n\t mynumbers.end( ) )) ;\n return *( std::max_element( concatnumbers.begin( ) ,\n\t concatnumbers.end( ) ) ) ;\n}\n\nint main( ) {\n std::vector mynumbers = { 98, 76 , 45 , 34, 9 , 4 , 3 , 1 } ;\n std::vector othernumbers = { 54 , 546 , 548 , 60 } ;\n std::cout << \"The largest concatenated int is \" <<\n findLargestConcat( mynumbers ) << \" !\\n\" ;\n std::cout << \"And here it is \" << findLargestConcat( othernumbers ) \n << \" !\\n\" ;\n return 0 ;\n}"} {"title": "Largest number divisible by its digits", "language": "C++ from D", "task": "Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the\n(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.\n\n\nNote that the digit zero (0) can not be in the number as integer division by zero is undefined. \n\nThe digits must all be unique so a base ten number will have at most '''9''' digits.\n\nFeel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)\n\n\n;Stretch goal:\nDo the same thing for hexadecimal.\n\n\n;Related tasks:\n:* gapful numbers.\n:* palindromic gapful numbers. \n\n\n;Also see:\n:* The OEIS sequence: A115569: Lynch-Bell numbers. \n\n", "solution": "#include \n#include \n#include \n\nbool checkDec(int num) {\n std::set set;\n\n std::stringstream ss;\n ss << num;\n auto str = ss.str();\n\n for (int i = 0; i < str.size(); ++i) {\n char c = str[i];\n int d = c - '0';\n if (d == 0) return false;\n if (num % d != 0) return false;\n if (set.find(d) != set.end()) {\n return false;\n }\n set.insert(d);\n }\n\n return true;\n}\n\nint main() {\n for (int i = 98764321; i > 0; i--) {\n if (checkDec(i)) {\n std::cout << i << \"\\n\";\n break;\n }\n }\n\n return 0;\n}"} {"title": "Largest proper divisor of n", "language": "C++", "task": "a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.\n\n", "solution": "#include \n#include \n#include \n\nint largest_proper_divisor(int n) {\n assert(n > 0);\n if ((n & 1) == 0)\n return n >> 1;\n for (int p = 3; p * p <= n; p += 2) {\n if (n % p == 0)\n return n / p;\n }\n return 1;\n}\n\nint main() {\n for (int n = 1; n < 101; ++n) {\n std::cout << std::setw(2) << largest_proper_divisor(n)\n << (n % 10 == 0 ? '\\n' : ' ');\n }\n}"} {"title": "Last letter-first letter", "language": "C++", "task": "A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \"animals\" as the category,\n\nChild 1: dog \nChild 2: goldfish\nChild 1: hippopotamus\nChild 2: snake\n...\n\n\n\n;Task:\nTake the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. \n\nNo Pokemon name is to be repeated.\n\n\naudino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\ncresselia croagunk darmanitan deino emboar emolga exeggcute gabite\ngirafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\nkricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\nnosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\nsealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\ntyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\n\n\n\nExtra brownie points for dealing with the full list of 646 names.\n\n", "solution": "#include \n#include \n#include \n\nstruct last_letter_first_letter {\n size_t max_path_length = 0;\n size_t max_path_length_count = 0;\n std::vector max_path_example;\n\n void search(std::vector& names, size_t offset) {\n if (offset > max_path_length) {\n max_path_length = offset;\n max_path_length_count = 1;\n max_path_example.assign(names.begin(), names.begin() + offset);\n } else if (offset == max_path_length) {\n ++max_path_length_count;\n }\n char last_letter = names[offset - 1].back();\n for (size_t i = offset, n = names.size(); i < n; ++i) {\n if (names[i][0] == last_letter) {\n names[i].swap(names[offset]);\n search(names, offset + 1);\n names[i].swap(names[offset]);\n }\n }\n }\n\n void find_longest_chain(std::vector& names) {\n max_path_length = 0;\n max_path_length_count = 0;\n max_path_example.clear();\n for (size_t i = 0, n = names.size(); i < n; ++i) {\n names[i].swap(names[0]);\n search(names, 1);\n names[i].swap(names[0]);\n }\n }\n};\n\nint main() {\n std::vector names{\"audino\", \"bagon\", \"baltoy\", \"banette\",\n \"bidoof\", \"braviary\", \"bronzor\", \"carracosta\", \"charmeleon\",\n \"cresselia\", \"croagunk\", \"darmanitan\", \"deino\", \"emboar\",\n \"emolga\", \"exeggcute\", \"gabite\", \"girafarig\", \"gulpin\",\n \"haxorus\", \"heatmor\", \"heatran\", \"ivysaur\", \"jellicent\",\n \"jumpluff\", \"kangaskhan\", \"kricketune\", \"landorus\", \"ledyba\",\n \"loudred\", \"lumineon\", \"lunatone\", \"machamp\", \"magnezone\",\n \"mamoswine\", \"nosepass\", \"petilil\", \"pidgeotto\", \"pikachu\",\n \"pinsir\", \"poliwrath\", \"poochyena\", \"porygon2\", \"porygonz\",\n \"registeel\", \"relicanth\", \"remoraid\", \"rufflet\", \"sableye\",\n \"scolipede\", \"scrafty\", \"seaking\", \"sealeo\", \"silcoon\",\n \"simisear\", \"snivy\", \"snorlax\", \"spoink\", \"starly\", \"tirtouga\",\n \"trapinch\", \"treecko\", \"tyrogue\", \"vigoroth\", \"vulpix\",\n \"wailord\", \"wartortle\", \"whismur\", \"wingull\", \"yamask\"};\n last_letter_first_letter solver;\n solver.find_longest_chain(names);\n std::cout << \"Maximum path length: \" << solver.max_path_length << '\\n';\n std::cout << \"Paths of that length: \" << solver.max_path_length_count << '\\n';\n std::cout << \"Example path of that length:\\n \";\n for (size_t i = 0, n = solver.max_path_example.size(); i < n; ++i) {\n if (i > 0 && i % 7 == 0)\n std::cout << \"\\n \";\n else if (i > 0)\n std::cout << ' ';\n std::cout << solver.max_path_example[i];\n }\n std::cout << '\\n';\n}"} {"title": "Latin Squares in reduced form", "language": "C++ from C#", "task": "A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.\n\nFor a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.\n\nDemonstrate by:\n* displaying the four reduced Latin Squares of order 4.\n* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ntypedef std::vector> matrix;\n\nmatrix dList(int n, int start) {\n start--; // use 0 basing\n\n std::vector a(n);\n std::iota(a.begin(), a.end(), 0);\n a[start] = a[0];\n a[0] = start;\n std::sort(a.begin() + 1, a.end());\n auto first = a[1];\n // recursive closure permutes a[1:]\n matrix r;\n std::function recurse;\n recurse = [&](int last) {\n if (last == first) {\n // bottom of recursion you get here once for each permutation.\n // test if permutation is deranged.\n for (size_t j = 1; j < a.size(); j++) {\n auto v = a[j];\n if (j == v) {\n return; //no, ignore it\n }\n }\n // yes, save a copy with 1 based indexing\n std::vector b;\n std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });\n r.push_back(b);\n return;\n }\n for (int i = last; i >= 1; i--) {\n std::swap(a[i], a[last]);\n recurse(last - 1);\n std::swap(a[i], a[last]);\n }\n };\n recurse(n - 1);\n return r;\n}\n\nvoid printSquare(const matrix &latin, int n) {\n for (auto &row : latin) {\n auto it = row.cbegin();\n auto end = row.cend();\n std::cout << '[';\n if (it != end) {\n std::cout << *it;\n it = std::next(it);\n }\n while (it != end) {\n std::cout << \", \" << *it;\n it = std::next(it);\n }\n std::cout << \"]\\n\";\n }\n std::cout << '\\n';\n}\n\nunsigned long reducedLatinSquares(int n, bool echo) {\n if (n <= 0) {\n if (echo) {\n std::cout << \"[]\\n\";\n }\n return 0;\n } else if (n == 1) {\n if (echo) {\n std::cout << \"[1]\\n\";\n }\n return 1;\n }\n\n matrix rlatin;\n for (int i = 0; i < n; i++) {\n rlatin.push_back({});\n for (int j = 0; j < n; j++) {\n rlatin[i].push_back(j);\n }\n }\n // first row\n for (int j = 0; j < n; j++) {\n rlatin[0][j] = j + 1;\n }\n\n unsigned long count = 0;\n std::function recurse;\n recurse = [&](int i) {\n auto rows = dList(n, i);\n\n for (size_t r = 0; r < rows.size(); r++) {\n rlatin[i - 1] = rows[r];\n for (int k = 0; k < i - 1; k++) {\n for (int j = 1; j < n; j++) {\n if (rlatin[k][j] == rlatin[i - 1][j]) {\n if (r < rows.size() - 1) {\n goto outer;\n }\n if (i > 2) {\n return;\n }\n }\n }\n }\n if (i < n) {\n recurse(i + 1);\n } else {\n count++;\n if (echo) {\n printSquare(rlatin, n);\n }\n }\n outer: {}\n }\n };\n\n //remaining rows\n recurse(2);\n return count;\n}\n\nunsigned long factorial(unsigned long n) {\n if (n <= 0) return 1;\n unsigned long prod = 1;\n for (unsigned long i = 2; i <= n; i++) {\n prod *= i;\n }\n return prod;\n}\n\nint main() {\n std::cout << \"The four reduced lating squares of order 4 are:\\n\";\n reducedLatinSquares(4, true);\n\n std::cout << \"The size of the set of reduced latin squares for the following orders\\n\";\n std::cout << \"and hence the total number of latin squares of these orders are:\\n\\n\";\n for (int n = 1; n < 7; n++) {\n auto size = reducedLatinSquares(n, false);\n auto f = factorial(n - 1);\n f *= f * n * size;\n std::cout << \"Order \" << n << \": Size \" << size << \" x \" << n << \"! x \" << (n - 1) << \"! => Total \" << f << '\\n';\n }\n\n return 0;\n}"} {"title": "Law of cosines - triples", "language": "C++", "task": "The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:\n A2 + B2 - 2ABcos(g) = C2 \n\n;Specific angles:\nFor an angle of of '''90o''' this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of '''60o''' this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of '''120o''' this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* Restrain all sides to the integers '''1..13''' inclusive.\n* Show how many results there are for each of the three angles mentioned above.\n* Display results on this page.\n\n\nNote: Triangles with the same length sides but different order are to be treated as the same. \n\n;Optional Extra credit:\n* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.\n\n\n;Related Task\n* [[Pythagorean triples]]\n\n\n;See also:\n* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing triple = std::tuple;\n\nvoid print_triple(std::ostream& out, const triple& t) {\n out << '(' << std::get<0>(t) << ',' << std::get<1>(t) << ',' << std::get<2>(t) << ')';\n}\n\nvoid print_vector(std::ostream& out, const std::vector& vec) {\n if (vec.empty())\n return;\n auto i = vec.begin();\n print_triple(out, *i++);\n for (; i != vec.end(); ++i) {\n out << ' ';\n print_triple(out, *i);\n }\n out << \"\\n\\n\";\n}\n\nint isqrt(int n) {\n return static_cast(std::sqrt(n));\n}\n\nint main() {\n const int min = 1, max = 13;\n std::vector solutions90, solutions60, solutions120;\n\n for (int a = min; a <= max; ++a) {\n int a2 = a * a;\n for (int b = a; b <= max; ++b) {\n int b2 = b * b, ab = a * b;\n int c2 = a2 + b2;\n int c = isqrt(c2);\n if (c <= max && c * c == c2)\n solutions90.emplace_back(a, b, c);\n else {\n c2 = a2 + b2 - ab;\n c = isqrt(c2);\n if (c <= max && c * c == c2)\n solutions60.emplace_back(a, b, c);\n else {\n c2 = a2 + b2 + ab;\n c = isqrt(c2);\n if (c <= max && c * c == c2)\n solutions120.emplace_back(a, b, c);\n }\n }\n }\n }\n\n std::cout << \"There are \" << solutions60.size() << \" solutions for gamma = 60 degrees:\\n\";\n print_vector(std::cout, solutions60);\n\n std::cout << \"There are \" << solutions90.size() << \" solutions for gamma = 90 degrees:\\n\";\n print_vector(std::cout, solutions90);\n\n std::cout << \"There are \" << solutions120.size() << \" solutions for gamma = 120 degrees:\\n\";\n print_vector(std::cout, solutions120);\n \n const int max2 = 10000;\n int count = 0;\n for (int a = min; a <= max2; ++a) {\n for (int b = a + 1; b <= max2; ++b) {\n int c2 = a * a + b * b - a * b;\n int c = isqrt(c2);\n if (c <= max2 && c * c == c2)\n ++count;\n }\n }\n std::cout << \"There are \" << count << \" solutions for gamma = 60 degrees in the range \"\n << min << \" to \" << max2 << \" where the sides are not all of the same length.\\n\";\n return 0;\n}"} {"title": "Least common multiple", "language": "C++11", "task": "Compute the least common multiple (LCM) of two integers.\n\nGiven ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. \n\n\n;Example:\nThe least common multiple of '''12''' and '''18''' is '''36''', because:\n:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and \n:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and \n:* there is no positive integer less than '''36''' that has both factors. \n\n\nAs a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.\n\nIf you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.\n\n\n;Related task\n:* greatest common divisor.\n\n\n;See also:\n* MathWorld entry: Least Common Multiple.\n* Wikipedia entry: Least common multiple.\n\n", "solution": "#include \n#include \n#include \n \nint gcd(int a, int b) {\n a = abs(a);\n b = abs(b);\n while (b != 0) {\n std::tie(a, b) = std::make_tuple(b, a % b);\n }\n return a;\n}\n \nint lcm(int a, int b) {\n int c = gcd(a, b);\n return c == 0 ? 0 : a / c * b;\n}\n \nint main() {\n std::cout << \"The least common multiple of 12 and 18 is \" << lcm(12, 18) << \",\\n\"\n << \"and their greatest common divisor is \" << gcd(12, 18) << \"!\" \n << std::endl;\n return 0;\n}\n"} {"title": "Left factorials", "language": "C++", "task": "'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; \nthe same notation can be confusingly seen being used for the two different definitions.\n\nSometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: \n:::::::* !''n''` \n:::::::* !''n'' \n:::::::* ''n''! \n\n\n(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)\n\n\nThis Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':\n\n::::: !n = \\sum_{k=0}^{n-1} k! \n\n:::: where\n\n::::: !0 = 0\n\n\n\n;Task\nDisplay the left factorials for:\n* zero through ten (inclusive)\n* 20 through 110 (inclusive) by tens\n\n\nDisplay the length (in decimal digits) of the left factorials for:\n* 1,000 through 10,000 (inclusive), by thousands.\n\n\n;Also see:\n* The OEIS entry: A003422 left factorials\n* The MathWorld entry: left factorial\n* The MathWorld entry: factorial sums\n* The MathWorld entry: subfactorial\n\n\n;Related task:\n* permutations/derangements (subfactorials)\n\n", "solution": "#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\n#if 1 // optimized for 64-bit architecture\ntypedef unsigned long usingle;\ntypedef unsigned long long udouble;\nconst int word_len = 32;\n#else // optimized for 32-bit architecture\ntypedef unsigned short usingle;\ntypedef unsigned long udouble;\nconst int word_len = 16;\n#endif\n\nclass bignum {\nprivate:\n // rep_.size() == 0 if and only if the value is zero.\n // Otherwise, the word rep_[0] keeps the least significant bits.\n vector rep_;\npublic:\n explicit bignum(usingle n = 0) { if (n > 0) rep_.push_back(n); }\n bool equals(usingle n) const {\n if (n == 0) return rep_.empty();\n if (rep_.size() > 1) return false;\n return rep_[0] == n;\n }\n bignum add(usingle addend) const {\n bignum result(0);\n udouble sum = addend;\n for (size_t i = 0; i < rep_.size(); ++i) {\n sum += rep_[i];\n result.rep_.push_back(sum & (((udouble)1 << word_len) - 1));\n sum >>= word_len;\n }\n if (sum > 0) result.rep_.push_back((usingle)sum);\n return result;\n }\n bignum add(const bignum& addend) const {\n bignum result(0);\n udouble sum = 0;\n size_t sz1 = rep_.size();\n size_t sz2 = addend.rep_.size();\n for (size_t i = 0; i < max(sz1, sz2); ++i) {\n if (i < sz1) sum += rep_[i];\n if (i < sz2) sum += addend.rep_[i];\n result.rep_.push_back(sum & (((udouble)1 << word_len) - 1));\n sum >>= word_len;\n }\n if (sum > 0) result.rep_.push_back((usingle)sum);\n return result;\n }\n bignum multiply(usingle factor) const {\n bignum result(0);\n udouble product = 0;\n for (size_t i = 0; i < rep_.size(); ++i) {\n product += (udouble)rep_[i] * factor;\n result.rep_.push_back(product & (((udouble)1 << word_len) - 1));\n product >>= word_len;\n }\n if (product > 0)\n result.rep_.push_back((usingle)product);\n return result;\n }\n void divide(usingle divisor, bignum& quotient, usingle& remainder) const {\n quotient.rep_.resize(0);\n udouble dividend = 0;\n remainder = 0;\n for (size_t i = rep_.size(); i > 0; --i) {\n dividend = ((udouble)remainder << word_len) + rep_[i - 1];\n usingle quo = (usingle)(dividend / divisor);\n remainder = (usingle)(dividend % divisor);\n if (quo > 0 || i < rep_.size())\n quotient.rep_.push_back(quo);\n }\n reverse(quotient.rep_.begin(), quotient.rep_.end());\n }\n};\n\nostream& operator<<(ostream& os, const bignum& x);\n\nostream& operator<<(ostream& os, const bignum& x) {\n string rep;\n bignum dividend = x;\n bignum quotient;\n usingle remainder;\n while (true) {\n dividend.divide(10, quotient, remainder);\n rep += (char)('0' + remainder);\n if (quotient.equals(0)) break;\n dividend = quotient;\n }\n reverse(rep.begin(), rep.end());\n os << rep;\n return os;\n}\n\nbignum lfact(usingle n);\n\nbignum lfact(usingle n) {\n bignum result(0);\n bignum f(1);\n for (usingle k = 1; k <= n; ++k) {\n result = result.add(f);\n f = f.multiply(k);\n }\n return result;\n}\n\nint main() {\n for (usingle i = 0; i <= 10; ++i) {\n cout << \"!\" << i << \" = \" << lfact(i) << endl;\n }\n\n for (usingle i = 20; i <= 110; i += 10) {\n cout << \"!\" << i << \" = \" << lfact(i) << endl;\n }\n\n for (usingle i = 1000; i <= 10000; i += 1000) {\n stringstream ss;\n ss << lfact(i);\n cout << \"!\" << i << \" has \" << ss.str().size()\n << \" digits.\" << endl;\n }\n}\n"} {"title": "Levenshtein distance", "language": "C++", "task": "{{Wikipedia}}\n\nIn information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \n\n\n;Example:\nThe Levenshtein distance between \"'''kitten'''\" and \"'''sitting'''\" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "#include \n#include \nusing namespace std;\n\n// Compute Levenshtein Distance\n// Martin Ettl, 2012-10-05\n\nsize_t uiLevenshteinDistance(const string &s1, const string &s2)\n{\n const size_t\n m(s1.size()),\n n(s2.size());\n\n if( m==0 ) return n;\n if( n==0 ) return m;\n\n // allocation below is not ISO-compliant,\n // it won't work with -pedantic-errors.\n size_t costs[n + 1];\n\n for( size_t k=0; k<=n; k++ ) costs[k] = k;\n\n size_t i { 0 };\n for (char const &c1 : s1) \n {\n costs[0] = i+1;\n size_t corner { i },\n j { 0 };\n for (char const &c2 : s2)\n {\n size_t upper { costs[j+1] };\n if( c1 == c2 ) costs[j+1] = corner;\n else {\n size_t t(upper\n#include \n\nstd::vector TREE_LIST;\nstd::vector OFFSET;\n\nvoid init() {\n for (size_t i = 0; i < 32; i++) {\n if (i == 1) {\n OFFSET.push_back(1);\n } else {\n OFFSET.push_back(0);\n }\n }\n}\n\nvoid append(long t) {\n TREE_LIST.push_back(1 | (t << 1));\n}\n\nvoid show(long t, int l) {\n while (l-- > 0) {\n if (t % 2 == 1) {\n std::cout << '(';\n } else {\n std::cout << ')';\n }\n t = t >> 1;\n }\n}\n\nvoid listTrees(int n) {\n for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {\n show(TREE_LIST[i], 2 * n);\n std::cout << '\\n';\n }\n}\n\nvoid assemble(int n, long t, int sl, int pos, int rem) {\n if (rem == 0) {\n append(t);\n return;\n }\n\n auto pp = pos;\n auto ss = sl;\n\n if (sl > rem) {\n ss = rem;\n pp = OFFSET[ss];\n } else if (pp >= OFFSET[ss + 1]) {\n ss--;\n if (ss == 0) {\n return;\n }\n pp = OFFSET[ss];\n }\n\n assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);\n assemble(n, t, ss, pp + 1, rem);\n}\n\nvoid makeTrees(int n) {\n if (OFFSET[n + 1] != 0) {\n return;\n }\n if (n > 0) {\n makeTrees(n - 1);\n }\n assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);\n OFFSET[n + 1] = TREE_LIST.size();\n}\n\nvoid test(int n) {\n if (n < 1 || n > 12) {\n throw std::runtime_error(\"Argument must be between 1 and 12\");\n }\n\n append(0);\n\n makeTrees(n);\n std::cout << \"Number of \" << n << \"-trees: \" << OFFSET[n + 1] - OFFSET[n] << '\\n';\n listTrees(n);\n}\n\nint main() {\n init();\n test(5);\n\n return 0;\n}"} {"title": "Long year", "language": "C++", "task": "Most years have 52 weeks, some have 53, according to ISO8601.\n\n\n;Task:\nWrite a function which determines if a given year is long (53 weeks) or not, and demonstrate it.\n\n", "solution": "// Reference:\n// https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year\n\n#include \n\ninline int p(int year) {\n return (year + (year/4) - (year/100) + (year/400)) % 7;\n}\n\nbool is_long_year(int year) {\n return p(year) == 4 || p(year - 1) == 3;\n}\n\nvoid print_long_years(int from, int to) {\n for (int year = from, count = 0; year <= to; ++year) {\n if (is_long_year(year)) {\n if (count > 0)\n std::cout << ((count % 10 == 0) ? '\\n' : ' ');\n std::cout << year;\n ++count;\n }\n }\n}\n\nint main() {\n std::cout << \"Long years between 1800 and 2100:\\n\";\n print_long_years(1800, 2100);\n std::cout << '\\n';\n return 0;\n}"} {"title": "Longest common subsequence", "language": "C++", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.\n\nA chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].\n\nEvery Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.\n\nAccording to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.\n\n'''Background'''\n\nWhere the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.\n\nThe divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.\n\nA binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "#include \n#include \n#include // for shared_ptr<>\n#include \n#include \n#include //[C++11]\n#include // for lower_bound()\n#include // for next() and prev()\n\nusing namespace std;\n\nclass LCS {\nprotected:\n // Instances of the Pair linked list class are used to recover the LCS:\n class Pair {\n public:\n uint32_t index1;\n uint32_t index2;\n shared_ptr next;\n\n Pair(uint32_t index1, uint32_t index2, shared_ptr next = nullptr)\n : index1(index1), index2(index2), next(next) {\n }\n\n static shared_ptr Reverse(const shared_ptr pairs) {\n shared_ptr head = nullptr;\n for (auto next = pairs; next != nullptr; next = next->next)\n head = make_shared(next->index1, next->index2, head);\n return head;\n }\n };\n\n typedef deque> PAIRS;\n typedef deque INDEXES;\n typedef unordered_map CHAR_TO_INDEXES_MAP;\n typedef deque MATCHES;\n\n static uint32_t FindLCS(\n MATCHES& indexesOf2MatchedByIndex1, shared_ptr* pairs) {\n auto traceLCS = pairs != nullptr;\n PAIRS chains;\n INDEXES prefixEnd;\n\n //\n //[Assert]After each index1 iteration prefixEnd[index3] is the least index2\n // such that the LCS of s1[0:index1] and s2[0:index2] has length index3 + 1\n //\n uint32_t index1 = 0;\n for (const auto& it1 : indexesOf2MatchedByIndex1) {\n auto dq2 = *it1;\n auto limit = prefixEnd.end();\n for (auto it2 = dq2.rbegin(); it2 != dq2.rend(); it2++) {\n // Each index1, index2 pair corresponds to a match\n auto index2 = *it2;\n\n //\n // Note: The reverse iterator it2 visits index2 values in descending order,\n // allowing in-place update of prefixEnd[]. std::lower_bound() is used to\n // perform a binary search.\n //\n limit = lower_bound(prefixEnd.begin(), limit, index2);\n\n //\n // Look ahead to the next index2 value to optimize Pairs used by the Hunt\n // and Szymanski algorithm. If the next index2 is also an improvement on\n // the value currently held in prefixEnd[index3], a new Pair will only be\n // superseded on the next index2 iteration.\n //\n // Verify that a next index2 value exists; and that this value is greater\n // than the final index2 value of the LCS prefix at prev(limit):\n //\n auto preferNextIndex2 = next(it2) != dq2.rend() &&\n (limit == prefixEnd.begin() || *prev(limit) < *next(it2));\n\n //\n // Depending on match redundancy, this optimization may reduce the number\n // of Pair allocations by factors ranging from 2 up to 10 or more.\n //\n if (preferNextIndex2) continue;\n\n auto index3 = distance(prefixEnd.begin(), limit);\n\n if (limit == prefixEnd.end()) {\n // Insert Case\n prefixEnd.push_back(index2);\n // Refresh limit iterator:\n limit = prev(prefixEnd.end());\n if (traceLCS) {\n chains.push_back(pushPair(chains, index3, index1, index2));\n }\n }\n else if (index2 < *limit) {\n // Update Case\n // Update limit value:\n *limit = index2;\n if (traceLCS) {\n chains[index3] = pushPair(chains, index3, index1, index2);\n }\n }\n } // next index2\n\n index1++;\n } // next index1\n\n if (traceLCS) {\n // Return the LCS as a linked list of matched index pairs:\n auto last = chains.empty() ? nullptr : chains.back();\n // Reverse longest chain\n *pairs = Pair::Reverse(last);\n }\n\n auto length = prefixEnd.size();\n return length;\n }\n\nprivate:\n static shared_ptr pushPair(\n PAIRS& chains, const ptrdiff_t& index3, uint32_t& index1, uint32_t& index2) {\n auto prefix = index3 > 0 ? chains[index3 - 1] : nullptr;\n return make_shared(index1, index2, prefix);\n }\n\nprotected:\n //\n // Match() avoids m*n comparisons by using CHAR_TO_INDEXES_MAP to\n // achieve O(m+n) performance, where m and n are the input lengths.\n //\n // The lookup time can be assumed constant in the case of characters.\n // The symbol space is larger in the case of records; but the lookup\n // time will be O(log(m+n)), at most.\n //\n static void Match(\n CHAR_TO_INDEXES_MAP& indexesOf2MatchedByChar, MATCHES& indexesOf2MatchedByIndex1,\n const string& s1, const string& s2) {\n uint32_t index = 0;\n for (const auto& it : s2)\n indexesOf2MatchedByChar[it].push_back(index++);\n\n for (const auto& it : s1) {\n auto& dq2 = indexesOf2MatchedByChar[it];\n indexesOf2MatchedByIndex1.push_back(&dq2);\n }\n }\n\n static string Select(shared_ptr pairs, uint32_t length,\n bool right, const string& s1, const string& s2) {\n string buffer;\n buffer.reserve(length);\n for (auto next = pairs; next != nullptr; next = next->next) {\n auto c = right ? s2[next->index2] : s1[next->index1];\n buffer.push_back(c);\n }\n return buffer;\n }\n\npublic:\n static string Correspondence(const string& s1, const string& s2) {\n CHAR_TO_INDEXES_MAP indexesOf2MatchedByChar;\n MATCHES indexesOf2MatchedByIndex1; // holds references into indexesOf2MatchedByChar\n Match(indexesOf2MatchedByChar, indexesOf2MatchedByIndex1, s1, s2);\n shared_ptr pairs; // obtain the LCS as index pairs\n auto length = FindLCS(indexesOf2MatchedByIndex1, &pairs);\n return Select(pairs, length, false, s1, s2);\n }\n};"} {"title": "Longest common substring", "language": "C++14", "task": "Write a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*Generalize Suffix Tree\n*[[Ukkonen's Suffix Tree Construction]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nauto collectSubStrings( const std::string& s, int maxSubLength )\n{\n int l = s.length();\n auto res = std::set();\n for ( int start = 0; start < l; start++ )\n {\n int m = std::min( maxSubLength, l - start + 1 );\n for ( int length = 1; length < m; length++ )\n {\n res.insert( s.substr( start, length ) );\n }\n }\n return res;\n}\n\nstd::string lcs( const std::string& s0, const std::string& s1 )\n{\n // collect substring set\n auto maxSubLength = std::min( s0.length(), s1.length() );\n auto set0 = collectSubStrings( s0, maxSubLength );\n auto set1 = collectSubStrings( s1, maxSubLength );\n\n // get commons into a vector\n auto common = std::vector();\n std::set_intersection( set0.begin(), set0.end(), set1.begin(), set1.end(),\n std::back_inserter( common ) );\n\n // get the longest one\n std::nth_element( common.begin(), common.begin(), common.end(),\n []( const std::string& s1, const std::string& s2 ) {\n return s1.length() > s2.length();\n } );\n return *common.begin();\n}\n\nint main( int argc, char* argv[] )\n{\n auto s1 = std::string( \"thisisatest\" );\n auto s2 = std::string( \"testing123testing\" );\n std::cout << \"The longest common substring of \" << s1 << \" and \" << s2\n << \" is:\\n\";\n std::cout << \"\\\"\" << lcs( s1, s2 ) << \"\\\" !\\n\";\n return 0;\n}"} {"title": "Longest increasing subsequence", "language": "C++", "task": "Calculate and show here a longest increasing subsequence of the list:\n:\\{3, 2, 6, 4, 5, 1\\}\nAnd of the list:\n:\\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\\}\n\nNote that a list may have more than one subsequence that is of the maximum length.\n\n\n\n;Ref:\n# Dynamic Programming #1: Longest Increasing Subsequence on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "#include \n#include \n#include \n#include \n\ntemplate \nstruct Node {\n T value;\n Node* prev_node;\n};\n\ntemplate \nbool compare (const T& node1, const T& node2)\n{\n return node1->value < node2->value;\n}\n\ntemplate \nContainer lis(const Container& values) {\n typedef typename Container::value_type E;\n typedef typename Container::const_iterator ValueConstIter;\n typedef typename Container::iterator ValueIter;\n typedef Node* NodePtr;\n typedef const NodePtr ConstNodePtr;\n typedef std::vector > NodeVector;\n typedef std::vector NodePtrVector;\n typedef typename NodeVector::iterator NodeVectorIter;\n typedef typename NodePtrVector::iterator NodePtrVectorIter;\n\n std::vector pileTops;\n std::vector > nodes(values.size());\n\n // sort into piles\n NodeVectorIter cur_node = nodes.begin();\n for (ValueConstIter cur_value = values.begin(); cur_value != values.end(); ++cur_value, ++cur_node)\n {\n NodePtr node = &*cur_node;\n node->value = *cur_value;\n\n // lower_bound returns the first element that is not less than 'node->value'\n NodePtrVectorIter lb = std::lower_bound(pileTops.begin(), pileTops.end(), node, compare);\n\n if (lb != pileTops.begin())\n node->prev_node = *(lb - 1);\n\n if (lb == pileTops.end())\n pileTops.push_back(node);\n else\n *lb = node;\n }\n\n // extract LIS from piles\n // note that LIS length is equal to the number of piles\n Container result(pileTops.size());\n std::reverse_iterator r = std::reverse_iterator(result.rbegin());\n\n for (NodePtr node = pileTops.back(); node; node = node->prev_node, ++r)\n *r = node->value;\n\n return result;\n}\n\ntemplate \nvoid show_lis(const Container& values)\n{\n const Container& result = lis(values);\n for (typename Container::const_iterator it = result.begin(); it != result.end(); ++it) {\n std::cout << *it << ' ';\n }\n std::cout << std::endl;\n}\n\nint main()\n{\n const int arr1[] = { 3, 2, 6, 4, 5, 1 };\n const int arr2[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };\n\n std::vector vec1(arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]));\n std::vector vec2(arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]));\n\n show_lis(vec1);\n show_lis(vec2);\n}"} {"title": "Lucky and even lucky numbers", "language": "C++ from Go", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n +-------------------+----------------------------------------------------+\n | j | Jth lucky number |\n | j , lucky | Jth lucky number |\n | j , evenLucky | Jth even lucky number |\n | | |\n | j k | Jth through Kth (inclusive) lucky numbers |\n | j k lucky | Jth through Kth (inclusive) lucky numbers |\n | j k evenLucky | Jth through Kth (inclusive) even lucky numbers |\n | | |\n | j -k | all lucky numbers in the range j --> |k| |\n | j -k lucky | all lucky numbers in the range j --> |k| |\n | j -k evenLucky | all even lucky numbers in the range j --> |k| |\n +-------------------+----------------------------------------------------+\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki Lucky numbers.\n* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.\n* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.\n* Entry lucky numbers on The Eric Weisstein's World of Mathematics.\n", "solution": "#include \n#include \n#include \n#include \n\nconst int luckySize = 60000;\nstd::vector luckyEven(luckySize);\nstd::vector luckyOdd(luckySize);\n\nvoid init() {\n for (int i = 0; i < luckySize; ++i) {\n luckyEven[i] = i * 2 + 2;\n luckyOdd[i] = i * 2 + 1;\n }\n}\n\nvoid filterLuckyEven() {\n for (size_t n = 2; n < luckyEven.size(); ++n) {\n int m = luckyEven[n - 1];\n int end = (luckyEven.size() / m) * m - 1;\n for (int j = end; j >= m - 1; j -= m) {\n std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);\n luckyEven.pop_back();\n }\n }\n}\n\nvoid filterLuckyOdd() {\n for (size_t n = 2; n < luckyOdd.size(); ++n) {\n int m = luckyOdd[n - 1];\n int end = (luckyOdd.size() / m) * m - 1;\n for (int j = end; j >= m - 1; j -= m) {\n std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);\n luckyOdd.pop_back();\n }\n }\n}\n\nvoid printBetween(size_t j, size_t k, bool even) {\n std::ostream_iterator out_it{ std::cout, \", \" };\n\n if (even) {\n size_t max = luckyEven.back();\n if (j > max || k > max) {\n std::cerr << \"At least one are is too big\\n\";\n exit(EXIT_FAILURE);\n }\n\n std::cout << \"Lucky even numbers between \" << j << \" and \" << k << \" are: \";\n std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {\n return j <= n && n <= k;\n });\n } else {\n size_t max = luckyOdd.back();\n if (j > max || k > max) {\n std::cerr << \"At least one are is too big\\n\";\n exit(EXIT_FAILURE);\n }\n\n std::cout << \"Lucky numbers between \" << j << \" and \" << k << \" are: \";\n std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {\n return j <= n && n <= k;\n });\n }\n std::cout << '\\n';\n}\n\nvoid printRange(size_t j, size_t k, bool even) {\n std::ostream_iterator out_it{ std::cout, \", \" };\n if (even) {\n if (k >= luckyEven.size()) {\n std::cerr << \"The argument is too large\\n\";\n exit(EXIT_FAILURE);\n }\n std::cout << \"Lucky even numbers \" << j << \" to \" << k << \" are: \";\n std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);\n } else {\n if (k >= luckyOdd.size()) {\n std::cerr << \"The argument is too large\\n\";\n exit(EXIT_FAILURE);\n }\n std::cout << \"Lucky numbers \" << j << \" to \" << k << \" are: \";\n std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);\n }\n}\n\nvoid printSingle(size_t j, bool even) {\n if (even) {\n if (j >= luckyEven.size()) {\n std::cerr << \"The argument is too large\\n\";\n exit(EXIT_FAILURE);\n }\n std::cout << \"Lucky even number \" << j << \"=\" << luckyEven[j - 1] << '\\n';\n } else {\n if (j >= luckyOdd.size()) {\n std::cerr << \"The argument is too large\\n\";\n exit(EXIT_FAILURE);\n }\n std::cout << \"Lucky number \" << j << \"=\" << luckyOdd[j - 1] << '\\n';\n }\n}\n\nvoid help() {\n std::cout << \"./lucky j [k] [--lucky|--evenLucky]\\n\";\n std::cout << \"\\n\";\n std::cout << \" argument(s) | what is displayed\\n\";\n std::cout << \"==============================================\\n\";\n std::cout << \"-j=m | mth lucky number\\n\";\n std::cout << \"-j=m --lucky | mth lucky number\\n\";\n std::cout << \"-j=m --evenLucky | mth even lucky number\\n\";\n std::cout << \"-j=m -k=n | mth through nth (inclusive) lucky numbers\\n\";\n std::cout << \"-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\\n\";\n std::cout << \"-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\\n\";\n std::cout << \"-j=m -k=-n | all lucky numbers in the range [m, n]\\n\";\n std::cout << \"-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\\n\";\n std::cout << \"-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\\n\";\n}\n\nint main(int argc, char **argv) {\n bool evenLucky = false;\n int j = 0;\n int k = 0;\n\n // skip arg 0, because that is just the executable name\n if (argc < 2) {\n help();\n exit(EXIT_FAILURE);\n }\n\n bool good = false;\n for (int i = 1; i < argc; ++i) {\n if ('-' == argv[i][0]) {\n if ('-' == argv[i][1]) {\n // long args\n if (0 == strcmp(\"--lucky\", argv[i])) {\n evenLucky = false;\n } else if (0 == strcmp(\"--evenLucky\", argv[i])) {\n evenLucky = true;\n } else {\n std::cerr << \"Unknown long argument: [\" << argv[i] << \"]\\n\";\n exit(EXIT_FAILURE);\n }\n } else {\n // short args\n if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {\n good = true;\n j = atoi(&argv[i][3]);\n } else if ('k' == argv[i][1] && '=' == argv[i][2]) {\n k = atoi(&argv[i][3]);\n } else {\n std::cerr << \"Unknown short argument: \" << argv[i] << '\\n';\n exit(EXIT_FAILURE);\n }\n }\n } else {\n std::cerr << \"Unknown argument: \" << argv[i] << '\\n';\n exit(EXIT_FAILURE);\n }\n }\n if (!good) {\n help();\n exit(EXIT_FAILURE);\n }\n\n init();\n filterLuckyEven();\n filterLuckyOdd();\n if (k > 0) {\n printRange(j, k, evenLucky);\n } else if (k < 0) {\n printBetween(j, -k, evenLucky);\n } else {\n printSingle(j, evenLucky);\n }\n\n return 0;\n}"} {"title": "Mad Libs", "language": "C++", "task": "{{wikipedia}}\n\n\nMad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. \n\n\n;Task;\nWrite a program to create a Mad Libs like story. \n\nThe program should read an arbitrary multiline story from input.\n\nThe story will be terminated with a blank line. \n\nThen, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.\n\nStop when there are none left and print the final story.\n\n\nThe input should be an arbitrary story in the form:\n\n went for a walk in the park. \nfound a . decided to take it home.\n\nGiven this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).\n\n\n\n", "solution": "#include \n#include \nusing namespace std;\n\nint main()\n{\n string story, input;\n\n //Loop\n while(true)\n {\n //Get a line from the user\n getline(cin, input);\n\n //If it's blank, break this loop\n if(input == \"\\r\")\n break;\n\n //Add the line to the story\n story += input;\n }\n\n //While there is a '<' in the story\n int begin;\n while((begin = story.find(\"<\")) != string::npos)\n {\n //Get the category from between '<' and '>'\n int end = story.find(\">\");\n string cat = story.substr(begin + 1, end - begin - 1);\n\n //Ask the user for a replacement\n cout << \"Give me a \" << cat << \": \";\n cin >> input;\n\n //While there's a matching category \n //in the story\n while((begin = story.find(\"<\" + cat + \">\")) != string::npos)\n {\n //Replace it with the user's replacement\n story.replace(begin, cat.length()+2, input);\n }\n }\n\n //Output the final story\n cout << endl << story;\n\n return 0;\n}"} {"title": "Magic 8-ball", "language": "C++", "task": "Create Magic 8-Ball. \n\n\nSee details at: Magic 8-Ball.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nint main()\n{\n constexpr std::array answers = {\n \"It is certain.\",\n \"It is decidedly so.\",\n \"Without a doubt.\",\n \"Yes - definitely.\",\n \"You may rely on it.\",\n \"As I see it, yes.\",\n \"Most likely.\",\n \"Outlook good.\",\n \"Yes.\",\n \"Signs point to yes.\",\n \"Reply hazy, try again.\",\n \"Ask again later.\",\n \"Better not tell you now.\",\n \"Cannot predict now.\",\n \"Concentrate and ask again.\",\n \"Don't count on it.\",\n \"My reply is no.\",\n \"My sources say no.\",\n \"Outlook not so good.\",\n \"Very doubtful.\"\n };\n\n std::string input;\n std::srand(std::time(nullptr));\n while (true) {\n std::cout << \"\\n? : \";\n std::getline(std::cin, input);\n\n if (input.empty()) {\n break;\n }\n\n std::cout << answers[std::rand() % answers.size()] << '\\n';\n }\n}"} {"title": "Magic squares of doubly even order", "language": "C++", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). \n\nThis means that the subsquares also have an even size, which plays a role in the construction.\n\n \n{| class=\"wikitable\" style=\"float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%\"\n|-\n|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''\n|-\n|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''\n|-\n|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''\n|-\n|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''\n|-\n|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''\n|-\n|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''\n|-\n|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''\n|-\n|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''\n|}\n\n;Task\nCreate a magic square of '''8 x 8'''.\n\n\n;Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n\n\n;See also:\n* Doubly Even Magic Squares (1728.org)\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nclass magicSqr\n{\npublic: \n magicSqr( int d ) {\n while( d % 4 > 0 ) { d++; }\n sz = d;\n sqr = new int[sz * sz];\n fillSqr();\n }\n ~magicSqr() { delete [] sqr; }\n\n void display() const {\n cout << \"Doubly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n ostringstream cvr; cvr << sz * sz;\n int l = cvr.str().size();\n \n for( int y = 0; y < sz; y++ ) {\n int yy = y * sz;\n for( int x = 0; x < sz; x++ ) {\n cout << setw( l + 2 ) << sqr[yy + x];\n }\n cout << \"\\n\";\n }\n cout << \"\\n\\n\";\n }\nprivate:\n void fillSqr() {\n static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };\n int i = 0;\n for( int curRow = 0; curRow < sz; curRow++ ) {\n for( int curCol = 0; curCol < sz; curCol++ ) {\n sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;\n i++;\n }\n }\n }\n int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n int* sqr;\n int sz;\n};\n \nint main( int argc, char* argv[] ) {\n magicSqr s( 8 );\n s.display();\n return 0;\n}"} {"title": "Magic squares of odd order", "language": "C++", "task": "A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| class=\"wikitable\" style=\"float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "#include \n#include \n#include \n#include \n#include \nusing namespace std;\n \nclass MagicSquare\n{\npublic: \n MagicSquare(int d) : sqr(d*d,0), sz(d)\n {\n assert(d&1);\n fillSqr();\n }\n \n void display()\n {\n cout << \"Odd Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n ostringstream cvr;\n cvr << sz * sz;\n int l = cvr.str().size();\n \n\tfor( int y = 0; y < sz; y++ )\n\t{\n\t int yy = y * sz;\n\t for( int x = 0; x < sz; x++ )\n\t\tcout << setw( l + 2 ) << sqr[yy + x];\n\t cout << \"\\n\";\n\t}\n cout << \"\\n\\n\";\n }\n \nprivate:\n void fillSqr()\n {\n\tint sx = sz / 2, sy = 0, c = 0;\n\twhile( c < sz * sz )\n\t{\n\t if( !sqr[sx + sy * sz] )\n\t {\n\t\tsqr[sx + sy * sz]= c + 1;\n\t\tinc( sx ); dec( sy ); \n\t\tc++;\n\t }\n\t else\n\t {\n\t\tdec( sx ); inc( sy ); inc( sy );\n\t }\n\t}\n }\n \n int magicNumber()\n { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n void inc( int& a )\n { if( ++a == sz ) a = 0; }\n \n void dec( int& a )\n { if( --a < 0 ) a = sz - 1; }\n \n bool checkPos( int x, int y )\n { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n bool isInside( int s )\n { return ( s < sz && s > -1 ); }\n \n vector sqr;\n int sz;\n};\n \nint main()\n{\n MagicSquare s(7);\n s.display();\n return 0;\n}\n"} {"title": "Magic squares of singly even order", "language": "C++", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.\n\n;Task\nCreate a magic square of 6 x 6.\n\n\n; Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of doubly even order]]\n\n; See also\n* Singly Even Magic Squares (1728.org)\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n \nclass magicSqr\n{\npublic: \n magicSqr() { sqr = 0; }\n ~magicSqr() { if( sqr ) delete [] sqr; }\n \n void create( int d ) {\n if( sqr ) delete [] sqr;\n if( d & 1 ) d++;\n while( d % 4 == 0 ) { d += 2; }\n sz = d;\n sqr = new int[sz * sz];\n memset( sqr, 0, sz * sz * sizeof( int ) );\n fillSqr();\n }\n void display() {\n cout << \"Singly Even Magic Square: \" << sz << \" x \" << sz << \"\\n\";\n cout << \"It's Magic Sum is: \" << magicNumber() << \"\\n\\n\";\n ostringstream cvr; cvr << sz * sz;\n int l = cvr.str().size();\n \n for( int y = 0; y < sz; y++ ) {\n int yy = y * sz;\n for( int x = 0; x < sz; x++ ) {\n cout << setw( l + 2 ) << sqr[yy + x];\n }\n cout << \"\\n\";\n }\n cout << \"\\n\\n\";\n }\nprivate:\n void siamese( int from, int to ) {\n int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;\n\n while( count > 0 ) {\n bool done = false;\n while ( false == done ) {\n if( curCol >= oneSide ) curCol = 0;\n if( curRow < 0 ) curRow = oneSide - 1;\n done = true;\n if( sqr[curCol + sz * curRow] != 0 ) {\n curCol -= 1; curRow += 2;\n if( curCol < 0 ) curCol = oneSide - 1;\n if( curRow >= oneSide ) curRow -= oneSide;\n\n done = false;\n }\n }\n sqr[curCol + sz * curRow] = s;\n s++; count--; curCol++; curRow--;\n }\n }\n void fillSqr() {\n int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;\n\n siamese( 0, n );\n\n for( int r = 0; r < n; r++ ) {\n int row = r * sz;\n for( int c = n; c < sz; c++ ) {\n int m = sqr[c - n + row];\n \n sqr[c + row] = m + add1;\n sqr[c + row + ns] = m + add3;\n sqr[c - n + row + ns] = m + add2;\n }\n }\n\n int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); \n for( int r = 0; r < n; r++ ) {\n int row = r * sz; \n for( int c = co; c < sz; c++ ) { \n sqr[c + row] -= add3;\n sqr[c + row + ns] += add3;\n }\n }\n for( int r = 0; r < n; r++ ) {\n int row = r * sz; \n for( int c = 0; c < lc; c++ ) {\n int cc = c;\n if( r == lc ) cc++;\n sqr[cc + row] += add2;\n sqr[cc + row + ns] -= add2;\n }\n }\n }\n int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }\n \n void inc( int& a ) { if( ++a == sz ) a = 0; }\n \n void dec( int& a ) { if( --a < 0 ) a = sz - 1; }\n \n bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }\n \n bool isInside( int s ) { return ( s < sz && s > -1 ); }\n \n int* sqr;\n int sz;\n};\nint main( int argc, char* argv[] ) {\n magicSqr s; s.create( 6 );\n s.display();\n return 0;\n}\n"} {"title": "Map range", "language": "C++", "task": "Given two ranges: \n:::* [a_1,a_2] and \n:::* [b_1,b_2]; \n:::* then a value s in range [a_1,a_2]\n:::* is linearly mapped to a value t in range [b_1,b_2]\n where: \n\n\n:::* t = b_1 + {(s - a_1)(b_2 - b_1) \\over (a_2 - a_1)}\n\n\n;Task:\nWrite a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. \n\nUse this function to map values from the range [0, 10] to the range [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "#include \n#include \n\ntemplate\ntVal map_value(std::pair a, std::pair b, tVal inVal)\n{\n tVal inValNorm = inVal - a.first;\n tVal aUpperNorm = a.second - a.first;\n tVal normPosition = inValNorm / aUpperNorm;\n\n tVal bUpperNorm = b.second - b.first;\n tVal bValNorm = normPosition * bUpperNorm;\n tVal outVal = b.first + bValNorm;\n\n return outVal;\n}\n\nint main()\n{\n std::pair a(0,10), b(-1,0);\n\n for(float value = 0.0; 10.0 >= value; ++value)\n std::cout << \"map_value(\" << value << \") = \" << map_value(a, b, value) << std::endl;\n\n return 0;\n}"} {"title": "Maximum triangle path sum", "language": "C++ from Ada", "task": "Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "/* Algorithm complexity: n*log(n) */\n#include \n\nint main( int argc, char* argv[] )\n{\n int triangle[] = \n {\n\t55,\n\t94, 48,\n\t95, 30, 96,\n\t77, 71, 26, 67,\n\t97, 13, 76, 38, 45,\n\t7, 36, 79, 16, 37, 68,\n\t48, 7, 9, 18, 70, 26, 6,\n\t18, 72, 79, 46, 59, 79, 29, 90,\n\t20, 76, 87, 11, 32, 7, 7, 49, 18,\n\t27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n\t14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n\t2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n\t92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n\t56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n\t44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n\t85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n\t6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n\t27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n };\n\n const int size = sizeof( triangle ) / sizeof( int );\n const int tn = static_cast(sqrt(2.0 * size));\n assert(tn * (tn + 1) == 2 * size); // size should be a triangular number\n\n // walk backward by rows, replacing each element with max attainable therefrom\n for (int n = tn - 1; n > 0; --n) // n is size of row, note we do not process last row\n for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) // from the start to the end of row\n triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);\n\n std::cout << \"Maximum total: \" << triangle[0] << \"\\n\\n\";\n}\n"} {"title": "Mian-Chowla sequence", "language": "C++ from Go", "task": "The Mian-Chowla sequence is an integer sequence defined recursively.\n\n\nMian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "using namespace std;\n\n#include \n#include \n\n#define n 100\n#define nn ((n * (n + 1)) >> 1)\n\nbool Contains(int lst[], int item, int size) {\n\tfor (int i = 0; i < size; i++) if (item == lst[i]) return true;\n\treturn false;\n}\n\nint * MianChowla()\n{\n\tstatic int mc[n]; mc[0] = 1;\n\tint sums[nn];\tsums[0] = 2;\n\tint sum, le, ss = 1;\n\tfor (int i = 1; i < n; i++) {\n\t\tle = ss;\n\t\tfor (int j = mc[i - 1] + 1; ; j++) {\n\t\t\tmc[i] = j;\n\t\t\tfor (int k = 0; k <= i; k++) {\n\t\t\t\tsum = mc[k] + j;\n\t\t\t\tif (Contains(sums, sum, ss)) {\n\t\t\t\t\tss = le; goto nxtJ;\n\t\t\t\t}\n\t\t\t\tsums[ss++] = sum;\n\t\t\t}\n\t\t\tbreak;\n\t\tnxtJ:;\n\t\t}\n\t}\n\treturn mc;\n}\n\nint main() {\n\tclock_t st = clock(); int * mc; mc = MianChowla();\n\tdouble et = ((double)(clock() - st)) / CLOCKS_PER_SEC;\n\tcout << \"The first 30 terms of the Mian-Chowla sequence are:\\n\";\n\tfor (int i = 0; i < 30; i++) { cout << mc[i] << ' '; }\n\tcout << \"\\n\\nTerms 91 to 100 of the Mian-Chowla sequence are:\\n\";\n\tfor (int i = 90; i < 100; i++) { cout << mc[i] << ' '; }\n\tcout << \"\\n\\nComputation time was \" << et << \" seconds.\";\n}"} {"title": "Middle three digits", "language": "C++", "task": "Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "#include \n\nstd::string middleThreeDigits(int n)\n{\n auto number = std::to_string(std::abs(n));\n auto length = number.size();\n\n if (length < 3) {\n return \"less than three digits\";\n } else if (length % 2 == 0) {\n return \"even number of digits\";\n } else {\n return number.substr(length / 2 - 1, 3);\n }\n}\n\nint main()\n{\n auto values {123, 12345, 1234567, 987654321, 10001,\n -10001, -123, -100, 100, -12345,\n 1, 2, -1, -10, 2002, -2002, 0};\n\n for (auto&& v : values) {\n std::cout << \"middleThreeDigits(\" << v << \"): \" <<\n middleThreeDigits(v) << \"\\n\";\n }\n}\n"} {"title": "Minimum multiple of m where digital sum equals m", "language": "C++", "task": "Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''.\n\n\n;Task\n\n* Find the first 40 elements of the sequence.\n\n\n\n;Stretch\n\n* Find the next 30 elements of the sequence.\n\n\n;See also\n\n;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n\n\n\n\n\n", "solution": "#include \n#include \n\nint digit_sum(int n) {\n int sum = 0;\n for (; n > 0; n /= 10)\n sum += n % 10;\n return sum;\n}\n\nint main() {\n for (int n = 1; n <= 70; ++n) {\n for (int m = 1;; ++m) {\n if (digit_sum(m * n) == n) {\n std::cout << std::setw(8) << m << (n % 10 == 0 ? '\\n' : ' ');\n break;\n }\n }\n }\n}"} {"title": "Minimum positive multiple in base 10 using only 0 and 1", "language": "C++ from C", "task": "Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.\n\nThis is simple to do, but can be challenging to do efficiently.\n\nTo avoid repeating long, unwieldy phrases, the operation \"minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1\" will hereafter be referred to as \"'''B10'''\".\n\n;Task:\n\nWrite a routine to find the B10 of a given integer. \n\nE.G. \n \n '''n''' '''B10''' '''n''' x '''multiplier'''\n 1 1 ( 1 x 1 )\n 2 10 ( 2 x 5 )\n 7 1001 ( 7 x 143 )\n 9 111111111 ( 9 x 12345679 )\n 10 10 ( 10 x 1 )\n\nand so on.\n\nUse the routine to find and display here, on this page, the '''B10''' value for: \n\n 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999\n\nOptionally find '''B10''' for:\n\n 1998, 2079, 2251, 2277\n\nStretch goal; find '''B10''' for:\n\n 2439, 2997, 4878\n\nThere are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.\n\n\n;See also:\n\n:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.\n:* How to find Minimum Positive Multiple in base 10 using only 0 and 1\n\n", "solution": "#include \n#include \n\n__int128 imax(__int128 a, __int128 b) {\n if (a > b) {\n return a;\n }\n return b;\n}\n\n__int128 ipow(__int128 b, __int128 n) {\n if (n == 0) {\n return 1;\n }\n if (n == 1) {\n return b;\n }\n\n __int128 res = b;\n while (n > 1) {\n res *= b;\n n--;\n }\n return res;\n}\n\n__int128 imod(__int128 m, __int128 n) {\n __int128 result = m % n;\n if (result < 0) {\n result += n;\n }\n return result;\n}\n\nbool valid(__int128 n) {\n if (n < 0) {\n return false;\n }\n while (n > 0) {\n int r = n % 10;\n if (r > 1) {\n return false;\n }\n n /= 10;\n }\n return true;\n}\n\n__int128 mpm(const __int128 n) {\n if (n == 1) {\n return 1;\n }\n\n std::vector<__int128> L(n * n, 0);\n L[0] = 1;\n L[1] = 1;\n\n __int128 m, k, r, j;\n m = 0;\n while (true) {\n m++;\n if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {\n break;\n }\n L[m * n + 0] = 1;\n for (k = 1; k < n; k++) {\n L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);\n }\n }\n\n r = ipow(10, m);\n k = imod(-r, n);\n\n for (j = m - 1; j >= 1; j--) {\n if (L[(j - 1) * n + k] == 0) {\n r = r + ipow(10, j);\n k = imod(k - ipow(10, j), n);\n }\n }\n\n if (k == 1) {\n r++;\n }\n return r / n;\n}\n\nstd::ostream& operator<<(std::ostream& os, __int128 n) {\n char buffer[64]; // more then is needed, but is nice and round;\n int pos = (sizeof(buffer) / sizeof(char)) - 1;\n bool negative = false;\n\n if (n < 0) {\n negative = true;\n n = -n;\n }\n\n buffer[pos] = 0;\n while (n > 0) {\n int rem = n % 10;\n buffer[--pos] = rem + '0';\n n /= 10;\n }\n if (negative) {\n buffer[--pos] = '-';\n }\n return os << &buffer[pos];\n}\n\nvoid test(__int128 n) {\n __int128 mult = mpm(n);\n if (mult > 0) {\n std::cout << n << \" * \" << mult << \" = \" << (n * mult) << '\\n';\n } else {\n std::cout << n << \"(no solution)\\n\";\n }\n}\n\nint main() {\n int i;\n\n // 1-10 (inclusive)\n for (i = 1; i <= 10; i++) {\n test(i);\n }\n // 95-105 (inclusive)\n for (i = 95; i <= 105; i++) {\n test(i);\n }\n test(297);\n test(576);\n test(594); // needs a larger number type (64 bits signed)\n test(891);\n test(909);\n test(999); // needs a larger number type (87 bits signed)\n\n // optional\n test(1998);\n test(2079);\n test(2251);\n test(2277);\n\n // stretch\n test(2439);\n test(2997);\n test(4878);\n\n return 0;\n}"} {"title": "Modular arithmetic", "language": "C++ from D", "task": "equivalence relation called ''congruence''. \n\nFor any positive integer p called the ''congruence modulus'', \ntwo numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:\n:a = b + k\\,p\n\nThe corresponding set of multiplicative inverse for this task.\n\nAddition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.\n\nThe purpose of this task is to show, if your programming language allows it, \nhow to redefine operators so that they can be used transparently on modular integers. \nYou can do it either by using a dedicated library, or by implementing your own class.\n\nYou will use the following function for demonstration:\n:f(x) = x^{100} + x + 1\nYou will use 13 as the congruence modulus and you will compute f(10).\n\nIt is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. \nIn other words, the function is an algebraic expression that could be used with any ring, not just integers.\n\n", "solution": "#include \n#include \n\ntemplate\nT f(const T& x) {\n return (T) pow(x, 100) + x + 1;\n}\n\nclass ModularInteger {\nprivate:\n int value;\n int modulus;\n\n void validateOp(const ModularInteger& rhs) const {\n if (modulus != rhs.modulus) {\n throw std::runtime_error(\"Left-hand modulus does not match right-hand modulus.\");\n }\n }\n\npublic:\n ModularInteger(int v, int m) {\n modulus = m;\n value = v % m;\n }\n\n int getValue() const {\n return value;\n }\n\n int getModulus() const {\n return modulus;\n }\n\n ModularInteger operator+(const ModularInteger& rhs) const {\n validateOp(rhs);\n return ModularInteger(value + rhs.value, modulus);\n }\n\n ModularInteger operator+(int rhs) const {\n return ModularInteger(value + rhs, modulus);\n }\n\n ModularInteger operator*(const ModularInteger& rhs) const {\n validateOp(rhs);\n return ModularInteger(value * rhs.value, modulus);\n }\n\n friend std::ostream& operator<<(std::ostream&, const ModularInteger&);\n};\n\nstd::ostream& operator<<(std::ostream& os, const ModularInteger& self) {\n return os << \"ModularInteger(\" << self.value << \", \" << self.modulus << \")\";\n}\n\nModularInteger pow(const ModularInteger& lhs, int pow) {\n if (pow < 0) {\n throw std::runtime_error(\"Power must not be negative.\");\n }\n\n ModularInteger base(1, lhs.getModulus());\n while (pow-- > 0) {\n base = base * lhs;\n }\n return base;\n}\n\nint main() {\n using namespace std;\n\n ModularInteger input(10, 13);\n auto output = f(input);\n cout << \"f(\" << input << \") = \" << output << endl;\n\n return 0;\n}"} {"title": "Modular inverse", "language": "C++ from C", "task": "From Wikipedia:\n\nIn modulo ''m'' is an integer ''x'' such that\n\n::a\\,x \\equiv 1 \\pmod{m}.\n\nOr in other words, such that:\n\n::\\exists k \\in\\Z,\\qquad a\\, x = 1 + k\\,m\n\nIt can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task.\n\n\n;Task:\nEither by implementing the algorithm, by using a dedicated library or by using a built-in function in \nyour language, compute the modular inverse of 42 modulo 2017.\n\n", "solution": "#include \n \nint mul_inv(int a, int b)\n{\n\tint b0 = b, t, q;\n\tint x0 = 0, x1 = 1;\n\tif (b == 1) return 1;\n\twhile (a > 1) {\n\t\tq = a / b;\n\t\tt = b, b = a % b, a = t;\n\t\tt = x0, x0 = x1 - q * x0, x1 = t;\n\t}\n\tif (x1 < 0) x1 += b0;\n\treturn x1;\n}\n \nint main(void) {\n\tstd::cout << mul_inv(42, 2017) << std::endl;\n\treturn 0;\n}"} {"title": "Monads/List monad", "language": "C++", "task": "A Monad is a combination of a data-type with two helper functions written for that type. \n\nThe data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.\n\nThe bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.\n\nA sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. \n\nThe natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.\n\n\nDemonstrate in your programming language the following:\n\n#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String\n#Compose the two functions with bind\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\n// std::vector can be a list monad. Use the >> operator as the bind function\ntemplate \nauto operator>>(const vector& monad, auto f)\n{\n // Declare a vector of the same type that the function f returns\n vector> result;\n for(auto& item : monad)\n {\n // Apply the function f to each item in the monad. f will return a\n // new list monad containing 0 or more items. \n const auto r = f(item);\n // Concatenate the results of f with previous results\n result.insert(result.end(), begin(r), end(r));\n }\n \n return result;\n}\n\n// The Pure function returns a vector containing one item, t\nauto Pure(auto t)\n{\n return vector{t};\n}\n\n// A function to double items in the list monad\nauto Double(int i)\n{\n return Pure(2 * i);\n}\n\n// A function to increment items\nauto Increment(int i)\n{\n return Pure(i + 1);\n}\n\n// A function to convert items to a string\nauto NiceNumber(int i)\n{\n return Pure(to_string(i) + \" is a nice number\\n\");\n}\n\n// A function to map an item to a sequence ending at max value\n// for example: 497 -> {497, 498, 499, 500}\nauto UpperSequence = [](auto startingVal)\n{\n const int MaxValue = 500;\n vector sequence;\n while(startingVal <= MaxValue) \n sequence.push_back(startingVal++);\n return sequence;\n};\n\n// Print contents of a vector\nvoid PrintVector(const auto& vec)\n{\n cout << \" \";\n for(auto value : vec)\n {\n cout << value << \" \";\n }\n cout << \"\\n\";\n}\n\n// Print the Pythagorean triples\nvoid PrintTriples(const auto& vec)\n{\n cout << \"Pythagorean triples:\\n\";\n for(auto it = vec.begin(); it != vec.end();)\n {\n auto x = *it++;\n auto y = *it++;\n auto z = *it++;\n \n cout << x << \", \" << y << \", \" << z << \"\\n\";\n }\n cout << \"\\n\";\n}\n\nint main()\n{\n // Apply Increment, Double, and NiceNumber to {2, 3, 4} using the monadic bind \n auto listMonad = \n vector {2, 3, 4} >> \n Increment >> \n Double >>\n NiceNumber;\n \n PrintVector(listMonad);\n \n // Find Pythagorean triples using the list monad. The 'x' monad list goes\n // from 1 to the max; the 'y' goes from the current 'x' to the max; and 'z'\n // goes from the current 'y' to the max. The last bind returns the triplet\n // if it is Pythagorean, otherwise it returns an empty list monad.\n auto pythagoreanTriples = UpperSequence(1) >> \n [](int x){return UpperSequence(x) >>\n [x](int y){return UpperSequence(y) >>\n [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector{};};};};\n \n PrintTriples(pythagoreanTriples);\n}\n"} {"title": "Monads/Maybe monad", "language": "C++", "task": "Demonstrate in your programming language the following:\n\n#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String\n#Compose the two functions with bind\n\n\nA Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.\n\nA Maybe Monad is a monad which specifically encapsulates the type of an undefined value.\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\n\n// std::optional can be a maybe monad. Use the >> operator as the bind function\ntemplate \nauto operator>>(const optional& monad, auto f)\n{\n if(!monad.has_value())\n {\n // Return an empty maybe monad of the same type as if there \n // was a value\n return optional>();\n }\n\n return f(*monad);\n}\n\n// The Pure function returns a maybe monad containing the value t\nauto Pure(auto t)\n{\n return optional{t};\n}\n\n// A safe function to invert a value \nauto SafeInverse(double v)\n{\n if (v == 0)\n {\n return optional();\n }\n else\n {\n return optional(1/v);\n }\n}\n\n// A safe function to calculate the arc cosine\nauto SafeAcos(double v)\n{\n if(v < -1 || v > 1)\n {\n // The input is out of range, return an empty monad\n return optional();\n }\n else\n {\n return optional(acos(v));\n }\n}\n\n// Print the monad\ntemplate\nostream& operator<<(ostream& s, optional v)\n{\n s << (v ? to_string(*v) : \"nothing\");\n return s;\n}\n\nint main()\n{\n // Use bind to compose SafeInverse and SafeAcos\n vector tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5};\n \n cout << \"x -> acos(1/x) , 1/(acos(x)\\n\";\n for(auto v : tests)\n {\n auto maybeMonad = Pure(v);\n auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos;\n auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse;\n cout << v << \" -> \" << inverseAcos << \", \" << acosInverse << \"\\n\";\n }\n}\n"} {"title": "Monads/Writer monad", "language": "C++", "task": "The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.\n\nDemonstrate in your programming language the following:\n\n# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)\n# Write three simple functions: root, addOne, and half\n# Derive Writer monad versions of each of these functions\n# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\n// Use a struct as the monad\nstruct LoggingMonad\n{\n double Value;\n string Log;\n};\n\n// Use the >> operator as the bind function\nauto operator>>(const LoggingMonad& monad, auto f)\n{\n auto result = f(monad.Value);\n return LoggingMonad{result.Value, monad.Log + \"\\n\" + result.Log};\n}\n\n// Define the three simple functions\nauto Root = [](double x){ return sqrt(x); };\nauto AddOne = [](double x){ return x + 1; };\nauto Half = [](double x){ return x / 2.0; };\n\n// Define a function to create writer monads from the simple functions\nauto MakeWriter = [](auto f, string message)\n{\n return [=](double x){return LoggingMonad(f(x), message);};\n};\n\n// Derive writer versions of the simple functions\nauto writerRoot = MakeWriter(Root, \"Taking square root\");\nauto writerAddOne = MakeWriter(AddOne, \"Adding 1\");\nauto writerHalf = MakeWriter(Half, \"Dividing by 2\");\n\n\nint main()\n{\n // Compose the writers to compute the golden ratio\n auto result = LoggingMonad{5, \"Starting with 5\"} >> writerRoot >> writerAddOne >> writerHalf;\n cout << result.Log << \"\\nResult: \" << result.Value;\n}\n"} {"title": "Move-to-front algorithm", "language": "C++", "task": "Given a symbol table of a ''zero-indexed'' array of all possible input symbols\nthis algorithm reversibly transforms a sequence\nof input symbols into an array of output numbers (indices).\n\nThe transform in many cases acts to give frequently repeated input symbols\nlower indices which is useful in some compression algorithms.\n\n\n;Encoding algorithm:\n\n for each symbol of the input sequence:\n output the index of the symbol in the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Decoding algorithm:\n\n # Using the same starting symbol table\n for each index of the input sequence:\n output the symbol at that index of the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Example:\nEncoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''\n\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''b'''roood\n| 1\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| b'''r'''oood\n| 1 17\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| br'''o'''ood\n| 1 17 15\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| bro'''o'''od\n| 1 17 15 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| broo'''o'''d\n| 1 17 15 0 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| brooo'''d'''\n| 1 17 15 0 0 5\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\nDecoding the indices back to the original symbol order:\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''1''' 17 15 0 0 5\n| b\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| 1 '''17''' 15 0 0 5\n| br\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| 1 17 '''15''' 0 0 5\n| bro\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| 1 17 15 '''0''' 0 5\n| broo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 '''0''' 5\n| brooo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 0 '''5''' \n| broood\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\n;Task:\n:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. \n:* Show the strings and their encoding here.\n:* Add a check to ensure that the decoded string is the same as the original.\n\n\nThe strings are: \n\n broood \n bananaaa \n hiphophiphop \n(Note the misspellings in the above strings.)\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\n\nclass MTF\n{\npublic:\n string encode( string str )\n {\n\tfillSymbolTable();\n\tvector output;\n\tfor( string::iterator it = str.begin(); it != str.end(); it++ )\n\t{\n\t for( int i = 0; i < 26; i++ )\n\t {\n\t\tif( *it == symbolTable[i] )\n\t\t{\n\t\t output.push_back( i );\n\t\t moveToFront( i );\n\t\t break;\n\t\t}\n\t }\n\t}\n\tstring r;\n\tfor( vector::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t ostringstream ss;\n\t ss << *it;\n\t r += ss.str() + \" \";\n\t}\n\treturn r;\n }\n\n string decode( string str )\n {\n\tfillSymbolTable();\n\tistringstream iss( str ); vector output;\n\tcopy( istream_iterator( iss ), istream_iterator(), back_inserter >( output ) );\n\tstring r;\n\tfor( vector::iterator it = output.begin(); it != output.end(); it++ )\n\t{\n\t r.append( 1, symbolTable[*it] );\n\t moveToFront( *it );\n\t}\n\treturn r;\n }\n\nprivate:\n void moveToFront( int i )\n {\n\tchar t = symbolTable[i];\n\tfor( int z = i - 1; z >= 0; z-- )\n\t symbolTable[z + 1] = symbolTable[z];\n\n symbolTable[0] = t;\n }\n\n void fillSymbolTable()\n {\n for( int x = 0; x < 26; x++ )\n\t symbolTable[x] = x + 'a';\n }\n\n char symbolTable[26];\n};\n\nint main()\n{\n MTF mtf;\n string a, str[] = { \"broood\", \"bananaaa\", \"hiphophiphop\" };\n for( int x = 0; x < 3; x++ )\n {\n a = str[x];\n cout << a << \" -> encoded = \";\n a = mtf.encode( a );\n cout << a << \"; decoded = \" << mtf.decode( a ) << endl;\n }\n return 0;\n}\n"} {"title": "Multi-dimensional array", "language": "C++", "task": "For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. \n\nIt is enough to:\n# State the number and extent of each index to the array.\n# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.\n# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.\n\n\n;Task:\n* State if the language supports multi-dimensional arrays in its syntax and usual implementation.\n* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.\n* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.\n:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).\n* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.\n* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.\n\n\nShow all output here, (but you may judiciously use ellipses to shorten repetitive output text).\n\n", "solution": "#include \n#include \n\n// convienince for printing the contents of a collection\ntemplate\nstd::ostream& operator<<(std::ostream& out, const std::vector& c) {\n auto it = c.cbegin();\n auto end = c.cend();\n\n out << '[';\n if (it != end) {\n out << *it;\n it = std::next(it);\n }\n while (it != end) {\n out << \", \" << *it;\n it = std::next(it);\n }\n return out << ']';\n}\n\nvoid fourDim() {\n using namespace std;\n\n // create a 4d jagged array, with bounds checking etc...\n vector>>> arr;\n int cnt = 0;\n\n arr.push_back(vector>>{});\n arr[0].push_back(vector>{});\n arr[0][0].push_back(vector{});\n arr[0][0][0].push_back(cnt++);\n arr[0][0][0].push_back(cnt++);\n arr[0][0][0].push_back(cnt++);\n arr[0][0][0].push_back(cnt++);\n arr[0].push_back(vector>{});\n arr[0][1].push_back(vector{});\n arr[0][1][0].push_back(cnt++);\n arr[0][1][0].push_back(cnt++);\n arr[0][1][0].push_back(cnt++);\n arr[0][1][0].push_back(cnt++);\n arr[0][1].push_back(vector{});\n arr[0][1][1].push_back(cnt++);\n arr[0][1][1].push_back(cnt++);\n arr[0][1][1].push_back(cnt++);\n arr[0][1][1].push_back(cnt++);\n\n arr.push_back(vector>>{});\n arr[1].push_back(vector>{});\n arr[1][0].push_back(vector{});\n arr[1][0][0].push_back(cnt++);\n arr[1][0][0].push_back(cnt++);\n arr[1][0][0].push_back(cnt++);\n arr[1][0][0].push_back(cnt++);\n\n cout << arr << '\\n';\n}\n\nint main() {\n /* C++ does not have native support for multi-dimensional arrays,\n * but classes could be written to make things easier to work with.\n * There are standard library classes which can be used for single dimension arrays.\n * Also raw access is supported through pointers as in C.\n */\n\n fourDim();\n\n return 0;\n}"} {"title": "Multifactorial", "language": "C++", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\nMultifactorials generalize factorials as follows:\n: n! = n(n-1)(n-2)...(2)(1)\n: n!! = n(n-2)(n-4)...\n: n!! ! = n(n-3)(n-6)...\n: n!! !! = n(n-4)(n-8)...\n: n!! !! ! = n(n-5)(n-10)...\n\nIn all cases, the terms in the products are positive integers.\n\nIf we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: \n# Write a function that given n and the degree, calculates the multifactorial.\n# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.\n\n\n'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.\n\n", "solution": "#include \n#include \n#include \n/*Generate multifactorials to 9\n\n Nigel_Galloway\n November 14th., 2012.\n*/\nint main(void) {\n for (int g = 1; g < 10; g++) {\n int v[11], n=0;\n generate_n(std::ostream_iterator(std::cout, \" \"), 10, [&]{n++; return v[n]=(g\n#include \nusing namespace std;\nusing namespace std::tr1;\n\ntypedef shared_ptr TPtr_t;\n// the following is NOT correct:\nstd::vector bvec_WRONG(n, p); // create n copies of p, which all point to the same opject p points to.\n\n// nor is this:\nstd::vector bvec_ALSO_WRONG(n, TPtr_t(new T(*p)) ); // create n pointers to a single copy of *p\n\n// the correct solution\nstd::vector bvec(n);\nfor (int i = 0; i < n; ++i)\n bvec[i] = TPtr_t(new T(*p); //or any other call to T's constructor\n\n// another correct solution\n// this solution avoids uninitialized pointers at any point\nstd::vector bvec2;\nfor (int i = 0; i < n; ++i)\n bvec2.push_back(TPtr_t(new T(*p)); \n\n"} {"title": "Multisplit", "language": "C++", "task": "It is often necessary to split a string into pieces \nbased on several different (potentially multi-character) separator strings, \nwhile still retaining the information about which separators were present in the input. \n\nThis is particularly useful when doing small parsing tasks. \nThe task is to write code to demonstrate this.\n\nThe function (or procedure or method, as appropriate) should \ntake an input string and an ordered collection of separators. \n\nThe order of the separators is significant: \nThe delimiter order represents priority in matching, with the first defined delimiter having the highest priority. \nIn cases where there would be an ambiguity as to \nwhich separator to use at a particular point \n(e.g., because one separator is a prefix of another) \nthe separator with the highest priority should be used. \nDelimiters can be reused and the output from the function should be an ordered sequence of substrings.\n\nTest your code using the input string \"a!===b=!=c\" and the separators \"==\", \"!=\" and \"=\".\n\nFor these inputs the string should be parsed as \"a\" (!=) \"\" (==) \"b\" (=) \"\" (!=) \"c\", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is \"a\", empty string, \"b\", empty string, \"c\". \nNote that the quotation marks are shown for clarity and do not form part of the output.\n\n'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.\n\n", "solution": "#include \n#include \n#include \n\nint main( ) {\n std::string str( \"a!===b=!=c\" ) , output ;\n typedef boost::tokenizer > tokenizer ;\n boost::char_separator separator ( \"==\" , \"!=\" ) , sep ( \"!\" ) ;\n tokenizer mytok( str , separator ) ;\n tokenizer::iterator tok_iter = mytok.begin( ) ;\n for ( ; tok_iter != mytok.end( ) ; ++tok_iter )\n output.append( *tok_iter ) ;\n tokenizer nexttok ( output , sep ) ;\n for ( tok_iter = nexttok.begin( ) ; tok_iter != nexttok.end( ) ;\n\t ++tok_iter ) \n std::cout << *tok_iter << \" \" ;\n std::cout << '\\n' ;\n return 0 ;\n}"} {"title": "Munchausen numbers", "language": "C++", "task": "A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.\n\n('''Munchausen''' is also spelled: '''Munchhausen'''.) \n\nFor instance: 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between '''1''' and '''5000'''.\n\n\n;Also see:\n:* The OEIS entry: A046253\n:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''\n\n", "solution": "#include \n#include \n\nunsigned pwr[10];\n\nunsigned munch( unsigned i ) {\n unsigned sum = 0;\n while( i ) {\n sum += pwr[(i % 10)];\n i /= 10;\n }\n return sum;\n}\n\nint main( int argc, char* argv[] ) {\n for( int i = 0; i < 10; i++ )\n pwr[i] = (unsigned)pow( (float)i, (float)i );\n std::cout << \"Munchausen Numbers\\n==================\\n\";\n for( unsigned i = 1; i < 5000; i++ )\n if( i == munch( i ) ) std::cout << i << \"\\n\";\n return 0;\n}\n"} {"title": "Musical scale", "language": "C++", "task": "Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.\n\nThese are the notes \"C, D, E, F, G, A, B, C(1 octave higher)\", or \"Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)\" on Fixed do Solfege.\n\nFor the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.\n\nFor languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.\n\n", "solution": "#include \n#include \n#include \n\n#pragma comment ( lib, \"winmm.lib\" )\n\ntypedef unsigned char byte;\n\ntypedef union \n{ \n unsigned long word; \n unsigned char data[4]; \n}\nmidi_msg;\n\nclass midi\n{\npublic:\n midi()\n {\n\tif( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) \n\t{\n\t std::cout << \"Error opening MIDI Output...\" << std::endl;\n\t device = 0;\n\t}\n }\n ~midi()\n {\n\tmidiOutReset( device );\n\tmidiOutClose( device );\n }\n bool isOpen() { return device != 0; }\n void setInstrument( byte i )\n {\n\tmessage.data[0] = 0xc0; message.data[1] = i;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n }\n void playNote( byte n, unsigned i )\n {\n\tplayNote( n ); Sleep( i ); stopNote( n );\n }\n\nprivate:\n void playNote( byte n )\n {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 127; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n }\n void stopNote( byte n )\n {\n\tmessage.data[0] = 0x90; message.data[1] = n;\n\tmessage.data[2] = 0; message.data[3] = 0;\n\tmidiOutShortMsg( device, message.word );\n }\n HMIDIOUT device;\n midi_msg message;\n};\n\nint main( int argc, char* argv[] )\n{\n midi m;\n if( m.isOpen() )\n {\n\tbyte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };\n\tm.setInstrument( 42 );\n\tfor( int x = 0; x < 8; x++ )\n\t m.playNote( notes[x], rand() % 100 + 158 );\n\tSleep( 1000 );\n }\n return 0;\n}\n"} {"title": "N-queens problem", "language": "C++", "task": "right\n\nSolve the eight queens puzzle. \n\n\nYou can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.\n \nFor the number of solutions for small values of '''N''', see OEIS: A000170.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[Peaceful chess queen armies]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "// Much shorter than the version below;\n// uses C++11 threads to parallelize the computation; also uses backtracking\n// Outputs all solutions for any table size\n#include \n#include \n#include \n#include \n#include \n\n// Print table. 'pos' is a vector of positions \u2013 the index in pos is the row,\n// and the number at that index is the column where the queen is placed.\nstatic void print(const std::vector &pos)\n{\n\t// print table header\n\tfor (int i = 0; i < pos.size(); i++) {\n\t\tstd::cout << std::setw(3) << char('a' + i);\n\t}\n\n\tstd::cout << '\\n';\n\n\tfor (int row = 0; row < pos.size(); row++) {\n\t\tint col = pos[row];\n\t\tstd::cout << row + 1 << std::setw(3 * col + 3) << \" # \";\n\t\tstd::cout << '\\n';\n\t}\n\n\tstd::cout << \"\\n\\n\";\n}\n\nstatic bool threatens(int row_a, int col_a, int row_b, int col_b)\n{\n\treturn row_a == row_b // same row\n\t\tor col_a == col_b // same column\n\t\tor std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal\n}\n\n// the i-th queen is in the i-th row\n// we only check rows up to end_idx\n// so that the same function can be used for backtracking and checking the final solution\nstatic bool good(const std::vector &pos, int end_idx)\n{\n\tfor (int row_a = 0; row_a < end_idx; row_a++) {\n\t\tfor (int row_b = row_a + 1; row_b < end_idx; row_b++) {\n\t\t\tint col_a = pos[row_a];\n\t\t\tint col_b = pos[row_b];\n\t\t\tif (threatens(row_a, col_a, row_b, col_b)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic std::mutex print_count_mutex; // mutex protecting 'n_sols'\nstatic int n_sols = 0; // number of solutions\n\n// recursive DFS backtracking solver\nstatic void n_queens(std::vector &pos, int index)\n{\n\t// if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return\n\tif (index >= pos.size()) {\n\t\tif (good(pos, index)) {\n\t\t\tstd::lock_guard lock(print_count_mutex);\n\t\t\tprint(pos);\n\t\t\tn_sols++;\n\t\t}\n\n\t\treturn;\n\t}\n\n\t// backtracking step\n\tif (not good(pos, index)) {\n\t\treturn;\n\t}\n\n\t// optimization: the first level of the search tree is parallelized\n\tif (index == 0) {\n\t\tstd::vector> fts;\n\t\tfor (int col = 0; col < pos.size(); col++) {\n\t\t\tpos[index] = col;\n\t\t\tauto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); });\n\t\t\tfts.push_back(std::move(ft));\n\t\t}\n\n\t\tfor (const auto &ft : fts) {\n\t\t\tft.wait();\n\t\t}\n\t} else { // deeper levels are not\n\t\tfor (int col = 0; col < pos.size(); col++) {\n\t\t\tpos[index] = col;\n\t\t\tn_queens(pos, index + 1);\n\t\t}\n\t}\n}\n\nint main()\n{\n\tstd::vector start(12); // 12: table size\n\tn_queens(start, 0);\n\tstd::cout << n_sols << \" solutions found.\\n\";\n\treturn 0;\n}\n"} {"title": "Narcissistic decimal number", "language": "C++", "task": "A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "#include \n#include \nusing namespace std;\ntypedef unsigned int uint;\n\nclass NarcissisticDecs\n{\npublic:\n void makeList( int mx )\n {\n\tuint st = 0, tl; int pwr = 0, len;\n while( narc.size() < mx )\n\t{\n\t len = getDigs( st );\n\t if( pwr != len )\n\t {\n\t\tpwr = len;\n\t\tfillPower( pwr );\n\t }\n tl = 0;\n\t for( int i = 1; i < 10; i++ )\n\t\ttl += static_cast( powr[i] * digs[i] );\n\n\t if( tl == st ) narc.push_back( st );\n\t st++;\n\t}\n }\n\n void display()\n {\n\tfor( vector::iterator i = narc.begin(); i != narc.end(); i++ )\n\t cout << *i << \" \";\n\tcout << \"\\n\\n\";\n }\n\nprivate:\n int getDigs( uint st )\n {\n\tmemset( digs, 0, 10 * sizeof( int ) );\n\tint r = 0;\n\twhile( st )\n\t{\n\t digs[st % 10]++;\n\t st /= 10;\n\t r++;\n\t}\n return r;\n }\n\n void fillPower( int z )\n {\n\tfor( int i = 1; i < 10; i++ )\n\t powr[i] = pow( static_cast( i ), z );\n }\n\n vector narc;\n uint powr[10];\n int digs[10];\n};\n\nint main( int argc, char* argv[] )\n{\n NarcissisticDecs n;\n n.makeList( 25 );\n n.display();\n return system( \"pause\" );\n}\n"} {"title": "Nautical bell", "language": "C++", "task": "Task\n\nWrite a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.\n\nThe bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.\n\nIt is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice \"Two Bells Gone\"), if these are more usual for the system type. \n\n\n;Related task:\n* [[Sleep]]\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nclass bells\n{\npublic:\n void start()\n {\n\twatch[0] = \"Middle\"; watch[1] = \"Morning\"; watch[2] = \"Forenoon\"; watch[3] = \"Afternoon\"; watch[4] = \"Dog\"; watch[5] = \"First\"; \n\tcount[0] = \"One\"; count[1] = \"Two\"; count[2] = \"Three\"; count[3] = \"Four\"; count[4] = \"Five\"; count[5] = \"Six\"; count[6] = \"Seven\"; count[7] = \"Eight\";\n\t_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );\n }\nprivate:\n static DWORD WINAPI bell( LPVOID p )\n {\n\tDWORD wait = _inst->waitTime();\n\twhile( true )\n\t{\n\t Sleep( wait );\n\t _inst->playBell();\n\t wait = _inst->waitTime();\n\t}\n\treturn 0;\n }\n\n DWORD waitTime() \n { \n\tGetLocalTime( &st );\n\tint m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;\n\treturn( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );\n }\n\n void playBell()\n {\n\tGetLocalTime( &st );\n\tint b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;\n\tint w = ( 60 * st.wHour + st.wMinute ); \n\tif( w < 1 ) w = 5; else w = ( w - 1 ) / 240;\n\tchar hr[32]; wsprintf( hr, \"%.2d:%.2d\", st.wHour, st.wMinute );\n\n\tcout << hr << \" - \" << watch[w] << \" watch - \" << count[b - 1] << \" Bell\";\n\tif( b > 1 ) cout << \"s\"; else cout << \" \"; cout << \" Gone.\" << endl;\n\n\tfor( int x = 0, c = 1; x < b; x++, c++ )\n\t{\n\t cout << \"\\7\"; Sleep( 500 );\n\t if( !( c % 2 ) ) Sleep( 300 );\n\t}\n }\n\n SYSTEMTIME st;\n string watch[7], count[8];\n static bells* _inst;\n};\n//--------------------------------------------------------------------------------------------------\nbells* bells::_inst = 0;\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n bells b; b.start();\n while( 1 ); // <- runs forever!\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Negative base numbers", "language": "C++ from C#", "task": "Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia\n\n\n;Task:\n\n*Encode the decimal number 10 as negabinary (expect 11110)\n*Encode the decimal number 146 as negaternary (expect 21102)\n*Encode the decimal number 15 as negadecimal (expect 195)\n*In each of the above cases, convert the encoded number back to decimal.\n\n\n;extra credit:\n\n* supply an integer, that when encoded to base -62 (or something \"higher\"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.\n\n", "solution": "#include \n#include \n#include \n#include \n\nconst std::string DIGITS = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nstd::string encodeNegativeBase(int64_t n, int b) {\n if (b < -62 || b > -1) {\n throw std::runtime_error(\"Argument out of range: b\");\n }\n if (n == 0) {\n return \"0\";\n }\n\n std::string output;\n int64_t nn = n;\n while (nn != 0) {\n int rem = nn % b;\n nn /= b;\n if (rem < 0) {\n nn++;\n rem -= b;\n }\n output += DIGITS[rem];\n }\n\n std::reverse(output.begin(), output.end());\n return output;\n}\n\nint64_t decodeNegativeBase(const std::string& ns, int b) {\n if (b < -62 || b > -1) {\n throw std::runtime_error(\"Argument out of range: b\");\n }\n if (ns == \"0\") {\n return 0;\n }\n\n int64_t total = 0;\n int64_t bb = 1;\n\n for (auto it = ns.crbegin(); it != ns.crend(); it = std::next(it)) {\n auto ptr = std::find(DIGITS.cbegin(), DIGITS.cend(), *it);\n if (ptr != DIGITS.cend()) {\n auto idx = ptr - DIGITS.cbegin();\n total += idx * bb;\n }\n bb *= b;\n }\n return total;\n}\n\nint main() {\n using namespace std;\n\n vector> nbl({\n make_pair(10, -2),\n make_pair(146, -3),\n make_pair(15, -10),\n make_pair(142961, -62)\n });\n\n for (auto& p : nbl) {\n string ns = encodeNegativeBase(p.first, p.second);\n cout << setw(12) << p.first << \" encoded in base \" << setw(3) << p.second << \" = \" << ns.c_str() << endl;\n\n int64_t n = decodeNegativeBase(ns, p.second);\n cout << setw(12) << ns.c_str() << \" decoded in base \" << setw(3) << p.second << \" = \" << n << endl;\n\n cout << endl;\n }\n\n return 0;\n}"} {"title": "Nested function", "language": "C++11", "task": "In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.\n\n\n;Task: \nWrite a program consisting of two nested functions that prints the following text.\n\n 1. first\n 2. second\n 3. third\n\nThe outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator \". \" as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.\n\nThe inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.\n\n\n;References:\n:* Nested function\n\n", "solution": "#include \n#include \n#include \n \nstd::vector makeList(std::string separator) {\n auto counter = 0;\n auto makeItem = [&](std::string item) {\n return std::to_string(++counter) + separator + item;\n };\n return {makeItem(\"first\"), makeItem(\"second\"), makeItem(\"third\")};\n}\n\nint main() {\n for (auto item : makeList(\". \"))\n std::cout << item << \"\\n\";\n}"} {"title": "Nested templated data", "language": "C++", "task": "A template for data is an arbitrarily nested tree of integer indices.\n \nData payloads are given as a separate mapping, array or other simpler, flat,\nassociation of indices to individual items of data, and are strings.\nThe idea is to create a data structure with the templates' nesting, and the \npayload corresponding to each index appearing at the position of each index.\n\nAnswers using simple string replacement or regexp are to be avoided. The idea is \nto use the native, or usual implementation of lists/tuples etc of the language\nand to hierarchically traverse the template to generate the output.\n\n;Task Detail:\nGiven the following input template t and list of payloads p:\n# Square brackets are used here to denote nesting but may be changed for other,\n# clear, visual representations of nested data appropriate to ones programming \n# language.\nt = [\n [[1, 2],\n [3, 4, 1], \n 5]]\n\np = 'Payload#0' ... 'Payload#6'\n\nThe correct output should have the following structure, (although spacing and \nlinefeeds may differ, the nesting and order should follow):\n[[['Payload#1', 'Payload#2'],\n ['Payload#3', 'Payload#4', 'Payload#1'],\n 'Payload#5']]\n\n1. Generate the output for the above template, t.\n\n;Optional Extended tasks:\n2. Show which payloads remain unused.\n3. Give some indication/handling of indices without a payload.\n\n''Show output on this page.''\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\n\n// print a single payload\ntemplate\nvoid PrintPayloads(const P &payloads, int index, bool isLast)\n{\n if(index < 0 || index >= (int)size(payloads)) cout << \"null\"; \n else cout << \"'\" << payloads[index] << \"'\";\n if (!isLast) cout << \", \"; // add a comma between elements\n}\n\n// print a tuple of playloads\ntemplate\nvoid PrintPayloads(const P &payloads, tuple const& nestedTuple, bool isLast = true)\n{\n std::apply // recursively call PrintPayloads on each element of the tuple\n (\n [&payloads, isLast](Ts const&... tupleArgs)\n {\n size_t n{0};\n cout << \"[\";\n (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);\n cout << \"]\";\n cout << (isLast ? \"\\n\" : \",\\n\");\n }, nestedTuple\n );\n}\n\n// find the unique index of a single index (helper for the function below)\nvoid FindUniqueIndexes(set &indexes, int index)\n{\n indexes.insert(index);\n}\n\n// find the unique indexes in the tuples\ntemplate\nvoid FindUniqueIndexes(set &indexes, std::tuple const& nestedTuple)\n{\n std::apply\n (\n [&indexes](Ts const&... tupleArgs)\n {\n (FindUniqueIndexes(indexes, tupleArgs),...);\n }, nestedTuple\n );\n}\n\n// print the payloads that were not used\ntemplate\nvoid PrintUnusedPayloads(const set &usedIndexes, const P &payloads)\n{\n for(size_t i = 0; i < size(payloads); i++)\n {\n if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << \"\\n\";\n }\n}\n\nint main()\n{\n // define the playloads, they can be in most containers\n vector payloads {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\", \"Payload#4\", \"Payload#5\", \"Payload#6\"};\n const char *shortPayloads[] {\"Payload#0\", \"Payload#1\", \"Payload#2\", \"Payload#3\"}; // as a C array\n\n // define the indexes as a nested tuple\n auto tpl = make_tuple(make_tuple(\n make_tuple(1, 2),\n make_tuple(3, 4, 1),\n 5));\n\n cout << \"Mapping indexes to payloads:\\n\";\n PrintPayloads(payloads, tpl); \n\n cout << \"\\nFinding unused payloads:\\n\";\n set usedIndexes;\n FindUniqueIndexes(usedIndexes, tpl);\n PrintUnusedPayloads(usedIndexes, payloads);\n\n cout << \"\\nMapping to some out of range payloads:\\n\";\n PrintPayloads(shortPayloads, tpl); \n \n return 0;\n}"} {"title": "Nim game", "language": "C++ from Go", "task": "Nim is a simple game where the second player-if they know the trick-will always win.\n\n\nThe game has only 3 rules:\n::* start with '''12''' tokens\n::* each player takes '''1, 2, or 3''' tokens in turn\n::* the player who takes the last token wins.\n\n\nTo win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. \n\n;Task:\nDesign a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\nvoid showTokens(int tokens) {\n cout << \"Tokens remaining \" << tokens << endl << endl;\n}\n\nint main() {\n int tokens = 12;\n while (true) {\n showTokens(tokens);\n cout << \" How many tokens 1, 2 or 3? \";\n int t;\n cin >> t;\n if (cin.fail()) {\n cin.clear();\n cin.ignore(numeric_limits::max(), '\\n');\n cout << endl << \"Invalid input, try again.\" << endl << endl;\n } else if (t < 1 || t > 3) {\n cout << endl << \"Must be a number between 1 and 3, try again.\" << endl << endl;\n } else {\n int ct = 4 - t;\n string s = (ct > 1) ? \"s\" : \"\";\n cout << \" Computer takes \" << ct << \" token\" << s << endl << endl;\n tokens -= 4;\n }\n if (tokens == 0) {\n showTokens(0);\n cout << \" Computer wins!\" << endl;\n return 0;\n }\n }\n}"} {"title": "Nonoblock", "language": "C++", "task": "Nonogram puzzle.\n\n\n;Given:\n* The number of cells in a row.\n* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.\n\n\n;Task: \n* show all possible positions. \n* show the number of positions of the blocks for the following cases within the row. \n* show all output on this page. \n* use a \"neat\" diagram of the block positions.\n\n\n;Enumerate the following configurations:\n# '''5''' cells and '''[2, 1]''' blocks\n# '''5''' cells and '''[]''' blocks (no blocks)\n# '''10''' cells and '''[8]''' blocks\n# '''15''' cells and '''[2, 3, 2, 3]''' blocks\n# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)\n\n\n;Example:\nGiven a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:\n\n |_|_|_|_|_| # 5 cells and [2, 1] blocks\n\nAnd would expand to the following 3 possible rows of block positions:\n\n |A|A|_|B|_|\n |A|A|_|_|B|\n |_|A|A|_|B|\n\n\nNote how the sets of blocks are always separated by a space.\n\nNote also that it is not necessary for each block to have a separate letter. \nOutput approximating\n\nThis:\n |#|#|_|#|_|\n |#|#|_|_|#|\n |_|#|#|_|#|\n\nThis would also work:\n ##.#.\n ##..#\n .##.#\n\n\n;An algorithm:\n* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).\n* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.\n* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.\n\n(This is the algorithm used in the [[Nonoblock#Python]] solution). \n\n\n;Reference:\n* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef std::pair > puzzle;\n\nclass nonoblock {\npublic:\n void solve( std::vector& p ) {\n for( std::vector::iterator i = p.begin(); i != p.end(); i++ ) {\n counter = 0;\n std::cout << \" Puzzle: \" << ( *i ).first << \" cells and blocks [ \";\n for( std::vector::iterator it = ( *i ).second.begin(); it != ( *i ).second.end(); it++ )\n std::cout << *it << \" \";\n std::cout << \"] \";\n int s = std::accumulate( ( *i ).second.begin(), ( *i ).second.end(), 0 ) + ( ( *i ).second.size() > 0 ? ( *i ).second.size() - 1 : 0 );\n if( ( *i ).first - s < 0 ) {\n std::cout << \"has no solution!\\n\\n\\n\";\n continue;\n }\n std::cout << \"\\n Possible configurations:\\n\\n\";\n std::string b( ( *i ).first, '-' );\n solve( *i, b, 0 );\n std::cout << \"\\n\\n\";\n } \n }\n\nprivate:\n void solve( puzzle p, std::string n, int start ) {\n if( p.second.size() < 1 ) {\n output( n );\n return;\n }\n std::string temp_string;\n int offset,\n this_block_size = p.second[0];\n\n int space_need_for_others = std::accumulate( p.second.begin() + 1, p.second.end(), 0 );\n space_need_for_others += p.second.size() - 1;\n\n int space_for_curr_block = p.first - space_need_for_others - std::accumulate( p.second.begin(), p.second.begin(), 0 );\n\n std::vector v1( p.second.size() - 1 );\n std::copy( p.second.begin() + 1, p.second.end(), v1.begin() );\n puzzle p1 = std::make_pair( space_need_for_others, v1 );\n\n for( int a = 0; a < space_for_curr_block; a++ ) {\n temp_string = n;\n\n if( start + this_block_size > n.length() ) return;\n\n for( offset = start; offset < start + this_block_size; offset++ )\n temp_string.at( offset ) = 'o';\n\n if( p1.first ) solve( p1, temp_string, offset + 1 );\n else output( temp_string );\n\n start++;\n }\n }\n void output( std::string s ) {\n char b = 65 - ( s.at( 0 ) == '-' ? 1 : 0 );\n bool f = false;\n std::cout << std::setw( 3 ) << ++counter << \"\\t|\";\n for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {\n b += ( *i ) == 'o' && f ? 1 : 0;\n std::cout << ( ( *i ) == 'o' ? b : '_' ) << \"|\";\n f = ( *i ) == '-' ? true : false;\n }\n std::cout << \"\\n\";\n }\n\n unsigned counter;\n};\n\nint main( int argc, char* argv[] )\n{\n std::vector problems;\n std::vector blocks; \n blocks.push_back( 2 ); blocks.push_back( 1 );\n problems.push_back( std::make_pair( 5, blocks ) );\n blocks.clear();\n problems.push_back( std::make_pair( 5, blocks ) );\n blocks.push_back( 8 );\n problems.push_back( std::make_pair( 10, blocks ) );\n blocks.clear();\n blocks.push_back( 2 ); blocks.push_back( 3 );\n problems.push_back( std::make_pair( 5, blocks ) );\n blocks.push_back( 2 ); blocks.push_back( 3 );\n problems.push_back( std::make_pair( 15, blocks ) );\n\n nonoblock nn;\n nn.solve( problems );\n\n return 0;\n}\n"} {"title": "Nonogram solver", "language": "C++", "task": "nonogram is a puzzle that provides \nnumeric clues used to fill in a grid of cells, \nestablishing for each cell whether it is filled or not. \nThe puzzle solution is typically a picture of some kind.\n\nEach row and column of a rectangular grid is annotated with the lengths \nof its distinct runs of occupied cells. \nUsing only these lengths you should find one valid configuration \nof empty and occupied cells, or show a failure message.\n\n;Example\nProblem: Solution:\n\n. . . . . . . . 3 . # # # . . . . 3\n. . . . . . . . 2 1 # # . # . . . . 2 1\n. . . . . . . . 3 2 . # # # . . # # 3 2\n. . . . . . . . 2 2 . . # # . . # # 2 2\n. . . . . . . . 6 . . # # # # # # 6\n. . . . . . . . 1 5 # . # # # # # . 1 5\n. . . . . . . . 6 # # # # # # . . 6\n. . . . . . . . 1 . . . . # . . . 1\n. . . . . . . . 2 . . . # # . . . 2\n1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3\n2 1 5 1 2 1 5 1 \nThe problem above could be represented by two lists of lists:\nx = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]\ny = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]\nA more compact representation of the same problem uses strings, \nwhere the letters represent the numbers, A=1, B=2, etc:\nx = \"C BA CB BB F AE F A B\"\ny = \"AB CA AE GA E C D C\"\n\n;Task\nFor this task, try to solve the 4 problems below, read from a \"nonogram_problems.txt\" file that has this content \n(the blank lines are separators):\nC BA CB BB F AE F A B\nAB CA AE GA E C D C\n\nF CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\nD D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\n\nCA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\nBC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\n\nE BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\nE CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\n\n'''Extra credit''': generate nonograms with unique solutions, of desired height and width.\n\nThis task is the problem n.98 of the \"99 Prolog Problems\" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).\n\n; Related tasks\n* [[Nonoblock]].\n\n;See also\n* Arc Consistency Algorithm\n* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)\n* http://twanvl.nl/blog/haskell/Nonograms (Haskell)\n* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)\n\n", "solution": "// A class to solve Nonogram (Hadje) Puzzles\n// Nigel Galloway - January 23rd., 2017\ntemplate class Nonogram {\n enum class ng_val : char {X='#',B='.',V='?'};\n template struct N {\n N() {}\n N(std::vector ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}\n std::bitset<_NG> X, B, T, Tx, Tb;\n std::vector ng;\n int En, gNG;\n void fn (const int n,const int i,const int g,const int e,const int l){ \n if (fe(g,l,false) and fe(g+l,e,true)){\n if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}\n else {\n if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}\n }}\n if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);\n }\n void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}\n ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}\n inline bool fe (const int n,const int i, const bool g){\n for (int e = n;e> ng;\n std::vector> gn;\n int En, zN, zG;\n void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}\npublic:\n Nonogram(const std::vector>& n,const std::vector>& i,const std::vector& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {\n for (int n=0; n(i[n],zN));\n for (int i=0; i(n[i],zG));\n if (i < g.size()) for(int e=0; e(ng[i].fg(g));}n<\n#include \n\nunsigned int divisor_count(unsigned int n) {\n unsigned int total = 1;\n for (; (n & 1) == 0; n >>= 1)\n ++total;\n for (unsigned int p = 3; p * p <= n; p += 2) {\n unsigned int count = 1;\n for (; n % p == 0; n /= p)\n ++count;\n total *= count;\n }\n if (n > 1)\n total *= 2;\n return total;\n}\n\nint main() {\n std::cout.imbue(std::locale(\"\"));\n std::cout << \"First 50 numbers which are the cube roots of the products of \"\n \"their proper divisors:\\n\";\n for (unsigned int n = 1, count = 0; count < 50000; ++n) {\n if (n == 1 || divisor_count(n) == 8) {\n ++count;\n if (count <= 50)\n std::cout << std::setw(3) << n\n << (count % 10 == 0 ? '\\n' : ' ');\n else if (count == 500 || count == 5000 || count == 50000)\n std::cout << std::setw(6) << count << \"th: \" << n << '\\n';\n }\n }\n}"} {"title": "Numbers with equal rises and falls", "language": "C++", "task": "When a number is written in base 10, adjacent digits may \"rise\" or \"fall\" as the number is read (usually from left to right).\n\n\n;Definition:\nGiven the decimal digits of the number are written as a series d:\n:* A ''rise'' is an index i such that d(i) < d(i+1)\n:* A ''fall'' is an index i such that d(i) > d(i+1)\n\n\n;Examples:\n:* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence.\n:* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence.\n\n\n;Task:\n:* Print the first '''200''' numbers in the sequence \n:* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002'''\n\n\n;See also:\n* OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal \"rises\" and \"falls\".\n\n\n;Related tasks:\n* Esthetic numbers\n\n", "solution": "#include \n#include \n\nbool equal_rises_and_falls(int n) {\n int total = 0;\n for (int previous_digit = -1; n > 0; n /= 10) {\n int digit = n % 10;\n if (previous_digit > digit)\n ++total;\n else if (previous_digit >= 0 && previous_digit < digit)\n --total;\n previous_digit = digit;\n }\n return total == 0;\n}\n\nint main() {\n const int limit1 = 200;\n const int limit2 = 10000000;\n int n = 0;\n std::cout << \"The first \" << limit1 << \" numbers in the sequence are:\\n\";\n for (int count = 0; count < limit2; ) {\n if (equal_rises_and_falls(++n)) {\n ++count;\n if (count <= limit1)\n std::cout << std::setw(3) << n << (count % 20 == 0 ? '\\n' : ' ');\n }\n }\n std::cout << \"\\nThe \" << limit2 << \"th number in the sequence is \" << n << \".\\n\";\n}"} {"title": "Numeric error propagation", "language": "C++", "task": "If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; \nthen if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, \nthen sf can be calculated as follows:\n\n:;Addition/Subtraction\n:* If f = a +- c, or f = c +- a then '''sf = sa'''\n:* If f = a +- b then '''sf2 = sa2 + sb2'''\n\n:;Multiplication/Division\n:* If f = ca or f = ac then '''sf = |csa|'''\n:* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)'''\n\n:;Exponentiation\n:* If f = ac then '''sf = |fc(sa / a)|'''\n\n\nCaution:\n::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue.\n\n\n;Task details:\n# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.\n# Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2 \n# Print and display both '''d''' and its error.\n\n \n\n;References:\n* A Guide to Error Propagation B. Keeney, 2005.\n* Propagation of uncertainty Wikipedia.\n\n\n;Related task:\n* [[Quaternion type]]\n\n", "solution": "#pragma once\n\n#include \n#include \n#include \n#include \n\nclass Approx {\npublic:\n Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}\n\n operator std::string() const {\n std::ostringstream os(\"\");\n os << std::setprecision(15) << v << \" \u00b1\" << std::setprecision(15) << s << std::ends;\n return os.str();\n }\n\n Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }\n Approx operator +(double d) const { return Approx(v + d, s); }\n Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }\n Approx operator -(double d) const { return Approx(v - d, s); }\n\n Approx operator *(const Approx& a) const {\n const double t = v * a.v;\n return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n }\n\n Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }\n\n Approx operator /(const Approx& a) const {\n const double t = v / a.v;\n return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));\n }\n\n Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }\n\n Approx pow(double d) const {\n const double t = ::pow(v, d);\n return Approx(t, fabs(t * d * s / v));\n }\n\nprivate:\n double v, s;\n};"} {"title": "Old Russian measure of length", "language": "C++", "task": "Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).\n\n\nIt is an example of a linear transformation of several variables. \n\n\nThe program should accept a single value in a selected unit of measurement, and convert and return it to the other units: \n''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.\n\n\n;Also see:\n:* Old Russian measure of length\n\n", "solution": "#include \n#include \n//-------------------------------------------------------------------------------------------\nusing namespace std;\n\n//-------------------------------------------------------------------------------------------\nclass ormConverter\n{\npublic:\n ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),\n\t\t MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}\n void convert( char c, float l )\n {\n\tsystem( \"cls\" );\n\tcout << endl << l;\n\tswitch( c )\n\t{\n\t case 'A': cout << \" Arshin to:\"; l *= AR; break;\n\t case 'C': cout << \" Centimeter to:\"; l *= CE; break;\n\t case 'D': cout << \" Diuym to:\"; l *= DI; break;\n\t case 'F': cout << \" Fut to:\"; l *= FU; break;\n\t case 'K': cout << \" Kilometer to:\"; l *= KI; break;\n\t case 'L': cout << \" Liniya to:\"; l *= LI; break;\n\t case 'M': cout << \" Meter to:\"; l *= ME; break;\n\t case 'I': cout << \" Milia to:\"; l *= MI; break;\n\t case 'P': cout << \" Piad to:\"; l *= PI; break;\n\t case 'S': cout << \" Sazhen to:\"; l *= SA; break;\n\t case 'T': cout << \" Tochka to:\"; l *= TO; break;\n\t case 'V': cout << \" Vershok to:\"; l *= VE; break;\n\t case 'E': cout << \" Versta to:\"; l *= VR;\n\t}\n\n\tfloat ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,\n\t mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;\n\tcout << left << endl << \"=================\" << endl\n\t << setw( 12 ) << \"Arshin:\" << ar << endl << setw( 12 ) << \"Centimeter:\" << ce << endl\n\t << setw( 12 ) << \"Diuym:\" << di << endl << setw( 12 ) << \"Fut:\" << fu << endl\n\t << setw( 12 ) << \"Kilometer:\" << ki << endl << setw( 12 ) << \"Liniya:\" << li << endl\n\t << setw( 12 ) << \"Meter:\" << me << endl << setw( 12 ) << \"Milia:\" << mi << endl\n\t << setw( 12 ) << \"Piad:\" << pi << endl << setw( 12 ) << \"Sazhen:\" << sa << endl\n\t << setw( 12 ) << \"Tochka:\" << to << endl << setw( 12 ) << \"Vershok:\" << ve << endl\n\t << setw( 12 ) << \"Versta:\" << vr << endl << endl << endl;\n }\nprivate:\n const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;\n};\n//-------------------------------------------------------------------------------------------\nint _tmain(int argc, _TCHAR* argv[])\n{\n ormConverter c;\n char s; float l;\n while( true )\n {\n\tcout << \"What unit:\\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\\n\";\n\tcin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;\n\tcout << \"Length (0 to Quit): \"; cin >> l; if( l == 0 ) return 0;\n\tc.convert( s, l ); system( \"pause\" ); system( \"cls\" );\n }\n return 0;\n}\n//-------------------------------------------------------------------------------------------\n"} {"title": "Old lady swallowed a fly", "language": "C++ from C#", "task": "Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. \n\nThis song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.\n\n\n\n", "solution": "#include \n\nconst char *CREATURES[] = { \"fly\", \"spider\", \"bird\", \"cat\", \"dog\", \"goat\", \"cow\", \"horse\" };\nconst char *COMMENTS[] = {\n \"I don't know why she swallowed that fly.\\nPerhaps she'll die\\n\",\n \"That wiggled and jiggled and tickled inside her\",\n \"How absurd, to swallow a bird\",\n \"Imagine that. She swallowed a cat\",\n \"What a hog to swallow a dog\",\n \"She just opened her throat and swallowed that goat\",\n \"I don't know how she swallowed that cow\",\n \"She's dead of course\"\n};\n\nint main() {\n auto max = sizeof(CREATURES) / sizeof(char*);\n for (size_t i = 0; i < max; ++i) {\n std::cout << \"There was an old lady who swallowed a \" << CREATURES[i] << '\\n';\n std::cout << COMMENTS[i] << '\\n';\n for (int j = i; j > 0 && i < max - 1; --j) {\n std::cout << \"She swallowed the \" << CREATURES[j] << \" to catch the \" << CREATURES[j - 1] << '\\n';\n if (j == 1)\n std::cout << COMMENTS[j - 1] << '\\n';\n }\n }\n\n return 0;\n}"} {"title": "One of n lines in a file", "language": "C++11", "task": "A method of choosing a line randomly from a file:\n::* Without reading the file more than once\n::* When substantial parts of the file cannot be held in memory\n::* Without knowing how many lines are in the file\nIs to:\n::* keep the first line of the file as a possible choice, then\n::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.\n::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.\n::* ...\n::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N\n\n::* Return the computed possible choice when no further lines exist in the file.\n\n\n;Task:\n# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.\n# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.\n# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.\n\n\nNote: You may choose a smaller number of repetitions if necessary, but mention this up-front.\n\nNote: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling\n\n", "solution": "#include \n#include \n#include \n#include \nusing namespace std;\n\nmt19937 engine; //mersenne twister\n\nunsigned int one_of_n(unsigned int n) {\n\tunsigned int choice;\n\tfor(unsigned int i = 0; i < n; ++i) {\n\t\tuniform_int_distribution distribution(0, i);\n\t\tif(!distribution(engine))\n\t\t\tchoice = i;\n\t}\n\treturn choice;\n}\n\nint main() {\n\tengine = mt19937(random_device()()); //seed random generator from system\n\tunsigned int results[10] = {0};\n\tfor(unsigned int i = 0; i < 1000000; ++i)\n\t\tresults[one_of_n(10)]++;\n\tostream_iterator out_it(cout, \" \");\n\tcopy(results, results+10, out_it);\n\tcout << '\\n';\n}\n"} {"title": "Operator precedence", "language": "C++", "task": "Operators in C and C++}}\n\n\n;Task:\nProvide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. \n\nOperators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. \n\nState whether arguments are passed by value or by reference.\n\n", "solution": "The following is a table that lists the [[wp:order of operations|precedence]] and [[wp:operator associativity|associativity]] of all the operators in the [[wp:C (programming language)|C]] and [[wp:C++|C++]] languages. An operator's precedence is unaffected by overloading.\n\n{| class=\"wikitable\"\n|-\n! style=\"text-align: left\" | Precedence\n! style=\"text-align: left\" | Operator\n! style=\"text-align: left\" | Description\n! style=\"text-align: left\" | Associativity\n|-\n! 1\nhighest\n| ::\n| Scope resolution (C++ only)\n| style=\"vertical-align: top\" rowspan=\"12\" | Left-to-right\n|-\n! rowspan=11| 2\n| style=\"border-bottom-style: none\" | ++\n| style=\"border-bottom-style: none\" | Suffix increment\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | --\n| style=\"border-bottom-style: none; border-top-style: none\" | Suffix decrement\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | ()\n| style=\"border-bottom-style: none; border-top-style: none\" | Function call\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | []\n| style=\"border-bottom-style: none; border-top-style: none\" | Array subscripting\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | .\n| style=\"border-bottom-style: none; border-top-style: none\" | Element selection by reference\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | ->\n| style=\"border-bottom-style: none; border-top-style: none\" | Element selection through pointer\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | typeid()\n| style=\"border-bottom-style: none; border-top-style: none\" | [[wp:Run-time type information|Run-time type information]] (C++ only) (see [[wp:typeid|typeid]])\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | const_cast\n| style=\"border-bottom-style: none; border-top-style: none\" | Type cast (C++ only) (see [[wp:const cast|const cast]])\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | dynamic_cast\n| style=\"border-bottom-style: none; border-top-style: none\" | Type cast (C++ only) (see [[wp:dynamic_cast|dynamic cast]])\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | reinterpret_cast\n| style=\"border-bottom-style: none; border-top-style: none\" | Type cast (C++ only) (see [[wp:reinterpret cast|reinterpret cast]])\n|-\n| style=\"border-top-style: none\" | static_cast\n| style=\"border-top-style: none\" | Type cast (C++ only) (see [[wp:static cast|static cast]])\n|-\n! rowspan=12| 3\n| style=\"border-bottom-style: none\" | ++\n| style=\"border-bottom-style: none\" | Prefix increment\n| style=\"vertical-align: top\" rowspan=\"12\" | Right-to-left\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | --\n| style=\"border-bottom-style: none; border-top-style: none\" | Prefix decrement\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | +\n| style=\"border-bottom-style: none; border-top-style: none\" | Unary plus\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | -\n| style=\"border-bottom-style: none; border-top-style: none\" | Unary minus\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | !\n| style=\"border-bottom-style: none; border-top-style: none\" | Logical NOT\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | ~\n| style=\"border-bottom-style: none; border-top-style: none\" | Bitwise NOT\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | (''type'')\n| style=\"border-bottom-style: none; border-top-style: none\" | Type cast\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | *\n| style=\"border-bottom-style: none; border-top-style: none\" | Indirection (dereference)\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | &\n| style=\"border-bottom-style: none; border-top-style: none\" | Address-of \n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | sizeof\n| style=\"border-bottom-style: none; border-top-style: none\" | [[wp:sizeof|Size-of]]\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | new, new[]\n| style=\"border-bottom-style: none; border-top-style: none\" | Dynamic memory allocation (C++ only)\n|-\n| style=\"border-top-style: none\" | delete, delete[]\n| style=\"border-top-style: none\" | Dynamic memory deallocation (C++ only)\n|-\n! rowspan=2| 4\n| style=\"border-bottom-style: none\" | .*\n| style=\"border-bottom-style: none\" | Pointer to member (C++ only)\n| style=\"vertical-align: top\" rowspan=\"20\" | Left-to-right\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | ->*\n| style=\"border-bottom-style: none; border-top-style: none\" | Pointer to member (C++ only)\n|-\n! rowspan=3| 5\n| style=\"border-bottom-style: none\" | *\n| style=\"border-bottom-style: none\" | Multiplication\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | /\n| style=\"border-bottom-style: none; border-top-style: none\" | Division\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | %\n| style=\"border-bottom-style: none; border-top-style: none\" | [[wp:Modulo operation|Modulo]] (remainder)\n|-\n! rowspan=2| 6\n| style=\"border-bottom-style: none\" | +\n| style=\"border-bottom-style: none\" | Addition\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | -\n| style=\"border-bottom-style: none; border-top-style: none\" | Subtraction\n|-\n! rowspan=2| 7\n| style=\"border-bottom-style: none\" | <<\n| style=\"border-bottom-style: none\" | [[wp:Bitwise operation|Bitwise]] left shift\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | >>\n| style=\"border-bottom-style: none; border-top-style: none\" | [[wp:Bitwise operation|Bitwise]] right shift\n|-\n! rowspan=4| 8\n| style=\"border-bottom-style: none\" | <\n| style=\"border-bottom-style: none\" | Less than\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | <=\n| style=\"border-bottom-style: none; border-top-style: none\" | Less than or equal to\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | >\n| style=\"border-bottom-style: none; border-top-style: none\" | Greater than\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | >=\n| style=\"border-bottom-style: none; border-top-style: none\" | Greater than or equal to\n|-\n! rowspan=2| 9\n| style=\"border-bottom-style: none\" | ==\n| style=\"border-bottom-style: none\" | Equal to\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | !=\n| style=\"border-bottom-style: none; border-top-style: none\" | Not equal to\n|-\n! 10\n| &\n| Bitwise AND\n|-\n! 11\n| ^\n| Bitwise XOR (exclusive or)\n|-\n! 12\n| |\n| Bitwise OR (inclusive or)\n|-\n! 13\n| &&\n| Logical AND\n|-\n! 14\n| ||\n| Logical OR\n|-\n! 15\n| ?:\n| [[wp:Ternary operator|Ternary]] conditional (see [[wp:?:|?:]])\n| style=\"vertical-align: top\" rowspan=\"12\" | Right-to-left\n|-\n! rowspan=11| 16\n| style=\"border-bottom-style: none\" | =\n| style=\"border-bottom-style: none\" | Direct assignment\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | +=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by sum\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | -=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by difference\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | *=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by product\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | /=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by quotient\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | %=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by remainder\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | <<=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by bitwise left shift\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | >>=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by bitwise right shift\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | &=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by bitwise AND\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | ^=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by bitwise XOR\n|-\n| style=\"border-bottom-style: none; border-top-style: none\" | |=\n| style=\"border-bottom-style: none; border-top-style: none\" | Assignment by bitwise OR\n|-\n! 17\n| throw\n| Throw operator (exceptions throwing, C++ only)\n|\n|-\n! 18\n| ,\n| [[wp:Comma operator|Comma]]\n| Left-to-right\n|}\n\nFor quick reference, see also [http://cpp.operator-precedence.com this] equivalent, color-coded table.\n\n"} {"title": "Padovan sequence", "language": "C++", "task": "The Fibonacci sequence in several ways.\nSome are given in the table below, and the referenced video shows some of the geometric\nsimilarities.\n\n::{| class=\"wikitable\"\n! Comment !! Padovan !! Fibonacci\n|-\n| || || \n|-\n| Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci\n|-\n| || || \n|-\n| Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1\n|-\n| Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2)\n|-\n| || || \n|-\n| First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34\n|-\n| || || \n|-\n| Ratio of successive terms... || Plastic ratio, p || Golden ratio, g\n|-\n| || 1.324717957244746025960908854... || 1.6180339887498948482...\n|-\n| Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2\n|-\n| Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1\n|-\n| || || \n|-\n| Spirally tiling the plane using. || Equilateral triangles || Squares\n|-\n| || || \n|-\n| Constants for ... || s= 1.0453567932525329623 || a=5**0.5\n|-\n| ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5)\n|-\n| || || \n|-\n| L-System Variables. || A,B,C || A,B\n|-\n| L-System Start/Axiom. || A || A\n|-\n| L-System Rules. || A->B,B->C,C->AB || A->B,B->AB\n|}\n\n;Task:\n* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.\n* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.\n* Show the first twenty terms of the sequence.\n* Confirm that the recurrence and floor based functions give the same results for 64 terms,\n* Write a function/method/... using the L-system to generate successive strings.\n* Show the first 10 strings produced from the L-system\n* Confirm that the length of the first 32 strings produced is the Padovan sequence.\n\nShow output here, on this page.\n\n;Ref:\n* The Plastic Ratio - Numberphile video.\n\n\n", "solution": "#include \n#include \n#include \n\n// Generate the Padovan sequence using the recurrence\n// relationship.\nint pRec(int n) {\n static std::map memo;\n auto it = memo.find(n);\n if (it != memo.end()) return it->second;\n\n if (n <= 2) memo[n] = 1;\n else memo[n] = pRec(n-2) + pRec(n-3);\n return memo[n];\n}\n\n// Calculate the N'th Padovan sequence using the\n// floor function.\nint pFloor(int n) {\n long const double p = 1.324717957244746025960908854;\n long const double s = 1.0453567932525329623;\n return std::pow(p, n-1)/s + 0.5;\n}\n\n// Return the N'th L-system string\nstd::string& lSystem(int n) {\n static std::map memo;\n auto it = memo.find(n);\n if (it != memo.end()) return it->second;\n \n if (n == 0) memo[n] = \"A\";\n else {\n memo[n] = \"\";\n for (char ch : memo[n-1]) {\n switch(ch) {\n case 'A': memo[n].push_back('B'); break;\n case 'B': memo[n].push_back('C'); break;\n case 'C': memo[n].append(\"AB\"); break;\n }\n }\n }\n return memo[n];\n}\n\n// Compare two functions up to p_N\nusing pFn = int(*)(int);\nvoid compare(pFn f1, pFn f2, const char* descr, int stop) {\n std::cout << \"The \" << descr << \" functions \";\n int i;\n for (i=0; i= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''1037''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''1037'''. \n\n\nA palindromic number is (for this task, a positive integer expressed in base ten), when the number is \nreversed, is the same as the original number.\n\n\n;Task:\n:* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with:\n:::* the digit '''1'''\n:::* the digit '''2'''\n:::* the digit '''3'''\n:::* the digit '''4'''\n:::* the digit '''5'''\n:::* the digit '''6'''\n:::* the digit '''7'''\n:::* the digit '''8'''\n:::* the digit '''9'''\n:* Show (nine sets, like above) of palindromic gapful numbers:\n:::* the last '''15''' palindromic gapful numbers (out of '''100''')\n:::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional}\n\n\nFor other ways of expressing the (above) requirements, see the ''discussion'' page.\n\n\n;Note:\nAll palindromic gapful numbers are divisible by eleven. \n\n\n;Related tasks:\n:* palindrome detection.\n:* gapful numbers.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n\n", "solution": "#include \n#include \n\ntypedef uint64_t integer;\n\ninteger reverse(integer n) {\n integer rev = 0;\n while (n > 0) {\n rev = rev * 10 + (n % 10);\n n /= 10;\n }\n return rev;\n}\n\n// generates base 10 palindromes greater than 100 starting\n// with the specified digit\nclass palindrome_generator {\npublic:\n palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),\n digit_(digit), even_(false) {}\n integer next_palindrome() {\n ++next_;\n if (next_ == power_ * (digit_ + 1)) {\n if (even_)\n power_ *= 10;\n next_ = digit_ * power_;\n even_ = !even_;\n }\n return next_ * (even_ ? 10 * power_ : power_)\n + reverse(even_ ? next_ : next_/10);\n }\nprivate:\n integer power_;\n integer next_;\n int digit_;\n bool even_;\n};\n\nbool gapful(integer n) {\n integer m = n;\n while (m >= 10)\n m /= 10;\n return n % (n % 10 + 10 * m) == 0;\n}\n\ntemplate\nvoid print(integer (&array)[9][len]) {\n for (int digit = 1; digit < 10; ++digit) {\n std::cout << digit << \":\";\n for (int i = 0; i < len; ++i)\n std::cout << ' ' << array[digit - 1][i];\n std::cout << '\\n';\n }\n}\n\nint main() {\n const int n1 = 20, n2 = 15, n3 = 10;\n const int m1 = 100, m2 = 1000;\n\n integer pg1[9][n1];\n integer pg2[9][n2];\n integer pg3[9][n3];\n\n for (int digit = 1; digit < 10; ++digit) {\n palindrome_generator pgen(digit);\n for (int i = 0; i < m2; ) {\n integer n = pgen.next_palindrome();\n if (!gapful(n))\n continue;\n if (i < n1)\n pg1[digit - 1][i] = n;\n else if (i < m1 && i >= m1 - n2)\n pg2[digit - 1][i - (m1 - n2)] = n;\n else if (i >= m2 - n3)\n pg3[digit - 1][i - (m2 - n3)] = n;\n ++i;\n }\n }\n\n std::cout << \"First \" << n1 << \" palindromic gapful numbers ending in:\\n\";\n print(pg1);\n\n std::cout << \"\\nLast \" << n2 << \" of first \" << m1 << \" palindromic gapful numbers ending in:\\n\";\n print(pg2);\n\n std::cout << \"\\nLast \" << n3 << \" of first \" << m2 << \" palindromic gapful numbers ending in:\\n\";\n print(pg3);\n\n return 0;\n}"} {"title": "Pancake numbers", "language": "C++", "task": "Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.\n\nThe task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.\n\n[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?\n\nFew people know p(20), generously I shall award an extra credit for anyone doing more than p(16).\n\n\n;References\n# Bill Gates and the pancake problem\n# A058986\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::vector flip_stack(std::vector& stack, const int32_t index) {\n\treverse(stack.begin(), stack.begin() + index);\n\treturn stack;\n}\n\nstd::pair, int32_t> pancake(const int32_t number) {\n\tstd::vector initial_stack(number);\n\tstd::iota(initial_stack.begin(), initial_stack.end(), 1);\n\tstd::map, int32_t> stack_flips = { std::make_pair(initial_stack, 1) };\n\tstd::queue> queue;\n\tqueue.push(initial_stack);\n\n\twhile ( ! queue.empty() ) {\n\t\tstd::vector stack = queue.front();\n\t\tqueue.pop();\n\n\t\tconst int32_t flips = stack_flips[stack] + 1;\n\t\tfor ( int i = 2; i <= number; ++i ) {\n\t\t\tstd::vector flipped = flip_stack(stack, i);\n\t\t\tif ( stack_flips.find(flipped) == stack_flips.end() ) {\n\t\t\t\tstack_flips[flipped] = flips;\n\t\t\t\tqueue.push(flipped);\n\t\t\t}\n\t\t}\n }\n\n\tauto ptr = std::max_element(\n\t\tstack_flips.begin(), stack_flips.end(),\n\t\t[] ( const auto & pair1, const auto & pair2 ) {\n\t \treturn pair1.second < pair2.second;\n\t\t}\n\t);\n\n\treturn std::make_pair(ptr->first, ptr->second);\n}\n\nint main() {\n\tfor ( int32_t n = 1; n <= 9; ++n ) {\n\t\tstd::pair, int32_t> result = pancake(n);\n\t\tstd::cout << \"pancake(\" << n << \") = \" << std::setw(2) << result.second << \". Example [\";\n\t\tfor ( uint64_t i = 0; i < result.first.size() - 1; ++i ) {\n\t\t\tstd::cout << result.first[i] << \", \";\n\t\t}\n\t\tstd::cout << result.first.back() << \"]\" << std::endl;\n\t}\n}\n"} {"title": "Pangram checker", "language": "C++", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: ''The quick brown fox jumps over the lazy dog''.\n\n\n;Task:\nWrite a function or method to check a sentence to see if it is a pangram (or not) and show its use.\n\n\n;Related tasks:\n:* determine if a string has all the same characters\n:* determine if a string has all unique characters\n\n", "solution": "#include \n#include \n#include \n#include \n\nconst std::string alphabet(\"abcdefghijklmnopqrstuvwxyz\");\n\nbool is_pangram(std::string s)\n{\n std::transform(s.begin(), s.end(), s.begin(), ::tolower);\n std::sort(s.begin(), s.end());\n return std::includes(s.begin(), s.end(), alphabet.begin(), alphabet.end());\n}\n\nint main()\n{\n const auto examples = {\"The quick brown fox jumps over the lazy dog\",\n \"The quick white cat jumps over the lazy dog\"};\n\n std::cout.setf(std::ios::boolalpha);\n for (auto& text : examples) {\n std::cout << \"Is \\\"\" << text << \"\\\" a pangram? - \" << is_pangram(text) << std::endl;\n }\n}\n"} {"title": "Parsing/RPN calculator algorithm", "language": "C++", "task": "Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.\n\n\n* Assume an input of a correct, space separated, string of tokens of an RPN expression\n* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: \n 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* '''^''' means exponentiation in the expression above.\n* '''/''' means division.\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* [[Parsing/RPN to infix conversion]].\n* [[Arithmetic evaluation]].\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble rpn(const std::string &expr){\n std::istringstream iss(expr);\n std::vector stack;\n std::cout << \"Input\\tOperation\\tStack after\" << std::endl;\n std::string token;\n while (iss >> token) {\n std::cout << token << \"\\t\";\n double tokenNum;\n if (std::istringstream(token) >> tokenNum) {\n std::cout << \"Push\\t\\t\";\n stack.push_back(tokenNum);\n } else {\n std::cout << \"Operate\\t\\t\";\n double secondOperand = stack.back();\n stack.pop_back();\n double firstOperand = stack.back();\n stack.pop_back();\n if (token == \"*\")\n\tstack.push_back(firstOperand * secondOperand);\n else if (token == \"/\")\n\tstack.push_back(firstOperand / secondOperand);\n else if (token == \"-\")\n\tstack.push_back(firstOperand - secondOperand);\n else if (token == \"+\")\n\tstack.push_back(firstOperand + secondOperand);\n else if (token == \"^\")\n\tstack.push_back(std::pow(firstOperand, secondOperand));\n else { //just in case\n\tstd::cerr << \"Error\" << std::endl;\n\tstd::exit(1);\n }\n }\n std::copy(stack.begin(), stack.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << std::endl;\n }\n return stack.back();\n}\n\nint main() {\n std::string s = \" 3 4 2 * 1 5 - 2 3 ^ ^ / + \";\n std::cout << \"Final answer: \" << rpn(s) << std::endl;\n \n return 0;\n}"} {"title": "Parsing/RPN to infix conversion", "language": "C++", "task": "Create a program that takes an infix notation.\n\n* Assume an input of a correct, space separated, string of tokens\n* Generate a space separated output string representing the same expression in infix notation\n* Show how the major datastructure of your algorithm changes with each new token parsed.\n* Test with the following input RPN strings then print and display the output here.\n:::::{| class=\"wikitable\"\n! RPN input !! sample output\n|- || align=\"center\"\n| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\n|- || align=\"center\"\n| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\n|}\n\n* Operator precedence and operator associativity is given in this table:\n::::::::{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\" \n| ^ || 4 || right || exponentiation\n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\" \n| - || 2 || left || subtraction\n|}\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* Postfix to infix from the RubyQuiz site.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n \nusing namespace std;\n \nstruct Entry_\n{\n\tstring expr_;\n\tstring op_;\n};\n \nbool PrecedenceLess(const string& lhs, const string& rhs, bool assoc)\n{\n\tstatic const map KNOWN({ { \"+\", 1 }, { \"-\", 1 }, { \"*\", 2 }, { \"/\", 2 }, { \"^\", 3 } });\n\tstatic const set ASSOCIATIVE({ \"+\", \"*\" });\n\treturn (KNOWN.count(lhs) ? KNOWN.find(lhs)->second : 0) < (KNOWN.count(rhs) ? KNOWN.find(rhs)->second : 0) + (assoc && !ASSOCIATIVE.count(rhs) ? 1 : 0);\n}\nvoid Parenthesize(Entry_* old, const string& token, bool assoc)\n{\n\tif (!old->op_.empty() && PrecedenceLess(old->op_, token, assoc))\n\t\told->expr_ = '(' + old->expr_ + ')';\n}\n \nvoid AddToken(stack* stack, const string& token)\n{\n\tif (token.find_first_of(\"0123456789\") != string::npos)\n\t\tstack->push(Entry_({ token, string() }));\t// it's a number, no operator\n\telse\n\t{\t// it's an operator\n\t\tif (stack->size() < 2)\n\t\t\tcout<<\"Stack underflow\";\n\t\tauto rhs = stack->top();\n\t\tParenthesize(&rhs, token, false);\n\t\tstack->pop();\n\t\tauto lhs = stack->top();\n\t\tParenthesize(&lhs, token, true);\n\t\tstack->top().expr_ = lhs.expr_ + ' ' + token + ' ' + rhs.expr_;\n\t\tstack->top().op_ = token;\n\t}\n}\n \n \nstring ToInfix(const string& src)\n{\n\tstack stack;\n\tfor (auto start = src.begin(), p = src.begin(); ; ++p)\n\t{\n\t\tif (p == src.end() || *p == ' ')\n\t\t{\n\t\t\tif (p > start)\n\t\t\t\tAddToken(&stack, string(start, p));\n\t\t\tif (p == src.end())\n\t\t\t\tbreak;\n\t\t\tstart = p + 1;\n\t\t}\n\t}\n\tif (stack.size() != 1)\n\t\tcout<<\"Incomplete expression\";\n\treturn stack.top().expr_;\n}\n \nint main(void)\n{\n\ttry\n\t{\n\t\tcout << ToInfix(\"3 4 2 * 1 5 - 2 3 ^ ^ / +\") << \"\\n\";\n\t\tcout << ToInfix(\"1 2 + 3 4 + ^ 5 6 + ^\") << \"\\n\";\n\t\treturn 0;\n\t}\n\tcatch (...)\n\t{\n\t\tcout << \"Failed\\n\";\n\t\treturn -1;\n\t}\n}\n"} {"title": "Parsing/Shunting-yard algorithm", "language": "C++", "task": "Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::vector;\nusing std::string;\n\n//-------------------------------------------------------------------------------------------------\n// throw error( \"You \", profanity, \"ed up!\" ); // Don't mess up, okay?\n//-------------------------------------------------------------------------------------------------\n#include \n#include \ntemplate std::runtime_error error( Args...args )\n{\n return std::runtime_error( (std::ostringstream{} << ... << args).str() );\n};\n\n//-------------------------------------------------------------------------------------------------\n// Stack\n//-------------------------------------------------------------------------------------------------\n// Let us co-opt a vector for our stack type.\n// C++ pedants: no splicing possible == totally okay to do this.\n//\n// Note: C++ provides a more appropriate std::stack class, except that the task requires us to\n// be able to display its contents, and that kind of access is an expressly non-stack behavior.\n\ntemplate struct stack : public std::vector \n{\n using base_type = std::vector ;\n T push ( const T& x ) { base_type::push_back( x ); return x; }\n const T& top () { return base_type::back(); }\n T pop () { T x = std::move( top() ); base_type::pop_back(); return x; }\n bool empty() { return base_type::empty(); }\n};\n\n//-------------------------------------------------------------------------------------------------\nusing Number = double;\n//-------------------------------------------------------------------------------------------------\n// Numbers are already too awesome to need extra diddling.\n\n//-------------------------------------------------------------------------------------------------\n// Operators\n//-------------------------------------------------------------------------------------------------\nusing Operator_Name = string;\nusing Precedence = int;\nenum class Associates { none, left_to_right, right_to_left };\n\nstruct Operator_Info { Precedence precedence; Associates associativity; };\n\nstd::unordered_map Operators =\n{\n { \"^\", { 4, Associates::right_to_left } },\n { \"*\", { 3, Associates::left_to_right } },\n { \"/\", { 3, Associates::left_to_right } },\n { \"+\", { 2, Associates::left_to_right } },\n { \"-\", { 2, Associates::left_to_right } },\n};\n\nPrecedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; }\nAssociates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }\n\n//-------------------------------------------------------------------------------------------------\nusing Token = string;\n//-------------------------------------------------------------------------------------------------\nbool is_number ( const Token& t ) { return regex_match( t, std::regex{ R\"z((\\d+(\\.\\d*)?|\\.\\d+)([Ee][\\+\\-]?\\d+)?)z\" } ); }\nbool is_operator ( const Token& t ) { return Operators.count( t ); }\nbool is_open_parenthesis ( const Token& t ) { return t == \"(\"; }\nbool is_close_parenthesis( const Token& t ) { return t == \")\"; }\nbool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }\n\n//-------------------------------------------------------------------------------------------------\n// std::cout << a_vector_of_something;\n//-------------------------------------------------------------------------------------------------\n// Weird C++ stream operator stuff (for I/O).\n// Don't worry if this doesn't look like it makes any sense.\n//\ntemplate std::ostream& operator << ( std::ostream& outs, const std::vector & xs )\n{\n std::size_t n = 0; for (auto x : xs) outs << (n++ ? \" \" : \"\") << x; return outs;\n}\n\n//-------------------------------------------------------------------------------------------------\n// Progressive_Display\n//-------------------------------------------------------------------------------------------------\n// This implements the required task:\n// \"use the algorithm to show the changes in the operator\n// stack and RPN output as each individual token is processed\"\n//\n#include \n\nstruct Progressive_Display\n{\n string token_name;\n string token_type;\n\n Progressive_Display() // Header for the table we are going to generate\n {\n std::cout << \"\\n\"\n \" INPUT \u2502 TYPE \u2502 ACTION \u2502 STACK \u2502 OUTPUT\\n\"\n \"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\\n\";\n }\n\n Progressive_Display& operator () ( const Token& token ) // Ready the first two columns\n {\n token_name = token;\n token_type = is_operator ( token ) ? \"op\"\n : is_parenthesis( token ) ? \"()\"\n : is_number ( token ) ? \"num\"\n : \"\";\n return *this;\n }\n\n Progressive_Display& operator () ( // Display all columns of a row\n const string & description,\n const stack & stack,\n const vector & output )\n {\n std::cout << std::right\n << std::setw( 7 ) << token_name << \" \u2502 \" << std::left\n << std::setw( 4 ) << token_type << \" \u2502 \"\n << std::setw( 16 ) << description << \" \u2502 \"\n << std::setw( 12 ) << (std::ostringstream{} << stack).str() << \" \u2502 \"\n << output << \"\\n\";\n return operator () ( \"\" ); // Reset the first two columns to empty for next iteration\n }\n};\n\n//-------------------------------------------------------------------------------------------------\nvector parse( const vector & tokens )\n//-------------------------------------------------------------------------------------------------\n{\n vector output;\n stack stack;\n\n Progressive_Display display;\n\n for (auto token : tokens) // Shunting Yard takes a single linear pass through the tokens\n\n //.........................................................................\n if (is_number( token ))\n {\n output.push_back( token );\n display( token )( \"num --> output\", stack, output );\n }\n\n //.........................................................................\n else if (is_operator( token ) or is_parenthesis( token ))\n {\n display( token );\n\n if (!is_open_parenthesis( token ))\n {\n // pop --> output\n // : until '(' if token is ')'\n // : while prec(token) > prec(top)\n // : while prec(token) == prec(top) AND assoc(token) is left-to-right\n while (!stack.empty()\n and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))\n or (precedence( stack.top() ) > precedence( token ))\n or ( (precedence( stack.top() ) == precedence( token ))\n and (associativity( token ) == Associates::left_to_right))))\n {\n output.push_back( stack.pop() );\n display( \"pop --> output\", stack, output );\n }\n\n // If we popped until '(' because token is ')', toss both parens\n if (is_close_parenthesis( token ))\n {\n stack.pop();\n display( \"pop\", stack, output );\n }\n }\n\n // Everything except ')' --> stack\n if (!is_close_parenthesis( token ))\n {\n stack.push( token );\n display( \"push op\", stack, output );\n }\n }\n\n //.........................................................................\n else throw error( \"unexpected token: \", token );\n\n // Anything left on the operator stack just gets moved to the output\n\n display( \"END\" );\n while (!stack.empty())\n {\n output.push_back( stack.pop() );\n display( \"pop --> output\", stack, output );\n }\n\n return output;\n}\n\n//-------------------------------------------------------------------------------------------------\nint main( int argc, char** argv )\n//-------------------------------------------------------------------------------------------------\ntry\n{\n auto tokens = vector ( argv+1, argv+argc );\n auto rpn_expr = parse( tokens );\n std::cout\n << \"\\nInfix = \" << tokens\n << \"\\nRPN = \" << rpn_expr\n << \"\\n\";\n}\ncatch (std::exception e)\n{\n std::cerr << \"error: \" << e.what() << \"\\n\";\n return 1;\n}"} {"title": "Parsing/Shunting-yard algorithm", "language": "C++ from Java", "task": "Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "#include \n#include \n#include \n\nstd::string infixToPostfix(const std::string& infix) {\n const std::string ops = \"-+/*^\";\n std::stringstream ss;\n std::stack s;\n\n std::stringstream input(infix);\n std::string token;\n while (std::getline(input, token, ' ')) {\n if (token.empty()) {\n continue;\n }\n\n char c = token[0];\n size_t idx = ops.find(c);\n\n // check for operator\n if (idx != std::string::npos) {\n while (!s.empty()) {\n int prec2 = s.top() / 2;\n int prec1 = idx / 2;\n if (prec2 > prec1 || (prec2 == prec1 && c != '^')) {\n ss << ops[s.top()] << ' ';\n s.pop();\n } else break;\n }\n s.push(idx);\n } else if (c == '(') {\n s.push(-2); // -2 stands for '('\n } else if (c == ')') {\n // until '(' on stack, pop operators.\n while (s.top() != -2) {\n ss << ops[s.top()] << ' ';\n s.pop();\n }\n s.pop();\n } else {\n ss << token << ' ';\n }\n }\n\n while (!s.empty()) {\n ss << ops[s.top()] << ' ';\n s.pop();\n }\n\n return ss.str();\n}\n\nint main() {\n std::string infix = \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\";\n std::cout << \"infix: \" << infix << '\\n';\n std::cout << \"postfix: \" << infixToPostfix(infix) << '\\n';\n\n return 0;\n}"} {"title": "Particle fountain", "language": "C++ from Raku", "task": "Implement a particle fountain.\n\nEmulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down.\n\nThe particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors.\n\nYour fountain should have at least several hundred particles in motion at any one time, and ideally several thousand.\n\nIt is optional to have the individual particle interact with each other.\n\nIf at all possible, link to a short video clip of your fountain in action.\n\nOff-site link to a demo video \n\n", "solution": "#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nauto now() {\n using namespace std::chrono;\n auto time = system_clock::now();\n return duration_cast(time.time_since_epoch()).count();\n}\n\nauto hsv_to_rgb(int h, double s, double v) {\n double hp = h / 60.0;\n double c = s * v;\n double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));\n double m = v - c;\n double r = 0, g = 0, b = 0;\n if (hp <= 1) {\n r = c;\n g = x;\n } else if (hp <= 2) {\n r = x;\n g = c;\n } else if (hp <= 3) {\n g = c;\n b = x;\n } else if (hp <= 4) {\n g = x;\n b = c;\n } else if (hp <= 5) {\n r = x;\n b = c;\n } else {\n r = c;\n b = x;\n }\n r += m;\n g += m;\n b += m;\n return std::make_tuple(Uint8(r * 255), Uint8(g * 255), Uint8(b * 255));\n}\n\nclass ParticleFountain {\npublic:\n ParticleFountain(int particles, int width, int height);\n void run();\n\nprivate:\n struct WindowDeleter {\n void operator()(SDL_Window* window) const { SDL_DestroyWindow(window); }\n };\n struct RendererDeleter {\n void operator()(SDL_Renderer* renderer) const {\n SDL_DestroyRenderer(renderer);\n }\n };\n struct PointInfo {\n double x = 0;\n double y = 0;\n double vx = 0;\n double vy = 0;\n double lifetime = 0;\n };\n\n void update(double df);\n bool handle_event();\n void render();\n double rand() { return dist_(rng_); }\n double reciprocate() const {\n return reciprocate_ ? range_ * std::sin(now() / 1000.0) : 0.0;\n }\n\n std::unique_ptr window_;\n std::unique_ptr renderer_;\n int width_;\n int height_;\n std::vector point_info_;\n std::vector points_;\n int num_points_ = 0;\n double saturation_ = 0.4;\n double spread_ = 1.5;\n double range_ = 1.5;\n bool reciprocate_ = false;\n std::mt19937 rng_;\n std::uniform_real_distribution<> dist_;\n};\n\nParticleFountain::ParticleFountain(int n, int width, int height)\n : width_(width), height_(height), point_info_(n), points_(n, {0, 0}),\n rng_(std::random_device{}()), dist_(0.0, 1.0) {\n window_.reset(SDL_CreateWindow(\n \"C++ Particle System!\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n width, height, SDL_WINDOW_RESIZABLE));\n if (window_ == nullptr)\n throw std::runtime_error(SDL_GetError());\n\n renderer_.reset(\n SDL_CreateRenderer(window_.get(), -1, SDL_RENDERER_ACCELERATED));\n if (renderer_ == nullptr)\n throw std::runtime_error(SDL_GetError());\n}\n\nvoid ParticleFountain::run() {\n for (double df = 0.0001;;) {\n auto start = now();\n if (!handle_event())\n break;\n update(df);\n render();\n df = (now() - start) / 1000.0;\n }\n}\n\nvoid ParticleFountain::update(double df) {\n int pointidx = 0;\n for (PointInfo& point : point_info_) {\n bool willdraw = false;\n if (point.lifetime <= 0.0) {\n if (rand() < df) {\n point.lifetime = 2.5;\n point.x = width_ / 20.0;\n point.y = height_ / 10.0;\n point.vx =\n (spread_ * rand() - spread_ / 2 + reciprocate()) * 10.0;\n point.vy = (rand() - 2.9) * height_ / 20.5;\n willdraw = true;\n }\n } else {\n if (point.y > height_ / 10.0 && point.vy > 0)\n point.vy *= -0.3;\n point.vy += (height_ / 10.0) * df;\n point.x += point.vx * df;\n point.y += point.vy * df;\n point.lifetime -= df;\n willdraw = true;\n }\n if (willdraw) {\n points_[pointidx].x = std::floor(point.x * 10.0);\n points_[pointidx].y = std::floor(point.y * 10.0);\n ++pointidx;\n }\n }\n num_points_ = pointidx;\n}\n\nbool ParticleFountain::handle_event() {\n bool result = true;\n SDL_Event event;\n while (result && SDL_PollEvent(&event)) {\n switch (event.type) {\n case SDL_QUIT:\n result = false;\n break;\n case SDL_WINDOWEVENT:\n if (event.window.event == SDL_WINDOWEVENT_RESIZED) {\n width_ = event.window.data1;\n height_ = event.window.data2;\n }\n break;\n case SDL_KEYDOWN:\n switch (event.key.keysym.scancode) {\n case SDL_SCANCODE_UP:\n saturation_ = std::min(saturation_ + 0.1, 1.0);\n break;\n case SDL_SCANCODE_DOWN:\n saturation_ = std::max(saturation_ - 0.1, 0.0);\n break;\n case SDL_SCANCODE_PAGEUP:\n spread_ = std::min(spread_ + 0.1, 5.0);\n break;\n case SDL_SCANCODE_PAGEDOWN:\n spread_ = std::max(spread_ - 0.1, 0.2);\n break;\n case SDL_SCANCODE_RIGHT:\n range_ = std::min(range_ + 0.1, 2.0);\n break;\n case SDL_SCANCODE_LEFT:\n range_ = std::max(range_ - 0.1, 0.1);\n break;\n case SDL_SCANCODE_SPACE:\n reciprocate_ = !reciprocate_;\n break;\n case SDL_SCANCODE_Q:\n result = false;\n break;\n default:\n break;\n }\n break;\n }\n }\n return result;\n}\n\nvoid ParticleFountain::render() {\n SDL_Renderer* renderer = renderer_.get();\n SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xff);\n SDL_RenderClear(renderer);\n auto [red, green, blue] = hsv_to_rgb((now() % 5) * 72, saturation_, 1);\n SDL_SetRenderDrawColor(renderer, red, green, blue, 0x7f);\n SDL_RenderDrawPoints(renderer, points_.data(), num_points_);\n SDL_RenderPresent(renderer);\n}\n\nint main() {\n std::cout << \"Use UP and DOWN arrow keys to modify the saturation of the \"\n \"particle colors.\\n\"\n \"Use PAGE UP and PAGE DOWN keys to modify the \\\"spread\\\" of \"\n \"the particles.\\n\"\n \"Toggle reciprocation off / on with the SPACE bar.\\n\"\n \"Use LEFT and RIGHT arrow keys to modify angle range for \"\n \"reciprocation.\\n\"\n \"Press the \\\"q\\\" key to quit.\\n\";\n\n if (SDL_Init(SDL_INIT_VIDEO) != 0) {\n std::cerr << \"ERROR: \" << SDL_GetError() << '\\n';\n return EXIT_FAILURE;\n }\n\n try {\n ParticleFountain pf(3000, 800, 800);\n pf.run();\n } catch (const std::exception& ex) {\n std::cerr << \"ERROR: \" << ex.what() << '\\n';\n SDL_Quit();\n return EXIT_FAILURE;\n }\n\n SDL_Quit();\n return EXIT_SUCCESS;\n}"} {"title": "Pascal's triangle/Puzzle", "language": "C++ from C", "task": "This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.\n\n [ 151]\n [ ][ ]\n [40][ ][ ]\n [ ][ ][ ][ ]\n [ X][11][ Y][ 4][ Z]\n\nEach brick of the pyramid is the sum of the two bricks situated below it.\nOf the three missing numbers at the base of the pyramid, \nthe middle one is the sum of the other two (that is, Y = X + Z).\n\n\n;Task:\nWrite a program to find a solution to this puzzle.\n\n", "solution": "#include \n#include \n\ninline int sign(int i) {\n return i < 0 ? -1 : i > 0;\n}\n\ninline int& E(int *x, int row, int col) {\n return x[row * (row + 1) / 2 + col];\n}\n\nint iter(int *v, int *diff) {\n // enforce boundary conditions\n E(v, 0, 0) = 151;\n E(v, 2, 0) = 40;\n E(v, 4, 1) = 11;\n E(v, 4, 3) = 4;\n\n // calculate difference from equilibrium\n for (auto i = 1u; i < 5u; i++)\n for (auto j = 0u; j <= i; j++) {\n E(diff, i, j) = 0;\n if (j < i)\n E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);\n if (j)\n E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);\n }\n\n for (auto i = 0u; i < 4u; i++)\n for (auto j = 0u; j < i; j++)\n E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);\n\n E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);\n\n // do feedback, check if we are done\n uint sum;\n int e = 0;\n for (auto i = sum = 0u; i < 15u; i++) {\n sum += !!sign(e = diff[i]);\n\n // 1/5-ish feedback strength on average. These numbers are highly magical, depending on nodes' connectivities\n if (e >= 4 || e <= -4)\n v[i] += e / 5;\n else if (rand() < RAND_MAX / 4)\n v[i] += sign(e);\n }\n return sum;\n}\n\nvoid show(int *x) {\n for (auto i = 0u; i < 5u; i++)\n for (auto j = 0u; j <= i; j++)\n std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\\n');\n}\n\nint main() {\n int v[15] = { 0 }, diff[15] = { 0 };\n for (auto i = 1u, s = 1u; s; i++) {\n s = iter(v, diff);\n std::cout << \"pass \" << i << \": \" << s << std::endl;\n }\n show(v);\n\n return 0;\n}"} {"title": "Password generator", "language": "C++", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a --> z\n upper-case letters: A --> Z\n digits: 0 --> 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include ''at least one'' (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), and \n one \"other\" character. \n\n\nThe user must be able to specify the password length and the number of passwords to generate. \n\nThe passwords should be displayed or written to a file, one per line.\n\nThe randomness should be from a system source or library. \n\nThe program should implement a help option or button which should describe the program and options when invoked. \n\nYou may also allow the user to specify a seed value, and give the option of excluding visually similar characters.\n\nFor example: Il1 O0 5S 2Z where the characters are: \n::::* capital eye, lowercase ell, the digit one\n::::* capital oh, the digit zero \n::::* the digit five, capital ess\n::::* the digit two, capital zee\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nconst std::string CHR[] = { \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"abcdefghijklmnopqrstuvwxyz\", \n \"0123456789\", \"!\\\"#$%&'()*+,-./:;<=>?@[]^_{|}~\" };\nconst std::string UNS = \"O0l1I5S2Z\";\n\nstd::string createPW( int len, bool safe ) {\n std::string pw;\n char t;\n for( int x = 0; x < len; x += 4 ) {\n for( int y = x; y < x + 4 && y < len; y++ ) {\n do {\n t = CHR[y % 4].at( rand() % CHR[y % 4].size() );\n } while( safe && UNS.find( t ) != UNS.npos );\n pw.append( 1, t );\n }\n }\n std::random_shuffle( pw.begin(), pw.end() );\n return pw;\n}\nvoid generate( int len, int count, bool safe ) {\n for( int c = 0; c < count; c++ ) {\n std::cout << createPW( len, safe ) << \"\\n\";\n }\n std::cout << \"\\n\\n\";\n}\nint main( int argc, char* argv[] ){\n if( argv[1][1] == '?' || argc < 5 ) {\n std::cout << \"Syntax: PWGEN length count safe seed /?\\n\"\n \"length:\\tthe length of the password(min 4)\\n\"\n \"count:\\thow many passwords should be generated\\n\"\n \"safe:\\t1 will exclude visually similar characters, 0 won't\\n\"\n \"seed:\\tnumber to seed the random generator or 0\\n\"\n \"/?\\tthis text\\n\\n\";\n } else {\n int l = atoi( argv[1] ),\n c = atoi( argv[2] ),\n e = atoi( argv[3] ), \n s = atoi( argv[4] );\n if( l < 4 ) {\n std::cout << \"Passwords must be at least 4 characters long.\\n\\n\";\n } else {\n if (s == 0) {\n std::srand( time( NULL ) );\n } else {\n std::srand( unsigned( s ) );\n }\n generate( l, c, e != 0 );\n }\n }\n return 0; \n}"} {"title": "Peaceful chess queen armies", "language": "C++ from D", "task": "In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.\n\n\n\n\n\\\n|\n/\n\n\n\n=\n=\n\n=\n=\n\n\n\n/\n|\n\\\n\n\n\n/\n\n|\n\n\\\n\n\n\n\n|\n\n\n\n\n\n\nThe goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.\n\n\n;Task:\n# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).\n# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.\n# Display here results for the m=4, n=5 case.\n\n\n;References:\n* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.\n* A250000 OEIS\n\n", "solution": "#include \n#include \n\nenum class Piece {\n empty,\n black,\n white\n};\n\ntypedef std::pair position;\n\nbool isAttacking(const position &queen, const position &pos) {\n return queen.first == pos.first\n || queen.second == pos.second\n || abs(queen.first - pos.first) == abs(queen.second - pos.second);\n}\n\nbool place(const int m, const int n, std::vector &pBlackQueens, std::vector &pWhiteQueens) {\n if (m == 0) {\n return true;\n }\n bool placingBlack = true;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n auto pos = std::make_pair(i, j);\n for (auto queen : pBlackQueens) {\n if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n goto inner;\n }\n }\n for (auto queen : pWhiteQueens) {\n if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n goto inner;\n }\n }\n if (placingBlack) {\n pBlackQueens.push_back(pos);\n placingBlack = false;\n } else {\n pWhiteQueens.push_back(pos);\n if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n return true;\n }\n pBlackQueens.pop_back();\n pWhiteQueens.pop_back();\n placingBlack = true;\n }\n\n inner: {}\n }\n }\n if (!placingBlack) {\n pBlackQueens.pop_back();\n }\n return false;\n}\n\nvoid printBoard(int n, const std::vector &blackQueens, const std::vector &whiteQueens) {\n std::vector board(n * n);\n std::fill(board.begin(), board.end(), Piece::empty);\n\n for (auto &queen : blackQueens) {\n board[queen.first * n + queen.second] = Piece::black;\n }\n for (auto &queen : whiteQueens) {\n board[queen.first * n + queen.second] = Piece::white;\n }\n\n for (size_t i = 0; i < board.size(); ++i) {\n if (i != 0 && i % n == 0) {\n std::cout << '\\n';\n }\n switch (board[i]) {\n case Piece::black:\n std::cout << \"B \";\n break;\n case Piece::white:\n std::cout << \"W \";\n break;\n case Piece::empty:\n default:\n int j = i / n;\n int k = i - j * n;\n if (j % 2 == k % 2) {\n std::cout << \"x \";\n } else {\n std::cout << \"* \";\n }\n break;\n }\n }\n\n std::cout << \"\\n\\n\";\n}\n\nint main() {\n std::vector nms = {\n {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},\n {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},\n {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},\n {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},\n };\n\n for (auto nm : nms) {\n std::cout << nm.second << \" black and \" << nm.second << \" white queens on a \" << nm.first << \" x \" << nm.first << \" board:\\n\";\n std::vector blackQueens, whiteQueens;\n if (place(nm.second, nm.first, blackQueens, whiteQueens)) {\n printBoard(nm.first, blackQueens, whiteQueens);\n } else {\n std::cout << \"No solution exists.\\n\\n\";\n }\n }\n\n return 0;\n}"} {"title": "Perfect shuffle", "language": "C++", "task": "A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:\n\n\n\n::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K\n\n\n\nWhen you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:\n\n\n\n::::: {| style=\"border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right\"\n|-\n| ''original:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|-\n| ''after 1st shuffle:'' ||\n1\n5\n2\n6\n3\n7\n4\n8\n|-\n| ''after 2nd shuffle:'' ||\n1\n3\n5\n7\n2\n4\n6\n8\n|-\n| ''after 3rd shuffle:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|}\n\n\n'''''The Task'''''\n\n# Write a function that can perform a perfect shuffle on an even-sized list of values.\n# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under \"Test Cases\" below.\n#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all \"cards\" are unique within each deck.\n#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.\n'''''Test Cases'''''\n\n::::: {| class=\"wikitable\"\n|-\n! input ''(deck size)'' !! output ''(number of shuffles required)''\n|-\n| 8 || 3\n|-\n| 24 || 11\n|-\n| 52 || 8\n|-\n| 100 || 30\n|-\n| 1020 || 1018\n|-\n| 1024 || 10\n|-\n| 10000 || 300\n|}\n\n", "solution": "#include \n#include \n#include \n\nint pShuffle( int t ) {\n std::vector v, o, r;\n\n for( int x = 0; x < t; x++ ) {\n o.push_back( x + 1 );\n }\n\n r = o;\n int t2 = t / 2 - 1, c = 1;\n\n while( true ) {\n v = r;\n r.clear();\n\n for( int x = t2; x > -1; x-- ) {\n r.push_back( v[x + t2 + 1] );\n r.push_back( v[x] );\n }\n\n std::reverse( r.begin(), r.end() );\n\n if( std::equal( o.begin(), o.end(), r.begin() ) ) return c;\n c++;\n }\n}\n\nint main() {\n int s[] = { 8, 24, 52, 100, 1020, 1024, 10000 };\n for( int x = 0; x < 7; x++ ) {\n std::cout << \"Cards count: \" << s[x] << \", shuffles required: \";\n std::cout << pShuffle( s[x] ) << \".\\n\";\n }\n return 0;\n}\n"} {"title": "Perfect totient numbers", "language": "C++", "task": "Generate and show here, the first twenty Perfect totient numbers.\n\n\n;Related task:\n::* [[Totient function]]\n\n\n;Also see:\n::* the OEIS entry for perfect totient numbers.\n::* mrob list of the first 54\n\n", "solution": "#include \n#include \n#include \n\nclass totient_calculator {\npublic:\n explicit totient_calculator(int max) : totient_(max + 1) {\n for (int i = 1; i <= max; ++i)\n totient_[i] = i;\n for (int i = 2; i <= max; ++i) {\n if (totient_[i] < i)\n continue;\n for (int j = i; j <= max; j += i)\n totient_[j] -= totient_[j] / i;\n }\n }\n int totient(int n) const {\n assert (n >= 1 && n < totient_.size());\n return totient_[n];\n }\n bool is_prime(int n) const {\n return totient(n) == n - 1;\n }\nprivate:\n std::vector totient_;\n};\n\nbool perfect_totient_number(const totient_calculator& tc, int n) {\n int sum = 0;\n for (int m = n; m > 1; ) {\n int t = tc.totient(m);\n sum += t;\n m = t;\n }\n return sum == n;\n}\n\nint main() {\n totient_calculator tc(10000);\n int count = 0, n = 1;\n std::cout << \"First 20 perfect totient numbers:\\n\";\n for (; count < 20; ++n) {\n if (perfect_totient_number(tc, n)) {\n if (count > 0)\n std::cout << ' ';\n ++count;\n std::cout << n;\n }\n }\n std::cout << '\\n';\n return 0;\n}"} {"title": "Permutations by swapping", "language": "C++", "task": "Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. \n\nAlso generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. \n\nShow the permutations and signs of three items, in order of generation ''here''.\n\nSuch data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.\n\nNote: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus-Johnson-Trotter algorithm\n* Johnson-Trotter Algorithm Listing All Permutations\n* Heap's algorithm\n* Tintinnalogia\n\n\n;Related tasks:\n* [[Matrix arithmetic]\n* [[Gray code]]\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\nvector UpTo(int n, int offset = 0)\n{\n\tvector retval(n);\n\tfor (int ii = 0; ii < n; ++ii)\n\t\tretval[ii] = ii + offset;\n\treturn retval;\n}\n\nstruct JohnsonTrotterState_\n{\n\tvector values_;\n\tvector positions_;\t// size is n+1, first element is not used\n\tvector directions_;\n\tint sign_;\n\n\tJohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}\n\n\tint LargestMobile() const\t// returns 0 if no mobile integer exists\n\t{\n\t\tfor (int r = values_.size(); r > 0; --r)\n\t\t{\n\t\t\tconst int loc = positions_[r] + (directions_[r] ? 1 : -1);\n\t\t\tif (loc >= 0 && loc < values_.size() && values_[loc] < r)\n\t\t\t\treturn r;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool IsComplete() const { return LargestMobile() == 0; }\n\n\tvoid operator++()\t// implement Johnson-Trotter algorithm\n\t{\n\t\tconst int r = LargestMobile();\n\t\tconst int rLoc = positions_[r];\n\t\tconst int lLoc = rLoc + (directions_[r] ? 1 : -1);\n\t\tconst int l = values_[lLoc];\n\t\t// do the swap\n\t\tswap(values_[lLoc], values_[rLoc]);\n\t\tswap(positions_[l], positions_[r]);\n\t\tsign_ = -sign_;\n\t\t// change directions\n\t\tfor (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)\n\t\t\t*pd = !*pd;\n\t}\n};\n\nint main(void)\n{\n\tJohnsonTrotterState_ state(4);\n\tdo\n\t{\n\t\tfor (auto v : state.values_)\n\t\t\tcout << v << \" \";\n\t\tcout << \"\\n\";\n\t\t++state;\n\t} while (!state.IsComplete());\n}\n"} {"title": "Phrase reversals", "language": "C++", "task": "Given a string of space separated words containing the following phrase:\n rosetta code phrase reversal\n\n:# Reverse the characters of the string.\n:# Reverse the characters of each individual word in the string, maintaining original word order within the string.\n:# Reverse the order of each word of the string, maintaining the order of characters in each word.\n\nShow your output here.\n \n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nint main() {\n std::string s = \"rosetta code phrase reversal\";\n std::cout << \"Input : \" << s << '\\n'\n << \"Input reversed : \" << std::string(s.rbegin(), s.rend()) << '\\n' ;\n std::istringstream is(s);\n std::vector words(std::istream_iterator(is), {});\n std::cout << \"Each word reversed : \" ;\n for(auto w : words)\n std::cout << std::string(w.rbegin(), w.rend()) << ' ';\n std::cout << '\\n'\n << \"Original word order reversed : \" ;\n reverse_copy(words.begin(), words.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << '\\n' ;\n}"} {"title": "Pig the dice game", "language": "C++", "task": "The game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach '''100''' points or more. \nPlay is taken in turns. On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.\n\n\n;Task:\nCreate a program to score for, and simulate dice throws for, a two-person game. \n\n\n;Related task:\n* [[Pig the dice game/Player]]\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nconst int PLAYERS = 2, MAX_POINTS = 100;\n\n//--------------------------------------------------------------------------------------------------\nclass player\n{\npublic:\n player() { reset(); }\n void reset()\n {\n\tname = \"\";\n\tcurrent_score = round_score = 0;\n }\n string getName() { return name; }\n void setName( string n ) { name = n; }\n int getCurrScore() { return current_score; }\n void addCurrScore() { current_score += round_score; }\n int getRoundScore() { return round_score; }\n void addRoundScore( int rs ) { round_score += rs; }\n void zeroRoundScore() { round_score = 0; }\n\nprivate:\n string name;\n int current_score, round_score;\n};\n//--------------------------------------------------------------------------------------------------\nclass pigGame\n{\npublic:\n pigGame() { resetPlayers(); }\n\n void play()\n {\n\twhile( true )\n\t{\n\t system( \"cls\" );\n\t int p = 0;\n\t while( true )\n\t {\n\t\tif( turn( p ) )\n\t\t{\n\t\t praise( p );\n\t\t break;\n\t\t}\n\n\t\t++p %= PLAYERS;\n\t }\n\n\t string r;\n\t cout << \"Do you want to play again ( y / n )? \"; cin >> r;\n\t if( r != \"Y\" && r != \"y\" ) return;\n\t resetPlayers();\n\t}\n }\n\nprivate:\n void resetPlayers()\n {\n\tsystem( \"cls\" );\n\tstring n;\n\tfor( int p = 0; p < PLAYERS; p++ )\n\t{\n\t _players[p].reset();\n\t cout << \"Enter name player \" << p + 1 << \": \"; cin >> n;\n\t _players[p].setName( n );\n\t}\n\n }\n\n void praise( int p )\n {\n\tsystem( \"cls\" );\n\tcout << \"CONGRATULATIONS \" << _players[p].getName() << \", you are the winner!\" << endl << endl;\n\tcout << \"Final Score\" << endl;\n\tdrawScoreboard();\n\tcout << endl << endl;\n }\n\n void drawScoreboard()\n {\n\tfor( int p = 0; p < PLAYERS; p++ )\n\t cout << _players[p].getName() << \": \" << _players[p].getCurrScore() << \" points\" << endl;\n\tcout << endl;\n }\n\n bool turn( int p )\n {\n\tsystem( \"cls\" );\n\tdrawScoreboard();\n\t_players[p].zeroRoundScore();\n\tstring r;\n\tint die;\n\twhile( true )\n\t{\n\t cout << _players[p].getName() << \", your round score is: \" << _players[p].getRoundScore() << endl;\n\t cout << \"What do you want to do (H)old or (R)oll? \"; cin >> r;\n\t if( r == \"h\" || r == \"H\" )\n\t {\n\t\t_players[p].addCurrScore();\n\t\treturn _players[p].getCurrScore() >= MAX_POINTS;\n\t }\n\t if( r == \"r\" || r == \"R\" )\n\t {\n\t\tdie = rand() % 6 + 1;\n\t\tif( die == 1 )\n\t\t{\n\t \t cout << _players[p].getName() << \", your turn is over.\" << endl << endl;\n\t\t system( \"pause\" );\n\t\t return false;\n\t\t}\n\t\t_players[p].addRoundScore( die );\n\t }\n\t cout << endl;\n\t}\n\treturn false;\n }\n\n player\t_players[PLAYERS];\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n srand( GetTickCount() );\n pigGame pg;\n pg.play();\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Pig the dice game/Player", "language": "C++", "task": "Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy.\n* State here the play strategies involved.\n* Show play during a game here.\n\n\nAs a stretch goal:\n* Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.\n\n\n;Game Rules:\nThe game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach 100 points or more.\nPlay is taken in turns. On each person's turn that person has the option of either\n\n# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n# '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.\n\n\n;References\n* Pig (dice)\n* The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nconst int PLAYERS = 4, MAX_POINTS = 100;\n\n//--------------------------------------------------------------------------------------------------\nenum Moves { ROLL, HOLD };\n\n//--------------------------------------------------------------------------------------------------\nclass player\n{\npublic:\n player() { current_score = round_score = 0; }\n void addCurrScore() { current_score += round_score; }\n int getCurrScore() { return current_score; }\n int getRoundScore() { return round_score; }\n void addRoundScore( int rs ) { round_score += rs; }\n void zeroRoundScore() { round_score = 0; }\n virtual int getMove() = 0;\n virtual ~player() {}\n\nprotected:\n int current_score, round_score;\n};\n//--------------------------------------------------------------------------------------------------\nclass RAND_Player : public player\n{\n virtual int getMove()\n {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( rand() % 10 < 5 ) return ROLL;\n\tif( round_score > 0 ) return HOLD;\n\treturn ROLL;\n }\n};\n//--------------------------------------------------------------------------------------------------\nclass Q2WIN_Player : public player\n{\n virtual int getMove()\n {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\t\t\n\tint q = MAX_POINTS - current_score;\n\tif( q < 6 ) return ROLL;\n\tq /= 4;\n\tif( round_score < q ) return ROLL;\n\treturn HOLD;\n }\n};\n//--------------------------------------------------------------------------------------------------\nclass AL20_Player : public player\n{\n virtual int getMove()\n {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tif( round_score < 20 ) return ROLL;\n\treturn HOLD;\n }\n};\n//--------------------------------------------------------------------------------------------------\nclass AL20T_Player : public player\n{\n virtual int getMove()\n {\n\tif( round_score + current_score >= MAX_POINTS ) return HOLD;\n\n\tint d = ( 100 * round_score ) / 20;\n\tif( round_score < 20 && d < rand() % 100 ) return ROLL;\n\treturn HOLD;\n }\n};\n//--------------------------------------------------------------------------------------------------\nclass Auto_pigGame\n{\npublic:\n Auto_pigGame() \n {\n\t_players[0] = new RAND_Player();\n\t_players[1] = new Q2WIN_Player();\n\t_players[2] = new AL20_Player();\n _players[3] = new AL20T_Player();\n }\n\n ~Auto_pigGame()\n {\n\tdelete _players[0];\n\tdelete _players[1];\n\tdelete _players[2];\n delete _players[3];\n }\n\n void play()\n {\n\tint die, p = 0;\n\tbool endGame = false;\n\n\twhile( !endGame )\n\t{\n\t switch( _players[p]->getMove() )\n\t {\n\t\tcase ROLL:\n\t \t die = rand() % 6 + 1;\n\t\t if( die == 1 )\n\t\t {\n\t\t\tcout << \"Player \" << p + 1 << \" rolled \" << die << \" - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t\tnextTurn( p );\n\t\t\tcontinue;\n\t\t }\n\t\t _players[p]->addRoundScore( die );\n\t\t cout << \"Player \" << p + 1 << \" rolled \" << die << \" - round score: \" << _players[p]->getRoundScore() << endl;\n\t\tbreak;\n\t\tcase HOLD:\n\t \t _players[p]->addCurrScore();\n\t\t cout << \"Player \" << p + 1 << \" holds - current score: \" << _players[p]->getCurrScore() << endl << endl;\n\t\t if( _players[p]->getCurrScore() >= MAX_POINTS )\n\t\t\tendGame = true;\n\t\t else nextTurn( p );\n\n\t }\n\t}\n\tshowScore();\n }\n\nprivate:\n void nextTurn( int& p )\n {\n\t_players[p]->zeroRoundScore();\n\t++p %= PLAYERS;\n }\n\n void showScore()\n {\n\tcout << endl;\n\tcout << \"Player I (RAND): \" << _players[0]->getCurrScore() << endl;\n\tcout << \"Player II (Q2WIN): \" << _players[1]->getCurrScore() << endl;\n cout << \"Player III (AL20): \" << _players[2]->getCurrScore() << endl;\n\tcout << \"Player IV (AL20T): \" << _players[3]->getCurrScore() << endl << endl << endl;\n\n\tsystem( \"pause\" );\n }\n\n player*\t_players[PLAYERS];\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n srand( GetTickCount() );\n Auto_pigGame pg;\n pg.play();\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Plasma effect", "language": "C++", "task": "The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.\n\n\n;Task\nCreate a plasma effect.\n\n\n;See also\n* Computer Graphics Tutorial (lodev.org)\n* Plasma (bidouille.org)\n\n", "solution": "#include \n#include \n#include \n\nconst int BMP_SIZE = 240, MY_TIMER = 987654;\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n DWORD* bits() { return ( DWORD* )pBits; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass plasma\n{\npublic:\n plasma() {\n currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;\n _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();\n plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];\n int i, j, dst = 0;\n double temp;\n for( j = 0; j < BMP_SIZE * 2; j++ ) {\n for( i = 0; i < BMP_SIZE * 2; i++ ) {\n plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );\n plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + \n ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );\n dst++;\n }\n }\n }\n void update() {\n DWORD dst;\n BYTE a, c1,c2, c3;\n currentTime += ( double )( rand() % 2 + 1 );\n\n int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ),\n x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ),\n x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),\n y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ),\n y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ),\n y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );\n\n int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;\n \n DWORD* bits = _bmp.bits();\n for( int j = 0; j < BMP_SIZE; j++ ) {\n dst = j * BMP_SIZE;\n for( int i= 0; i < BMP_SIZE; i++ ) {\n a = plasma2[src1] + plasma1[src2] + plasma2[src3];\n c1 = a << 1; c2 = a << 2; c3 = a << 3;\n bits[dst + i] = RGB( c1, c2, c3 );\n src1++; src2++; src3++;\n }\n src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;\n }\n draw();\n }\n void setHWND( HWND hwnd ) { _hwnd = hwnd; }\nprivate:\n void draw() {\n HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );\n BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n ReleaseDC( _hwnd, wdc );\n }\n myBitmap _bmp; HWND _hwnd; float _ang;\n BYTE *plasma1, *plasma2;\n double currentTime; int _WD, _WV;\n};\nclass wnd\n{\npublic:\n wnd() { _inst = this; }\n int wnd::Run( HINSTANCE hInst ) {\n _hInst = hInst; _hwnd = InitAll();\n SetTimer( _hwnd, MY_TIMER, 15, NULL );\n _plasma.setHWND( _hwnd );\n ShowWindow( _hwnd, SW_SHOW );\n UpdateWindow( _hwnd );\n MSG msg;\n ZeroMemory( &msg, sizeof( msg ) );\n while( msg.message != WM_QUIT ) {\n if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {\n TranslateMessage( &msg );\n DispatchMessage( &msg );\n }\n }\n return UnregisterClass( \"_MY_PLASMA_\", _hInst );\n }\nprivate:\n void wnd::doPaint( HDC dc ) { _plasma.update(); }\n void wnd::doTimer() { _plasma.update(); }\n static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {\n switch( msg ) {\n case WM_PAINT: {\n PAINTSTRUCT ps;\n _inst->doPaint( BeginPaint( hWnd, &ps ) );\n EndPaint( hWnd, &ps );\n return 0;\n }\n case WM_DESTROY: PostQuitMessage( 0 ); break;\n case WM_TIMER: _inst->doTimer(); break;\n default: return DefWindowProc( hWnd, msg, wParam, lParam );\n }\n return 0;\n }\n HWND InitAll() {\n WNDCLASSEX wcex;\n ZeroMemory( &wcex, sizeof( wcex ) );\n wcex.cbSize = sizeof( WNDCLASSEX );\n wcex.style = CS_HREDRAW | CS_VREDRAW;\n wcex.lpfnWndProc = ( WNDPROC )WndProc;\n wcex.hInstance = _hInst;\n wcex.hCursor = LoadCursor( NULL, IDC_ARROW );\n wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n wcex.lpszClassName = \"_MY_PLASMA_\";\n\n RegisterClassEx( &wcex );\n\n RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n int w = rc.right - rc.left, h = rc.bottom - rc.top;\n return CreateWindow( \"_MY_PLASMA_\", \".: Plasma -- PJorente :.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n }\n static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;\n};\nwnd* wnd::_inst = 0;\nint APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {\n wnd myWnd;\n return myWnd.Run( hInstance );\n}\n"} {"title": "Playfair cipher", "language": "C++", "task": "Implement a Playfair cipher for encryption and decryption.\n\n\nThe user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet.\n\nThe output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.\n\n\n;Output example:\n HI DE TH EG OL DI NT HE TR EX ES TU MP\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\nclass playfair\n{\npublic:\n void doIt( string k, string t, bool ij, bool e )\n {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n }\n\nprivate:\n void doIt( int dir )\n {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n }\n\n void display()\n {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t cout << *si; si++; cout << *si << \" \"; si++;\n\t if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n }\n\n char getChar( int a, int b )\n {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n }\n\n bool getCharPos( char l, int &a, int &b )\n {\n\tfor( int y = 0; y < 5; y++ )\n\t for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n }\n\n void getTextReady( string t, bool ij, bool e )\n {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t if( *si == 'J' && ij ) *si = 'I';\n\t else if( *si == 'Q' && !ij ) continue;\n\t _txt += *si;\n\t}\n\tif( e )\n\t{\n\t string ntxt = \"\"; size_t len = _txt.length();\n\t for( size_t x = 0; x < len; x += 2 )\n\t {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t ntxt += _txt[x + 1];\n\t\t}\n\t }\n\t _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n }\n\n void createGrid( string k, bool ij )\n {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n }\n\n string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n string key, i, txt; bool ij, e;\n cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n cout << \"Enter a en/decryption key: \"; getline( cin, key ); \n cout << \"I <-> J (Y/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n cout << \"Enter the text: \"; getline( cin, txt ); \n playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}"} {"title": "Plot coordinate pairs", "language": "C++", "task": "Plot a function represented as x, y numerical arrays.\n\nPost the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''):\n x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "#include \n#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nconst int HSTEP = 46, MWID = 40, MHEI = 471;\nconst float VSTEP = 2.3f;\n\n//--------------------------------------------------------------------------------------------------\nclass vector2\n{\npublic:\n vector2() { x = y = 0; }\n vector2( float a, float b ) { x = a; y = b; }\n void set( float a, float b ) { x = a; y = b; }\n float x, y;\n};\n//--------------------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n }\n\n bool create( int w, int h )\n {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes = 1;\n\tbi.bmiHeader.biWidth = w;\n\tbi.bmiHeader.biHeight = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n }\n\n void clear( BYTE clr = 0 )\n {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n\n void setBrushColor( DWORD bClr )\n {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n }\n\n void setPenColor( DWORD c ) { clr = c; createPen(); }\n\n void setPenWidth( int w ) { wid = w; createPen(); }\n\n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO infoheader;\n\tBITMAP bitmap;\n\tDWORD wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n }\n\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n\nprivate:\n void createPen()\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n }\n\n HBITMAP bmp;\n HDC hdc;\n HPEN pen;\n HBRUSH brush;\n void *pBits;\n int width, height, wid;\n DWORD clr;\n};\n//--------------------------------------------------------------------------------------------------\nclass plot\n{\npublic:\n plot() { bmp.create( 512, 512 ); }\n\n void draw( vector* pairs )\n {\n\tbmp.clear( 0xff );\n\tdrawGraph( pairs );\n\tplotIt( pairs );\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tBitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\tReleaseDC( GetConsoleWindow(), dc );\n\t//bmp.saveBitmap( \"f:\\\\rc\\\\plot.bmp\" );\n }\n\nprivate:\n void drawGraph( vector* pairs )\n {\n\tHDC dc = bmp.getDC();\n\tbmp.setPenColor( RGB( 240, 240, 240 ) );\n\tDWORD b = 11, c = 40, x; \n\tRECT rc; char txt[8];\n\n\tfor( x = 0; x < pairs->size(); x++ )\n\t{\n\t MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );\n\t MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );\n\n\t wsprintf( txt, \"%d\", ( pairs->size() - x ) * 20 );\n\t SetRect( &rc, 0, b - 9, 36, b + 11 );\n\t DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\t wsprintf( txt, \"%d\", x );\n\t SetRect( &rc, c - 8, 472, c + 8, 492 );\n\t DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );\n\n\t c += 46; b += 46;\n\t}\n\n\tSetRect( &rc, 0, b - 9, 36, b + 11 );\n\tDrawText( dc, \"0\", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );\n\n\tbmp.setPenColor( 0 ); bmp.setPenWidth( 3 );\n\tMoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );\n\tMoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );\n }\n\n void plotIt( vector* pairs )\n {\t\n\tHDC dc = bmp.getDC();\n\tHBRUSH br = CreateSolidBrush( 255 );\n\tRECT rc;\n\t\t\n\tbmp.setPenColor( 255 ); bmp.setPenWidth( 2 );\n\tvector::iterator it = pairs->begin();\n\tint a = MWID + HSTEP * static_cast( ( *it ).x ), b = MHEI - static_cast( VSTEP * ( *it ).y );\n\tMoveToEx( dc, a, b, NULL );\n\tSetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );\n\n\tit++;\n\tfor( ; it < pairs->end(); it++ )\n\t{\n\t a = MWID + HSTEP * static_cast( ( *it ).x );\n\t b = MHEI - static_cast( VSTEP * ( *it ).y );\n\t SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );\n\t FillRect( dc, &rc, br ); LineTo( dc, a, b );\n\t}\n\n\tDeleteObject( br );\n }\n\n myBitmap bmp;\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n plot pt;\n vector pairs;\n pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );\n pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );\n pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );\n pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );\n pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );\n\t\n pt.draw( &pairs );\n system( \"pause\" );\n\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Poker hand analyser", "language": "C++", "task": "Create a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' (two of diamonds).\n\n\n\nFaces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or \nalternatively, the unicode card-suit characters: \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2 2 2 k q: three-of-a-kind\n 2 5 7 8 9: high-card\n a 2 3 4 5: straight\n 2 3 2 3 3: full-house\n 2 7 2 3 3: two-pair\n 2 7 7 7 7: four-of-a-kind \n 10 j q k a: straight-flush\n 4 4 k 5 10: one-pair\n q 10 7 6 q: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2 2 k q: three-of-a-kind\n joker 5 7 8 9: straight\n joker 2 3 4 5: straight\n joker 3 2 3 3: four-of-a-kind\n joker 7 2 3 3: three-of-a-kind\n joker 7 7 7 7: five-of-a-kind\n joker j q k A: straight-flush\n joker 4 k 5 10: one-pair\n joker k 7 6 4: flush\n joker 2 joker 4 5: straight\n joker Q joker A 10: straight\n joker Q joker A 10: straight-flush\n joker 2 2 joker q: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\n\nclass poker\n{\npublic:\n poker() { face = \"A23456789TJQK\"; suit = \"SHCD\"; }\n string analyze( string h )\n {\n\tmemset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector hand;\n\ttransform( h.begin(), h.end(), h.begin(), toupper ); istringstream i( h );\n\tcopy( istream_iterator( i ), istream_iterator(), back_inserter >( hand ) );\n\tif( hand.size() != 5 ) return \"invalid hand.\"; vector::iterator it = hand.begin();\n\tsort( it, hand.end() ); if( hand.end() != adjacent_find( it, hand.end() ) ) return \"invalid hand.\";\n\twhile( it != hand.end() )\n\t{\n\t if( ( *it ).length() != 2 ) return \"invalid hand.\";\n\t int n = face.find( ( *it ).at( 0 ) ), l = suit.find( ( *it ).at( 1 ) );\n\t if( n < 0 || l < 0 ) return \"invalid hand.\";\n\t faceCnt[n]++; suitCnt[l]++; it++;\n\t}\n\tcout << h << \": \"; return analyzeHand();\n }\nprivate:\n string analyzeHand()\n {\n\tbool p1 = false, p2 = false, t = false, f = false, fl = false, st = false;\n\tfor( int x = 0; x < 13; x++ )\n\t switch( faceCnt[x] )\n\t {\n\t\tcase 2: if( p1 ) p2 = true; else p1 = true; break;\n\t\tcase 3: t = true; break;\n\t\tcase 4: f = true;\n\t }\n\tfor( int x = 0; x < 4; x++ )if( suitCnt[x] == 5 ){ fl = true; break; }\n\n\tif( !p1 && !p2 && !t && !f )\n {\n\t int s = 0;\n\t for( int x = 0; x < 13; x++ )\n\t { \n\t\tif( faceCnt[x] ) s++; else s = 0;\n\t\tif( s == 5 ) break;\n\t }\n\t st = ( s == 5 ) || ( s == 4 && faceCnt[0] && !faceCnt[1] );\n\t}\n\n\tif( st && fl ) return \"straight-flush\";\n\telse if( f ) return \"four-of-a-kind\"; \n\telse if( p1 && t ) return \"full-house\";\n\telse if( fl ) return \"flush\";\n\telse if( st ) return \"straight\";\n\telse if( t ) return \"three-of-a-kind\";\n\telse if( p1 && p2 ) return \"two-pair\";\n\telse if( p1 ) return \"one-pair\";\n return \"high-card\";\n }\n string face, suit;\n unsigned char faceCnt[13], suitCnt[4];\n};\n\nint main( int argc, char* argv[] )\n{\n poker p; \n cout << p.analyze( \"2h 2d 2s ks qd\" ) << endl; cout << p.analyze( \"2h 5h 7d 8s 9d\" ) << endl;\n cout << p.analyze( \"ah 2d 3s 4s 5s\" ) << endl; cout << p.analyze( \"2h 3h 2d 3s 3d\" ) << endl;\n cout << p.analyze( \"2h 7h 2d 3s 3d\" ) << endl; cout << p.analyze( \"2h 7h 7d 7s 7c\" ) << endl;\n cout << p.analyze( \"th jh qh kh ah\" ) << endl; cout << p.analyze( \"4h 4c kc 5d tc\" ) << endl;\n cout << p.analyze( \"qc tc 7c 6c 4c\" ) << endl << endl; return system( \"pause\" );\n}\n"} {"title": "Polyspiral", "language": "C++", "task": "A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. \n\n\n;Task\nAnimate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.\n\nIf animation is not practical in your programming environment, you may show a single frame instead.\n\n\n;Pseudo code\n\n set incr to 0.0\n\n // animation loop\n WHILE true \n\n incr = (incr + 0.05) MOD 360\n x = width / 2\n y = height / 2\n length = 5\n angle = incr\n\n // spiral loop\n FOR 1 TO 150\n drawline\n change direction by angle\n length = length + 3\n angle = (angle + incr) MOD 360\n ENDFOR\n \n\n\n", "solution": "#include \n#include \n#include \n\nconst float PI = 3.1415926536f, TWO_PI = 2.f * PI;\nclass vector2\n{\npublic:\n vector2( float a = 0, float b = 0 ) { set( a, b ); }\n void set( float a, float b ) { x = a; y = b; }\n void rotate( float r ) {\n float _x = x, _y = y,\n s = sinf( r ), c = cosf( r ),\n a = _x * c - _y * s, b = _x * s + _y * c;\n x = a; y = b;\n }\n vector2 add( const vector2& v ) {\n x += v.x; y += v.y;\n return *this;\n }\n float x, y;\n};\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap(){\n DeleteObject( pen );\n DeleteObject( brush );\n DeleteDC( hdc );\n DeleteObject( bmp );\n }\n bool create( int w, int h ){\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ){\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ){\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ){\n clr = c; createPen();\n }\n void setPenWidth( int w ){\n wid = w; createPen();\n }\n void saveBitmap( std::string path ){\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n \n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n \n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n \n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n \n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n \n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n \n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen(){\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nint main( int argc, char* argv[] ) {\n srand( unsigned( time( 0 ) ) );\n myBitmap bmp;\n bmp.create( 600, 600 ); bmp.clear();\n HDC dc = bmp.getDC();\n float fs = ( TWO_PI ) / 100.f;\n int index = 0;\n std::string a = \"f://users//images//test\", b;\n float ang, len;\n vector2 p1, p2;\n\n for( float step = 0.1f; step < 5.1f; step += .05f ) {\n ang = 0; len = 2;\n p1.set( 300, 300 );\n bmp.setPenColor( RGB( rand() % 50 + 200, rand() % 300 + 220, rand() % 50 + 200 ) );\n for( float xx = 0; xx < TWO_PI; xx += fs ) {\n MoveToEx( dc, (int)p1.x, (int)p1.y, NULL );\n p2.set( 0, len ); p2.rotate( ang ); p2.add( p1 );\n LineTo( dc, (int)p2.x, (int)p2.y );\n p1 = p2; ang += step; len += step;\n }\n std::ostringstream ss; ss << index++;\n b = a + ss.str() + \".bmp\";\n bmp.saveBitmap( b );\n bmp.clear();\n }\n return 0;\n}\n"} {"title": "Population count", "language": "C++11", "task": "The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.\n\n''Population count'' is also known as:\n::::* ''pop count''\n::::* ''popcount'' \n::::* ''sideways sum''\n::::* ''bit summation'' \n::::* ''Hamming weight'' \n\n\nFor example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.\n\n\n''Evil numbers'' are non-negative integers that have an ''even'' population count.\n\n''Odious numbers'' are positive integers that have an ''odd'' population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with '''0''' (zero indexed).\n:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').\n:* display the 1st thirty ''evil'' numbers.\n:* display the 1st thirty ''odious'' numbers.\n* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.\n\n", "solution": "#include \n#include \n#include \n\nsize_t popcount(unsigned long long n) {\n return std::bitset(n).count();\n}\n\nint main() {\n {\n unsigned long long n = 1;\n for (int i = 0; i < 30; i++) {\n std::cout << popcount(n) << \" \";\n n *= 3;\n }\n std::cout << std::endl;\n }\n\n int od[30];\n int ne = 0, no = 0;\n std::cout << \"evil : \";\n for (int n = 0; ne+no < 60; n++) {\n if ((popcount(n) & 1) == 0) {\n if (ne < 30) {\n\tstd::cout << n << \" \";\n\tne++;\n }\n } else {\n if (no < 30) {\n\tod[no++] = n;\n }\n }\n }\n std::cout << std::endl;\n std::cout << \"odious: \";\n for (int i = 0; i < 30; i++) {\n std::cout << od[i] << \" \";\n }\n std::cout << std::endl;\n\n return 0;\n}"} {"title": "Prime triangle", "language": "C++", "task": "You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.\n\n\n;See also\n:* OEIS:A036440\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nbool is_prime(unsigned int n) {\n assert(n > 0 && n < 64);\n return (1ULL << n) & 0x28208a20a08a28ac;\n}\n\ntemplate \nbool prime_triangle_row(Iterator begin, Iterator end) {\n if (std::distance(begin, end) == 2)\n return is_prime(*begin + *(begin + 1));\n for (auto i = begin + 1; i + 1 != end; ++i) {\n if (is_prime(*begin + *i)) {\n std::iter_swap(i, begin + 1);\n if (prime_triangle_row(begin + 1, end))\n return true;\n std::iter_swap(i, begin + 1);\n }\n }\n return false;\n}\n\ntemplate \nvoid prime_triangle_count(Iterator begin, Iterator end, int& count) {\n if (std::distance(begin, end) == 2) {\n if (is_prime(*begin + *(begin + 1)))\n ++count;\n return;\n }\n for (auto i = begin + 1; i + 1 != end; ++i) {\n if (is_prime(*begin + *i)) {\n std::iter_swap(i, begin + 1);\n prime_triangle_count(begin + 1, end, count);\n std::iter_swap(i, begin + 1);\n }\n }\n}\n\ntemplate \nvoid print(Iterator begin, Iterator end) {\n if (begin == end)\n return;\n auto i = begin;\n std::cout << std::setw(2) << *i++;\n for (; i != end; ++i)\n std::cout << ' ' << std::setw(2) << *i;\n std::cout << '\\n';\n}\n\nint main() {\n auto start = std::chrono::high_resolution_clock::now();\n for (unsigned int n = 2; n < 21; ++n) {\n std::vector v(n);\n std::iota(v.begin(), v.end(), 1);\n if (prime_triangle_row(v.begin(), v.end()))\n print(v.begin(), v.end());\n }\n std::cout << '\\n';\n for (unsigned int n = 2; n < 21; ++n) {\n std::vector v(n);\n std::iota(v.begin(), v.end(), 1);\n int count = 0;\n prime_triangle_count(v.begin(), v.end(), count);\n if (n > 2)\n std::cout << ' ';\n std::cout << count;\n }\n std::cout << '\\n';\n auto end = std::chrono::high_resolution_clock::now();\n std::chrono::duration duration(end - start);\n std::cout << \"\\nElapsed time: \" << duration.count() << \" seconds\\n\";\n}"} {"title": "Priority queue", "language": "C++", "task": "A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.\n\n\n;Task:\nCreate a priority queue. The queue must support at least two operations:\n:# Insertion. An element is added to the queue with a priority (a numeric value).\n:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.\n\n\nOptionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.\n\n\nTo test your implementation, insert a number of elements into the queue, each with some random priority. \n\nThen dequeue them sequentially; now the elements should be sorted by priority. \n\nYou can use the following task/priority items as input data:\n '''Priority''' '''Task'''\n ---------- ----------------\n 3 Clear drains\n 4 Feed cat\n 5 Make tea\n 1 Solve RC tasks\n 2 Tax return\n\n\nThe implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. \n\nYou may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.\n\n", "solution": "#include \n#include \n#include \n#include \n\nint main() {\n std::priority_queue > pq;\n pq.push(std::make_pair(3, \"Clear drains\"));\n pq.push(std::make_pair(4, \"Feed cat\"));\n pq.push(std::make_pair(5, \"Make tea\"));\n pq.push(std::make_pair(1, \"Solve RC tasks\"));\n pq.push(std::make_pair(2, \"Tax return\"));\n\n while (!pq.empty()) {\n std::cout << pq.top().first << \", \" << pq.top().second << std::endl;\n pq.pop();\n }\n\n return 0;\n}"} {"title": "Pseudo-random numbers/Combined recursive generator MRG32k3a", "language": "C++ from C", "task": "MRG32k3a Combined recursive generator (pseudo-code):\n\n /* Constants */\n /* First generator */\n a1 = [0, 1403580, -810728]\n m1 = 2**32 - 209\n /* Second Generator */\n a2 = [527612, 0, -1370589]\n m2 = 2**32 - 22853\n \n d = m1 + 1\n \n class MRG32k3a\n x1 = [0, 0, 0] /* list of three last values of gen #1 */\n x2 = [0, 0, 0] /* list of three last values of gen #2 */\n \n method seed(u64 seed_state)\n assert seed_state in range >0 and < d \n x1 = [seed_state, 0, 0]\n x2 = [seed_state, 0, 0]\n end method\n \n method next_int()\n x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1\n x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2\n x1 = [x1i, x1[0], x1[1]] /* Keep last three */\n x2 = [x2i, x2[0], x2[1]] /* Keep last three */\n z = (x1i - x2i) % m1\n answer = (z + 1)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / d\n end method\n \n end class\n \n:MRG32k3a Use:\n random_gen = instance MRG32k3a\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 1459213977 */\n print(random_gen.next_int()) /* 2827710106 */\n print(random_gen.next_int()) /* 4245671317 */\n print(random_gen.next_int()) /* 3877608661 */\n print(random_gen.next_int()) /* 2595287583 */\n \n \n;Task\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers generated with the seed `1234567`\nare as shown above \n\n* Show that for an initial seed of '987654321' the counts of 100_000\nrepetitions of\n\n floor(random_gen.next_float() * 5)\n\nIs as follows:\n \n 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931\n\n* Show your output here, on this page.\n\n\n", "solution": "#include \n#include \n\nint64_t mod(int64_t x, int64_t y) {\n int64_t m = x % y;\n if (m < 0) {\n if (y < 0) {\n return m - y;\n } else {\n return m + y;\n }\n }\n return m;\n}\n\nclass RNG {\nprivate:\n // First generator\n const std::array a1{ 0, 1403580, -810728 };\n const int64_t m1 = (1LL << 32) - 209;\n std::array x1;\n // Second generator\n const std::array a2{ 527612, 0, -1370589 };\n const int64_t m2 = (1LL << 32) - 22853;\n std::array x2;\n // other\n const int64_t d = (1LL << 32) - 209 + 1; // m1 + 1\n\npublic:\n void seed(int64_t state) {\n x1 = { state, 0, 0 };\n x2 = { state, 0, 0 };\n }\n\n int64_t next_int() {\n int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);\n int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);\n int64_t z = mod(x1i - x2i, m1);\n\n // keep last three values of the first generator\n x1 = { x1i, x1[0], x1[1] };\n // keep last three values of the second generator\n x2 = { x2i, x2[0], x2[1] };\n\n return z + 1;\n }\n\n double next_float() {\n return static_cast(next_int()) / d;\n }\n};\n\nint main() {\n RNG rng;\n\n rng.seed(1234567);\n std::cout << rng.next_int() << '\\n';\n std::cout << rng.next_int() << '\\n';\n std::cout << rng.next_int() << '\\n';\n std::cout << rng.next_int() << '\\n';\n std::cout << rng.next_int() << '\\n';\n std::cout << '\\n';\n\n std::array counts{ 0, 0, 0, 0, 0 };\n rng.seed(987654321);\n for (size_t i = 0; i < 100000; i++) \t\t{\n auto value = floor(rng.next_float() * 5.0);\n counts[value]++;\n }\n for (size_t i = 0; i < counts.size(); i++) \t\t{\n std::cout << i << \": \" << counts[i] << '\\n';\n }\n\n return 0;\n}"} {"title": "Pseudo-random numbers/Middle-square method", "language": "C++", "task": "{{Wikipedia|Middle-square method|en}}\n; The Method:\nTo generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. \n; Pseudo code:\n\nvar seed = 675248\nfunction random()\n var s = str(seed * seed) 'str: turn a number into string\n do while not len(s) = 12\n s = \"0\" + s 'add zeroes before the string\n end do\n seed = val(mid(s, 4, 6)) 'mid: string variable, start, length\n 'val: turn a string into number\n return seed\nend function\n\n; Middle-square method use:\n\nfor i = 1 to 5\n print random()\nend for\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers (6 digits) as shown above.\n\n* Show the first five integers generated with the seed 675248 as shown above.\n\n* Show your output here, on this page.\n\n", "solution": "#include \n#include \n\nusing ulong = unsigned long;\n\nclass MiddleSquare {\nprivate:\n ulong state;\n ulong div, mod;\npublic:\n MiddleSquare() = delete;\n MiddleSquare(ulong start, ulong length) {\n if (length % 2) throw std::invalid_argument(\"length must be even\");\n div = mod = 1;\n for (ulong i=0; i>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n:'''|''' Bitwise or operator\n::https://en.wikipedia.org/wiki/Bitwise_operation#OR\n::Bitwise comparison gives 1 if any of corresponding bits are 1\n:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111\n\n\n;PCG32 Generator (pseudo-code):\n\nPCG32 has two unsigned 64-bit integers of internal state:\n# '''state''': All 2**64 values may be attained.\n# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).\n\nValues of sequence allow 2**63 ''different'' sequences of random numbers from the same state.\n\nThe algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-\n\nconst N<-U64 6364136223846793005\nconst inc<-U64 (seed_sequence << 1) | 1\nstate<-U64 ((inc+seed_state)*N+inc\ndo forever\n xs<-U32 (((state>>18)^state)>>27)\n rot<-INT (state>>59)\n OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))\n state<-state*N+inc\nend do\n\nNote that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers using the above.\n\n* Show that the first five integers generated with the seed 42, 54\nare: 2707161783 2068313097 3122475824 2211639955 3215226955\n\n \n\n* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005\n\n* Show your output here, on this page.\n\n\n", "solution": "#include \n#include \n\nclass PCG32 {\nprivate:\n const uint64_t N = 6364136223846793005;\n uint64_t state = 0x853c49e6748fea9b;\n uint64_t inc = 0xda3e39cb94b95bdb;\npublic:\n uint32_t nextInt() {\n uint64_t old = state;\n state = old * N + inc;\n uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);\n uint32_t rot = old >> 59;\n return (shifted >> rot) | (shifted << ((~rot + 1) & 31));\n }\n\n double nextFloat() {\n return ((double)nextInt()) / (1LL << 32);\n }\n\n void seed(uint64_t seed_state, uint64_t seed_sequence) {\n state = 0;\n inc = (seed_sequence << 1) | 1;\n nextInt();\n state = state + seed_state;\n nextInt();\n }\n};\n\nint main() {\n auto r = new PCG32();\n\n r->seed(42, 54);\n std::cout << r->nextInt() << '\\n';\n std::cout << r->nextInt() << '\\n';\n std::cout << r->nextInt() << '\\n';\n std::cout << r->nextInt() << '\\n';\n std::cout << r->nextInt() << '\\n';\n std::cout << '\\n';\n\n std::array counts{ 0, 0, 0, 0, 0 };\n r->seed(987654321, 1);\n for (size_t i = 0; i < 100000; i++) {\n int j = (int)floor(r->nextFloat() * 5.0);\n counts[j]++;\n }\n\n std::cout << \"The counts for 100,000 repetitions are:\\n\";\n for (size_t i = 0; i < counts.size(); i++) {\n std::cout << \" \" << i << \" : \" << counts[i] << '\\n';\n }\n\n return 0;\n}"} {"title": "Pseudo-random numbers/Xorshift star", "language": "C++ from C", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n;Xorshift_star Generator (pseudo-code):\n\n /* Let u64 denote an unsigned 64 bit integer type. */\n /* Let u32 denote an unsigned 32 bit integer type. */\n \n class Xorshift_star\n u64 state /* Must be seeded to non-zero initial value */\n u64 const = HEX '2545F4914F6CDD1D'\n \n method seed(u64 num):\n state = num\n end method\n \n method next_int():\n u64 x = state\n x = x ^ (x >> 12)\n x = x ^ (x << 25)\n x = x ^ (x >> 27)\n state = x\n u32 answer = ((x * const) >> 32)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / (1 << 32)\n end method\n \n end class\n \n:;Xorshift use:\n\n random_gen = instance Xorshift_star\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 3540625527 */\n print(random_gen.next_int()) /* 2750739987 */\n print(random_gen.next_int()) /* 4037983143 */\n print(random_gen.next_int()) /* 1993361440 */\n print(random_gen.next_int()) /* 3809424708 */\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers genrated with the seed 1234567\nare as shown above \n\n* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007\n\n* Show your output here, on this page.\n\n\n\n", "solution": "#include \n#include \n#include \n\nclass XorShiftStar {\nprivate:\n const uint64_t MAGIC = 0x2545F4914F6CDD1D;\n uint64_t state;\npublic:\n void seed(uint64_t num) {\n state = num;\n }\n\n uint32_t next_int() {\n uint64_t x;\n uint32_t answer;\n\n x = state;\n x = x ^ (x >> 12);\n x = x ^ (x << 25);\n x = x ^ (x >> 27);\n state = x;\n answer = ((x * MAGIC) >> 32);\n\n return answer;\n }\n\n float next_float() {\n return (float)next_int() / (1LL << 32);\n }\n};\n\nint main() {\n auto rng = new XorShiftStar();\n rng->seed(1234567);\n std::cout << rng->next_int() << '\\n';\n std::cout << rng->next_int() << '\\n';\n std::cout << rng->next_int() << '\\n';\n std::cout << rng->next_int() << '\\n';\n std::cout << rng->next_int() << '\\n';\n std::cout << '\\n';\n\n std::array counts = { 0, 0, 0, 0, 0 };\n rng->seed(987654321);\n for (int i = 0; i < 100000; i++) {\n int j = (int)floor(rng->next_float() * 5.0);\n counts[j]++;\n }\n for (size_t i = 0; i < counts.size(); i++) {\n std::cout << i << \": \" << counts[i] << '\\n';\n }\n\n return 0;\n}"} {"title": "Pythagoras tree", "language": "C++", "task": "The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. \n\n;Task\nConstruct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).\n\n;Related tasks\n* Fractal tree\n\n", "solution": "[[File:pythagoras_treeCpp.png|300px|thumb|]]\nWindows version\n"} {"title": "Pythagoras tree", "language": "C++ from Java", "task": "The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. \n\n;Task\nConstruct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).\n\n;Related tasks\n* Fractal tree\n\n", "solution": "#include \n#include \n#include \n \nconst int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;\n\nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass tree {\npublic:\n tree() {\n bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();\n clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 );\n clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );\n clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 );\n }\n void draw( int it, POINT a, POINT b ) {\n if( !it ) return;\n bmp.setPenColor( clr[it % 6] );\n POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x };\n POINT d = { a.x - df.y, a.y - df.x };\n POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};\n drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );\n }\n void save( std::string p ) { bmp.saveBitmap( p ); }\nprivate:\n void drawSqr( POINT a, POINT b, POINT c, POINT d ) {\n HDC dc = bmp.getDC();\n MoveToEx( dc, a.x, a.y, NULL );\n LineTo( dc, b.x, b.y );\n LineTo( dc, c.x, c.y );\n LineTo( dc, d.x, d.y );\n LineTo( dc, a.x, a.y );\n }\n myBitmap bmp;\n DWORD clr[6];\n};\nint main( int argc, char* argv[] ) {\n POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },\n ptB = { ptA.x + LINE_LEN, ptA.y };\n tree t; t.draw( 12, ptA, ptB );\n // change this path \n t.save( \"?:/pt.bmp\" );\n return 0;\n}"} {"title": "Pythagorean quadruples", "language": "C++ from D", "task": "One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): \n\n\n:::::::: a2 + b2 + c2 = d2 \n\n\nAn example:\n\n:::::::: 22 + 32 + 62 = 72 \n\n::::: which is:\n\n:::::::: 4 + 9 + 36 = 49 \n\n\n;Task:\n\nFor positive integers up '''2,200''' (inclusive), for all values of '''a''', \n'''b''', '''c''', and '''d''', \nfind (and show here) those values of '''d''' that ''can't'' be represented.\n\nShow the values of '''d''' on one line of output (optionally with a title).\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]]. \n* [[Pythagorean triples]].\n\n\n;Reference:\n:* the Wikipedia article: Pythagorean quadruple.\n\n", "solution": "#include \n#include \n\nconstexpr int N = 2200;\nconstexpr int N2 = 2 * N * N;\n\nint main() {\n using namespace std;\n\n vector found(N + 1);\n vector aabb(N2 + 1);\n\n int s = 3;\n\n for (int a = 1; a < N; ++a) {\n int aa = a * a;\n for (int b = 1; b < N; ++b) {\n aabb[aa + b * b] = true;\n }\n }\n\n for (int c = 1; c <= N; ++c) {\n int s1 = s;\n s += 2;\n int s2 = s;\n for (int d = c + 1; d <= N; ++d) {\n if (aabb[s1]) {\n found[d] = true;\n }\n s1 += s2;\n s2 += 2;\n }\n }\n\n cout << \"The values of d <= \" << N << \" which can't be represented:\" << endl;\n for (int d = 1; d <= N; ++d) {\n if (!found[d]) {\n cout << d << \" \";\n }\n }\n cout << endl;\n\n return 0;\n}"} {"title": "Pythagorean triples", "language": "C++", "task": "A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.\n\nThey are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\\rm gcd}(a, b) = {\\rm gcd}(a, c) = {\\rm gcd}(b, c) = 1. \n\nBecause of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\\rm gcd}(a, b) = 1). \n\nEach triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.\n\n\n;Task:\nThe task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.\n\n\n;Extra credit: \nDeal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]] \n* [[List comprehensions]]\n* [[Pythagorean quadruples]] \n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n unsigned long long totalCount = 0;\n unsigned long long primitveCount = 0;\n auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;\n for(unsigned long long m = 2; m < max_M; ++m)\n {\n for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n {\n if(gcd(m,n) != 1)\n {\n continue;\n }\n \n // The formulas below will generate primitive triples if:\n // 0 < n < m\n // m and n are relatively prime (gcd == 1)\n // m + n is odd\n \n auto a = m * m - n * n;\n auto b = 2 * m * n;\n auto c = m * m + n * n;\n auto perimeter = a + b + c;\n if(perimeter <= maxPerimeter)\n {\n primitveCount++;\n totalCount+= maxPerimeter / perimeter;\n }\n }\n }\n \n return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n vector inputs{100, 1000, 10'000, 100'000,\n 1000'000, 10'000'000, 100'000'000, 1000'000'000,\n 10'000'000'000}; // This last one takes almost a minute\n for(auto maxPerimeter : inputs)\n {\n auto [total, primitive] = CountTriplets(maxPerimeter);\n cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n }\n}\n"} {"title": "Quaternion type", "language": "C++", "task": "complex numbers.\n\nA complex number has a real and complex part, sometimes written as a + bi, \nwhere a and b stand for real numbers, and i stands for the square root of minus 1.\n\nAn example of a complex number might be -3 + 2i, \nwhere the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, i, j, and k. \n\nA quaternion might be written as a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* ii = jj = kk = ijk = -1, or more simply,\n:::* ii = jj = kk = ijk = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: q1 and q2: q1q2 q2q1. \n\nAn example of a quaternion might be 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. \n\nSo the example above would be written as (1, 2, 3, 4) \n\n\n;Task:\nGiven the three quaternions and their components: \n q = (1, 2, 3, 4) = (a, b, c, d)\n q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)\n q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) \nAnd a wholly real number r = 7. \n\n\nCreate functions (or classes) to perform simple maths with quaternions including computing:\n# The norm of a quaternion: = \\sqrt{a^2 + b^2 + c^2 + d^2} \n# The negative of a quaternion: = (-a, -b, -c, -d) \n# The conjugate of a quaternion: = ( a, -b, -c, -d) \n# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) \n# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) \n# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) \n# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) \n# Show that, for the two quaternions q1 and q2: q1q2 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* [[Vector products]]\n* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.\n\n", "solution": "#include \nusing namespace std;\n\ntemplate\nclass Quaternion\n{\npublic:\n T w, x, y, z;\n\n // Numerical constructor\n Quaternion(const T &w, const T &x, const T &y, const T &z): w(w), x(x), y(y), z(z) {};\n Quaternion(const T &x, const T &y, const T &z): w(T()), x(x), y(y), z(z) {}; // For 3-rotations\n Quaternion(const T &r): w(r), x(T()), y(T()), z(T()) {};\n Quaternion(): w(T()), x(T()), y(T()), z(T()) {};\n\n // Copy constructor and assignment\n Quaternion(const Quaternion &q): w(q.w), x(q.x), y(q.y), z(q.z) {};\n Quaternion& operator=(const Quaternion &q) { w=q.w; x=q.x; y=q.y; z=q.z; return *this; }\n\n // Unary operators\n Quaternion operator-() const { return Quaternion(-w, -x, -y, -z); }\n Quaternion operator~() const { return Quaternion(w, -x, -y, -z); } // Conjugate\n\n // Norm-squared. SQRT would have to be made generic to be used here\n T normSquared() const { return w*w + x*x + y*y + z*z; }\n\n // In-place operators\n Quaternion& operator+=(const T &r) \n { w += r; return *this; }\n Quaternion& operator+=(const Quaternion &q) \n { w += q.w; x += q.x; y += q.y; z += q.z; return *this; }\n\n Quaternion& operator-=(const T &r) \n { w -= r; return *this; }\n Quaternion& operator-=(const Quaternion &q) \n { w -= q.w; x -= q.x; y -= q.y; z -= q.z; return *this; }\n\n Quaternion& operator*=(const T &r) \n { w *= r; x *= r; y *= r; z *= r; return *this; }\n Quaternion& operator*=(const Quaternion &q) \n { \n T oldW(w), oldX(x), oldY(y), oldZ(z);\n w = oldW*q.w - oldX*q.x - oldY*q.y - oldZ*q.z;\n x = oldW*q.x + oldX*q.w + oldY*q.z - oldZ*q.y;\n y = oldW*q.y + oldY*q.w + oldZ*q.x - oldX*q.z;\n z = oldW*q.z + oldZ*q.w + oldX*q.y - oldY*q.x;\n return *this;\n }\n \n Quaternion& operator/=(const T &r) \n { w /= r; x /= r; y /= r; z /= r; return *this; }\n Quaternion& operator/=(const Quaternion &q) \n { \n T oldW(w), oldX(x), oldY(y), oldZ(z), n(q.normSquared());\n w = (oldW*q.w + oldX*q.x + oldY*q.y + oldZ*q.z) / n;\n x = (oldX*q.w - oldW*q.x + oldY*q.z - oldZ*q.y) / n;\n y = (oldY*q.w - oldW*q.y + oldZ*q.x - oldX*q.z) / n;\n z = (oldZ*q.w - oldW*q.z + oldX*q.y - oldY*q.x) / n;\n return *this;\n }\n\n // Binary operators based on in-place operators\n Quaternion operator+(const T &r) const { return Quaternion(*this) += r; }\n Quaternion operator+(const Quaternion &q) const { return Quaternion(*this) += q; }\n Quaternion operator-(const T &r) const { return Quaternion(*this) -= r; }\n Quaternion operator-(const Quaternion &q) const { return Quaternion(*this) -= q; }\n Quaternion operator*(const T &r) const { return Quaternion(*this) *= r; }\n Quaternion operator*(const Quaternion &q) const { return Quaternion(*this) *= q; }\n Quaternion operator/(const T &r) const { return Quaternion(*this) /= r; }\n Quaternion operator/(const Quaternion &q) const { return Quaternion(*this) /= q; }\n\n // Comparison operators, as much as they make sense\n bool operator==(const Quaternion &q) const \n { return (w == q.w) && (x == q.x) && (y == q.y) && (z == q.z); }\n bool operator!=(const Quaternion &q) const { return !operator==(q); }\n\n // The operators above allow quaternion op real. These allow real op quaternion.\n // Uses the above where appropriate.\n template friend Quaternion operator+(const T &r, const Quaternion &q);\n template friend Quaternion operator-(const T &r, const Quaternion &q);\n template friend Quaternion operator*(const T &r, const Quaternion &q);\n template friend Quaternion operator/(const T &r, const Quaternion &q);\n \n // Allows cout << q \n template friend ostream& operator<<(ostream &io, const Quaternion &q);\n};\n\n// Friend functions need to be outside the actual class definition\ntemplate\nQuaternion operator+(const T &r, const Quaternion &q) \n { return q+r; }\n\ntemplate\nQuaternion operator-(const T &r, const Quaternion &q)\n { return Quaternion(r-q.w, q.x, q.y, q.z); }\n\ntemplate\nQuaternion operator*(const T &r, const Quaternion &q) \n { return q*r; }\n\ntemplate\nQuaternion operator/(const T &r, const Quaternion &q)\n{\n T n(q.normSquared());\n return Quaternion(r*q.w/n, -r*q.x/n, -r*q.y/n, -r*q.z/n);\n}\n\ntemplate\nostream& operator<<(ostream &io, const Quaternion &q)\n{ \n io << q.w;\n (q.x < T()) ? (io << \" - \" << (-q.x) << \"i\") : (io << \" + \" << q.x << \"i\");\n (q.y < T()) ? (io << \" - \" << (-q.y) << \"j\") : (io << \" + \" << q.y << \"j\");\n (q.z < T()) ? (io << \" - \" << (-q.z) << \"k\") : (io << \" + \" << q.z << \"k\");\n return io;\n}"} {"title": "Quine", "language": "C++", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA '''quine''' (named after Willard Van Orman Quine) is also known as:\n::* ''self-reproducing automata'' (1972)\n::* ''self-replicating program'' or ''self-replicating computer program''\n::* ''self-reproducing program'' or ''self-reproducing computer program''\n::* ''self-copying program'' or ''self-copying computer program''\n\n\n\nIt is named after the philosopher and logician \nwho studied self-reference and quoting in natural language, \nas for example in the paradox \"'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation.\"\n\n\"Source\" has one of two meanings. It can refer to the text-based program source. \nFor languages in which program source is represented as a data structure, \"source\" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.\n\nThe usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.\n\n\n;Task:\nWrite a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.\n\nThere are several difficulties that one runs into when writing a quine, mostly dealing with quoting:\n* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.\n** Some languages have a function for getting the \"source code representation\" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.\n** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.\n* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. \"\\n\"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.\n** If the language has a way of getting the \"source code representation\", it usually handles the escaping of characters, so this is not a problem.\n** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.\n** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.\n\n\n'''Next to the Quines presented here, many other versions can be found on the Quine page.'''\n\n\n;Related task:\n:* print itself.\n\n", "solution": "#include\nint main(){char n[]=R\"(#include\nint main(){char n[]=R\"(%s%c\";printf(n,n,41);})\";printf(n,n,41);}"} {"title": "RPG attributes generator", "language": "C++", "task": "'''RPG''' = Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main()\n{\n srand(time(0));\n \n unsigned int attributes_total = 0;\n unsigned int count = 0;\n int attributes[6] = {};\n int rolls[4] = {};\n \n while(attributes_total < 75 || count < 2)\n {\n attributes_total = 0;\n count = 0;\n \n for(int attrib = 0; attrib < 6; attrib++)\n { \n for(int roll = 0; roll < 4; roll++)\n {\n rolls[roll] = 1 + (rand() % 6);\n }\n \n sort(rolls, rolls + 4);\n int roll_total = rolls[1] + rolls[2] + rolls[3]; \n \n attributes[attrib] = roll_total;\n attributes_total += roll_total;\n \n if(roll_total >= 15) count++;\n }\n }\n \n cout << \"Attributes generated : [\";\n cout << attributes[0] << \", \";\n cout << attributes[1] << \", \";\n cout << attributes[2] << \", \";\n cout << attributes[3] << \", \";\n cout << attributes[4] << \", \";\n cout << attributes[5];\n \n cout << \"]\\nTotal: \" << attributes_total;\n cout << \", Values above 15 : \" << count;\n \n return 0;\n}"} {"title": "Ramer-Douglas-Peucker line simplification", "language": "C++", "task": "The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points:\n (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) \n\nThe error threshold to be used is: '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* the Wikipedia article: Ramer-Douglas-Peucker algorithm.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef std::pair Point;\n\ndouble PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd)\n{\n\tdouble dx = lineEnd.first - lineStart.first;\n\tdouble dy = lineEnd.second - lineStart.second;\n\n\t//Normalise\n\tdouble mag = pow(pow(dx,2.0)+pow(dy,2.0),0.5);\n\tif(mag > 0.0)\n\t{\n\t\tdx /= mag; dy /= mag;\n\t}\n\n\tdouble pvx = pt.first - lineStart.first;\n\tdouble pvy = pt.second - lineStart.second;\n\n\t//Get dot product (project pv onto normalized direction)\n\tdouble pvdot = dx * pvx + dy * pvy;\n\n\t//Scale line direction vector\n\tdouble dsx = pvdot * dx;\n\tdouble dsy = pvdot * dy;\n\n\t//Subtract this from pv\n\tdouble ax = pvx - dsx;\n\tdouble ay = pvy - dsy;\n\n\treturn pow(pow(ax,2.0)+pow(ay,2.0),0.5);\n}\n\nvoid RamerDouglasPeucker(const vector &pointList, double epsilon, vector &out)\n{\n\tif(pointList.size()<2)\n\t\tthrow invalid_argument(\"Not enough points to simplify\");\n\n\t// Find the point with the maximum distance from line between start and end\n\tdouble dmax = 0.0;\n\tsize_t index = 0;\n\tsize_t end = pointList.size()-1;\n\tfor(size_t i = 1; i < end; i++)\n\t{\n\t\tdouble d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]);\n\t\tif (d > dmax)\n\t\t{\n\t\t\tindex = i;\n\t\t\tdmax = d;\n\t\t}\n\t}\n\n\t// If max distance is greater than epsilon, recursively simplify\n\tif(dmax > epsilon)\n\t{\n\t\t// Recursive call\n\t\tvector recResults1;\n\t\tvector recResults2;\n\t\tvector firstLine(pointList.begin(), pointList.begin()+index+1);\n\t\tvector lastLine(pointList.begin()+index, pointList.end());\n\t\tRamerDouglasPeucker(firstLine, epsilon, recResults1);\n\t\tRamerDouglasPeucker(lastLine, epsilon, recResults2);\n \n\t\t// Build the result list\n\t\tout.assign(recResults1.begin(), recResults1.end()-1);\n\t\tout.insert(out.end(), recResults2.begin(), recResults2.end());\n\t\tif(out.size()<2)\n\t\t\tthrow runtime_error(\"Problem assembling output\");\n\t} \n\telse \n\t{\n\t\t//Just return start and end points\n\t\tout.clear();\n\t\tout.push_back(pointList[0]);\n\t\tout.push_back(pointList[end]);\n\t}\n}\n\nint main()\n{\n\tvector pointList;\n\tvector pointListOut;\n\n\tpointList.push_back(Point(0.0, 0.0));\n\tpointList.push_back(Point(1.0, 0.1));\n\tpointList.push_back(Point(2.0, -0.1));\n\tpointList.push_back(Point(3.0, 5.0));\n\tpointList.push_back(Point(4.0, 6.0));\n\tpointList.push_back(Point(5.0, 7.0));\n\tpointList.push_back(Point(6.0, 8.1));\n\tpointList.push_back(Point(7.0, 9.0));\n\tpointList.push_back(Point(8.0, 9.0));\n\tpointList.push_back(Point(9.0, 9.0));\n\n\tRamerDouglasPeucker(pointList, 1.0, pointListOut);\n\n\tcout << \"result\" << endl;\n\tfor(size_t i=0;i< pointListOut.size();i++)\n\t{\n\t\tcout << pointListOut[i].first << \",\" << pointListOut[i].second << endl;\n\t}\n\n\treturn 0;\n}"} {"title": "Random Latin squares", "language": "C++ from Java", "task": "A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.\nFor the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.\n\n;Example n=4 randomised Latin square:\n0 2 3 1\n2 1 0 3\n3 0 1 2\n1 3 2 0\n\n;Task:\n# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.\n# Use the function to generate ''and show here'', two randomly generated squares of size 5.\n\n;Note: \nStrict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.\n\n;Related tasks:\n* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]\n* [[Latin Squares in reduced form]]\n\n;Reference:\n* Wikipedia: Latin square\n* OEIS: A002860\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\ntemplate \nstd::ostream &operator<<(std::ostream &os, const std::vector &v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \";\n os << *it;\n it = std::next(it);\n }\n return os << ']';\n}\n\nvoid printSquare(const std::vector> &latin) {\n for (auto &row : latin) {\n std::cout << row << '\\n';\n }\n std::cout << '\\n';\n}\n\nvoid latinSquare(int n) {\n if (n <= 0) {\n std::cout << \"[]\\n\";\n return;\n }\n\n // obtain a time-based seed:\n unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n auto g = std::default_random_engine(seed);\n\n std::vector> latin;\n for (int i = 0; i < n; ++i) {\n std::vector inner;\n for (int j = 0; j < n; ++j) {\n inner.push_back(j);\n }\n latin.push_back(inner);\n }\n // first row\n std::shuffle(latin[0].begin(), latin[0].end(), g);\n\n // middle row(s)\n for (int i = 1; i < n - 1; ++i) {\n bool shuffled = false;\n\n while (!shuffled) {\n std::shuffle(latin[i].begin(), latin[i].end(), g);\n for (int k = 0; k < i; ++k) {\n for (int j = 0; j < n; ++j) {\n if (latin[k][j] == latin[i][j]) {\n goto shuffling;\n }\n }\n }\n shuffled = true;\n\n shuffling: {}\n }\n }\n\n // last row\n for (int j = 0; j < n; ++j) {\n std::vector used(n, false);\n for (int i = 0; i < n - 1; ++i) {\n used[latin[i][j]] = true;\n }\n for (int k = 0; k < n; ++k) {\n if (!used[k]) {\n latin[n - 1][j] = k;\n break;\n }\n }\n }\n\n printSquare(latin);\n}\n\nint main() {\n latinSquare(5);\n latinSquare(5);\n latinSquare(10);\n return 0;\n}"} {"title": "Random number generator (device)", "language": "C++", "task": "If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:\n\nshow how to obtain a random 32-bit number from that mechanism.\n\n;Related task\n* [[Random_number_generator_(included)]]\n\n", "solution": "std::random_device is a uniformly-distributed integer random number generator that produces non-deterministic random numbers.\n\nNote that std::random_device may be implemented in terms of a pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. \n\nSee the C++ section on [[Random_number_generator_(included)#C.2B.2B|Random number generator (included)]] for the list of pseudo-random number engines available.\n"} {"title": "Random number generator (device)", "language": "C++11", "task": "If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:\n\nshow how to obtain a random 32-bit number from that mechanism.\n\n;Related task\n* [[Random_number_generator_(included)]]\n\n", "solution": "#include \n#include \n \nint main()\n{\n std::random_device rd;\n std::uniform_int_distribution dist; // long is guaranteed to be 32 bits\n \n std::cout << \"Random Number: \" << dist(rd) << std::endl;\n}"} {"title": "Random number generator (included)", "language": "C++", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "As part of the C++11 specification the language now includes various forms of random number generation.\n\nWhile the default engine is implementation specific (ex, unspecified), the following Pseudo-random generators are available in the standard:\n* Linear congruential (minstd_rand0, minstd_rand)\n* Mersenne twister (mt19937, mt19937_64)\n* Subtract with carry (ranlux24_base, ranlux48_base)\n* Discard block (ranlux24, ranlux48)\n* Shuffle order (knuth_b)\n\nAdditionally, the following distributions are supported:\n* Uniform distributions: uniform_int_distribution, uniform_real_distribution\n* Bernoulli distributions: bernoulli_distribution, geometric_distribution, binomial_distribution, negative_binomial_distribution\n* Poisson distributions: poisson_distribution, gamma_distribution, exponential_distribution, weibull_distribution, extreme_value_distribution\n* Normal distributions: normal_distribution, fisher_f_distribution, cauchy_distribution, lognormal_distribution, chi_squared_distribution, student_t_distribution\n* Sampling distributions: discrete_distribution, piecewise_linear_distribution, piecewise_constant_distribution\n\nExample of use:\n"} {"title": "Random number generator (included)", "language": "C++11", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "#include \n#include \n#include \n \nint main()\n{\n std::random_device rd;\n std::uniform_int_distribution dist(1, 10);\n std::mt19937 mt(rd());\n \n std::cout << \"Random Number (hardware): \" << dist(rd) << std::endl;\n std::cout << \"Mersenne twister (hardware seeded): \" << dist(mt) << std::endl;\n}"} {"title": "Range consolidation", "language": "C++", "task": "Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* If one range covers all of the other then the result is that encompassing range.\n* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.\n* Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. \n\nIf '''N < 2''' then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then \n: there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then \n: there is : an overlap '''[2.5, 1.8]''' between the ranges and \n: the result is the single range '''[1, 4.7]'''. \n: Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then \n: they touch at '''7.2''' and \n: the result is the single range '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]''' \n: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]''' \n: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and \n: consolidate to produce the range '''[1, 5]'''. \n: This range, in turn, overlaps the other range '''[4, 8]''', and \n: so consolidates to the final output of the single range '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; and show the\nrange with the smaller lower bound to the left of other ranges when showing multiple ranges.\n\nOutput the ''normalized'' result of applying consolidation to these five sets of ranges: \n [1.1, 2.2]\n [6.1, 7.2], [7.2, 8.3]\n [4, 3], [2, 1]\n [4, 3], [2, 1], [-1, -2], [3.9, 10]\n [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] \nShow all output here.\n\n\n;See also:\n* [[Set consolidation]]\n* [[Set of real numbers]]\n\n", "solution": "#include \n#include \n#include \n#include \n\n// A range is represented as std::pair\n\ntemplate \nvoid normalize_ranges(iterator begin, iterator end) {\n for (iterator i = begin; i != end; ++i) {\n if (i->second < i->first)\n std::swap(i->first, i->second);\n }\n std::sort(begin, end);\n}\n\n// Merges a range of ranges in-place. Returns an iterator to the\n// end of the resulting range, similarly to std::remove.\ntemplate \niterator merge_ranges(iterator begin, iterator end) {\n iterator out = begin;\n for (iterator i = begin; i != end; ) {\n iterator j = i;\n while (++j != end && j->first <= i->second)\n i->second = std::max(i->second, j->second);\n *out++ = *i;\n i = j;\n }\n return out;\n}\n\ntemplate \niterator consolidate_ranges(iterator begin, iterator end) {\n normalize_ranges(begin, end);\n return merge_ranges(begin, end);\n}\n\ntemplate \nvoid print_range(std::ostream& out, const pair& range) {\n out << '[' << range.first << \", \" << range.second << ']';\n}\n\ntemplate \nvoid print_ranges(std::ostream& out, iterator begin, iterator end) {\n if (begin != end) {\n print_range(out, *begin++);\n for (; begin != end; ++begin) {\n out << \", \";\n print_range(out, *begin);\n }\n }\n}\n\nint main() {\n std::vector> test_cases[] = {\n { {1.1, 2.2} },\n { {6.1, 7.2}, {7.2, 8.3} },\n { {4, 3}, {2, 1} },\n { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} },\n { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} }\n };\n for (auto&& ranges : test_cases) {\n print_ranges(std::cout, std::begin(ranges), std::end(ranges));\n std::cout << \" -> \";\n auto i = consolidate_ranges(std::begin(ranges), std::end(ranges));\n print_ranges(std::cout, std::begin(ranges), i);\n std::cout << '\\n';\n }\n return 0;\n}"} {"title": "Range expansion", "language": "C++", "task": "{{:Range extraction/Format}}\n\n\n;Task:\nExpand the range description: \n -6,-3--1,3-5,7-11,14,15,17-20 \nNote that the second element above, \nis the '''range from minus 3 to ''minus'' 1'''. \n\n\n;Related task:\n* [[Range extraction]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n// parse a list of numbers with ranges\n//\n// arguments:\n// is: the stream to parse\n// out: the output iterator the parsed list is written to.\n//\n// returns true if the parse was successful. false otherwise\ntemplate\n bool parse_number_list_with_ranges(std::istream& is, OutIter out)\n{\n int number;\n // the list always has to start with a number\n while (is >> number)\n {\n *out++ = number;\n\n char c;\n if (is >> c)\n switch(c)\n {\n case ',':\n continue;\n case '-':\n {\n int number2;\n if (is >> number2)\n {\n if (number2 < number)\n return false;\n while (number < number2)\n *out++ = ++number;\n char c2;\n if (is >> c2)\n if (c2 == ',')\n continue;\n else\n return false;\n else\n return is.eof();\n }\n else\n return false;\n }\n default:\n return is.eof();\n }\n else\n return is.eof();\n }\n // if we get here, something went wrong (otherwise we would have\n // returned from inside the loop)\n return false;\n}\n\nint main()\n{\n std::istringstream example(\"-6,-3--1,3-5,7-11,14,15,17-20\");\n std::deque v;\n bool success = parse_number_list_with_ranges(example, std::back_inserter(v));\n if (success)\n {\n std::copy(v.begin(), v.end()-1,\n std::ostream_iterator(std::cout, \",\"));\n std::cout << v.back() << \"\\n\";\n }\n else\n std::cout << \"an error occured.\";\n}"} {"title": "Range extraction", "language": "C++", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "#include \n#include \n#include \n\ntemplate\n void extract_ranges(InIter begin, InIter end, std::ostream& os)\n{\n if (begin == end)\n return;\n\n int current = *begin++;\n os << current;\n int count = 1;\n\n while (begin != end)\n {\n int next = *begin++;\n if (next == current+1)\n ++count;\n else\n {\n if (count > 2)\n os << '-';\n else\n os << ',';\n if (count > 1)\n os << current << ',';\n os << next;\n count = 1;\n }\n current = next;\n }\n\n if (count > 1)\n os << (count > 2? '-' : ',') << current;\n}\n\ntemplate\n T* end(T (&array)[n])\n{\n return array+n;\n}\n\nint main()\n{\n int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39 };\n\n extract_ranges(data, end(data), std::cout);\n std::cout << std::endl;\n}\n"} {"title": "Rate counter", "language": "C++", "task": "Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.\nOf interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.\n\nMultiple approaches are allowed (even preferable), so long as they can accomplish these goals:\n\n* Run N seconds worth of jobs and/or Y jobs.\n* Report at least three distinct times.\n\nBe aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.\n\n'''See also:''' [[System time]], [[Time a function]]\n\n", "solution": "#include \n#include \n\n// We only get one-second precision on most systems, as\n// time_t only holds seconds.\nclass CRateState\n{\nprotected:\n time_t m_lastFlush;\n time_t m_period;\n size_t m_tickCount;\npublic:\n CRateState(time_t period);\n void Tick();\n};\n\nCRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),\n m_period(period),\n m_tickCount(0)\n{ }\n\nvoid CRateState::Tick()\n{\n m_tickCount++;\n\n time_t now = std::time(NULL);\n\n if((now - m_lastFlush) >= m_period)\n {\n //TPS Report\n size_t tps = 0.0;\n if(m_tickCount > 0)\n tps = m_tickCount / (now - m_lastFlush);\n\n std::cout << tps << \" tics per second\" << std::endl;\n\n //Reset\n m_tickCount = 0;\n m_lastFlush = now;\n }\n}\n\n// A stub function that simply represents whatever it is\n// that we want to multiple times.\nvoid something_we_do()\n{\n // We use volatile here, as many compilers will optimize away\n // the for() loop otherwise, even without optimizations\n // explicitly enabled.\n //\n // volatile tells the compiler not to make any assumptions\n // about the variable, implying that the programmer knows more\n // about that variable than the compiler, in this case.\n volatile size_t anchor = 0;\n for(size_t x = 0; x < 0xffff; ++x)\n {\n anchor = x;\n }\n}\n\nint main()\n{\n time_t start = std::time(NULL);\n\n CRateState rateWatch(5);\n\n // Loop for twenty seconds\n for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))\n {\n // Do something.\n something_we_do();\n\n // Note that we did something.\n rateWatch.Tick();\n }\n\n return 0;\n}"} {"title": "Read a specific line from a file", "language": "C++", "task": "Some languages have special semantics for obtaining a known line number from a file.\n\n\n;Task:\nDemonstrate how to obtain the contents of a specific line within a file. \n\nFor the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded). \n\nIf the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message. \n\nIf no special semantics are available for obtaining the required line, it is permissible to read line by line. \n\nNote that empty lines are considered and should still be counted.\n\nAlso note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.\n\n", "solution": "#include \n#include \n#include \n\nint main( ) {\n std::cout << \"Which file do you want to look at ?\\n\" ;\n std::string input ;\n std::getline( std::cin , input ) ;\n std::ifstream infile( input.c_str( ) , std::ios::in ) ;\n std::string file( input ) ;\n std::cout << \"Which file line do you want to see ? ( Give a number > 0 ) ?\\n\" ;\n std::getline( std::cin , input ) ;\n int linenumber = std::stoi( input ) ;\n int lines_read = 0 ;\n std::string line ;\n if ( infile.is_open( ) ) {\n while ( infile ) {\n\t getline( infile , line ) ;\n\t lines_read++ ;\n\t if ( lines_read == linenumber ) {\n\t std::cout << line << std::endl ;\n\t break ; \n\t }\n }\n infile.close( ) ;\n if ( lines_read < linenumber ) \n\t std::cout << \"No \" << linenumber << \" lines in \" << file << \" !\\n\" ;\n return 0 ;\n }\n else {\n std::cerr << \"Could not find file \" << file << \" !\\n\" ;\n return 1 ;\n }\n}"} {"title": "Recaman's sequence", "language": "C++ from C#", "task": "The '''Recaman's sequence''' generates Natural numbers.\n\nStarting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* A005132, The On-Line Encyclopedia of Integer Sequences.\n* The Slightly Spooky Recaman Sequence, Numberphile video.\n* Recaman's sequence, on Wikipedia.\n\n", "solution": "#include \n#include \n#include \n#include \n\ntemplate\nstd::ostream& operator<<(std::ostream& os, const std::vector& v) {\n auto i = v.cbegin();\n auto e = v.cend();\n os << '[';\n if (i != e) {\n os << *i;\n i = std::next(i);\n }\n while (i != e) {\n os << \", \" << *i;\n i = std::next(i);\n }\n return os << ']';\n}\n\nint main() {\n using namespace std;\n\n vector a{ 0 };\n set used{ 0 };\n set used1000{ 0 };\n bool foundDup = false;\n int n = 1;\n while (n <= 15 || !foundDup || used1000.size() < 1001) {\n int next = a[n - 1] - n;\n if (next < 1 || used.find(next) != used.end()) {\n next += 2 * n;\n }\n bool alreadyUsed = used.find(next) != used.end();\n a.push_back(next);\n if (!alreadyUsed) {\n used.insert(next);\n if (0 <= next && next <= 1000) {\n used1000.insert(next);\n }\n }\n if (n == 14) {\n cout << \"The first 15 terms of the Recaman sequence are: \" << a << '\\n';\n }\n if (!foundDup && alreadyUsed) {\n cout << \"The first duplicated term is a[\" << n << \"] = \" << next << '\\n';\n foundDup = true;\n }\n if (used1000.size() == 1001) {\n cout << \"Terms up to a[\" << n << \"] are needed to generate 0 to 1000\\n\";\n }\n n++;\n }\n\n return 0;\n}"} {"title": "Remove lines from a file", "language": "C++", "task": "Remove a specific line or a number of lines from a file. \n\nThis should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). \n\nFor the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2\n\nEmpty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. \n\nAn appropriate message should appear if an attempt is made to remove lines beyond the end of the file.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nvoid deleteLines( const std::string & , int , int ) ;\n\nint main( int argc, char * argv[ ] ) {\n if ( argc != 4 ) {\n std::cerr << \"Error! Invoke with !\\n\" ;\n return 1 ;\n }\n std::string filename( argv[ 1 ] ) ;\n int startfrom = atoi( argv[ 2 ] ) ;\n int howmany = atoi( argv[ 3 ] ) ;\n deleteLines ( filename , startfrom , howmany ) ;\n return 0 ;\n}\n\nvoid deleteLines( const std::string & filename , int start , int skip ) {\n std::ifstream infile( filename.c_str( ) , std::ios::in ) ;\n if ( infile.is_open( ) ) {\n std::string line ;\n std::list filelines ;\n while ( infile ) {\n\t getline( infile , line ) ;\n\t filelines.push_back( line ) ;\n }\n infile.close( ) ;\n if ( start > filelines.size( ) ) {\n\t std::cerr << \"Error! Starting to delete lines past the end of the file!\\n\" ;\n\t return ;\n }\n if ( ( start + skip ) > filelines.size( ) ) {\n\t std::cerr << \"Error! Trying to delete lines past the end of the file!\\n\" ;\n\t return ;\n }\n std::list::iterator deletebegin = filelines.begin( ) , deleteend ;\n for ( int i = 1 ; i < start ; i++ )\n\t deletebegin++ ;\n deleteend = deletebegin ;\n for( int i = 0 ; i < skip ; i++ )\n\t deleteend++ ;\n filelines.erase( deletebegin , deleteend ) ;\n std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;\n if ( outfile.is_open( ) ) {\n\t for ( std::list::const_iterator sli = filelines.begin( ) ;\n\t sli != filelines.end( ) ; sli++ )\n\t outfile << *sli << \"\\n\" ;\n }\n outfile.close( ) ;\n }\n else {\n std::cerr << \"Error! Could not find file \" << filename << \" !\\n\" ;\n return ;\n }\n}"} {"title": "Rep-string", "language": "C++", "task": "Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.\n\nFor example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.\n\nNote that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.\n\n\n;Task:\n* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). \n* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.\n* Use the function to indicate the repeating substring if any, in the following:\n\n\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\n\n\n* Show your output on this page.\n\n\n\n", "solution": "#include \n#include \n#include \n\nbool is_repstring( const std::string & teststring , std::string & repunit ) {\n std::string regex( \"^(.+)\\\\1+(.*)$\" ) ;\n boost::regex e ( regex ) ;\n boost::smatch what ;\n if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {\n std::string firstbracket( what[1 ] ) ;\n std::string secondbracket( what[ 2 ] ) ;\n if ( firstbracket.length( ) >= secondbracket.length( ) &&\n\t firstbracket.find( secondbracket ) != std::string::npos ) {\n\t repunit = firstbracket ;\n }\n }\n return !repunit.empty( ) ;\n}\n\nint main( ) {\n std::vector teststrings { \"1001110011\" , \"1110111011\" , \"0010010010\" ,\n \"1010101010\" , \"1111111111\" , \"0100101101\" , \"0100100\" , \"101\" , \"11\" , \"00\" , \"1\" } ;\n std::string theRep ;\n for ( std::string myString : teststrings ) {\n if ( is_repstring( myString , theRep ) ) {\n\t std::cout << myString << \" is a rep string! Here is a repeating string:\\n\" ;\n\t std::cout << theRep << \" \" ;\n }\n else {\n\t std::cout << myString << \" is no rep string!\" ;\n }\n theRep.clear( ) ;\n std::cout << std::endl ;\n }\n return 0 ;\n}"} {"title": "Repeat", "language": "C++", "task": "Write a procedure which accepts as arguments another procedure and a positive integer. \n\nThe latter procedure is executed a number of times equal to the accepted integer.\n\n", "solution": "template \nvoid repeat(Function f, unsigned int n) {\n for(unsigned int i=n; 0\n#include \n#include \n\nclass Node {\nprivate:\n double v;\n int fixed;\n\npublic:\n Node() : v(0.0), fixed(0) {\n // empty\n }\n\n Node(double v, int fixed) : v(v), fixed(fixed) {\n // empty\n }\n\n double getV() const {\n return v;\n }\n\n void setV(double nv) {\n v = nv;\n }\n\n int getFixed() const {\n return fixed;\n }\n\n void setFixed(int nf) {\n fixed = nf;\n }\n};\n\nvoid setBoundary(std::vector>& m) {\n m[1][1].setV(1.0);\n m[1][1].setFixed(1);\n\n m[6][7].setV(-1.0);\n m[6][7].setFixed(-1);\n}\n\ndouble calculateDifference(const std::vector>& m, std::vector>& d, const int w, const int h) {\n double total = 0.0;\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n double v = 0.0;\n int n = 0;\n if (i > 0) {\n v += m[i - 1][j].getV();\n n++;\n }\n if (j > 0) {\n v += m[i][j - 1].getV();\n n++;\n }\n if (i + 1 < h) {\n v += m[i + 1][j].getV();\n n++;\n }\n if (j + 1 < w) {\n v += m[i][j + 1].getV();\n n++;\n }\n v = m[i][j].getV() - v / n;\n d[i][j].setV(v);\n if (m[i][j].getFixed() == 0) {\n total += v * v;\n }\n }\n }\n return total;\n}\n\ndouble iter(std::vector>& m, const int w, const int h) {\n using namespace std;\n vector> d;\n for (int i = 0; i < h; ++i) {\n vector t(w);\n d.push_back(t);\n }\n\n double curr[] = { 0.0, 0.0, 0.0 };\n double diff = 1e10;\n\n while (diff > 1e-24) {\n setBoundary(m);\n diff = calculateDifference(m, d, w, h);\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n m[i][j].setV(m[i][j].getV() - d[i][j].getV());\n }\n }\n }\n\n for (int i = 0; i < h; ++i) {\n for (int j = 0; j < w; ++j) {\n int k = 0;\n if (i != 0) ++k;\n if (j != 0) ++k;\n if (i < h - 1) ++k;\n if (j < w - 1) ++k;\n curr[m[i][j].getFixed() + 1] += d[i][j].getV()*k;\n }\n }\n\n return (curr[2] - curr[0]) / 2.0;\n}\n\nconst int S = 10;\nint main() {\n using namespace std;\n vector> mesh;\n\n for (int i = 0; i < S; ++i) {\n vector t(S);\n mesh.push_back(t);\n }\n\n double r = 2.0 / iter(mesh, S, S);\n cout << \"R = \" << setprecision(15) << r << '\\n';\n\n return 0;\n}"} {"title": "Reverse words in a string", "language": "C++", "task": "Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! would be shown reversed as: Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. \n\nYou may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string (or one just containing spaces) would be the result.\n\n'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. \n\n(You can consider the ten strings as ten lines, and the tokens as words.)\n\n\n;Input data\n\n (ten lines within the box)\n line\n +----------------------------------------+\n 1 | ---------- Ice and Fire ------------ |\n 2 | | <--- a blank line here.\n 3 | fire, in end will world the say Some |\n 4 | ice. in say Some |\n 5 | desire of tasted I've what From |\n 6 | fire. favor who those with hold I |\n 7 | | <--- a blank line here.\n 8 | ... elided paragraph last ... |\n 9 | | <--- a blank line here.\n 10 | Frost Robert ----------------------- |\n +----------------------------------------+\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n//code for a C++11 compliant compiler\ntemplate \nvoid block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {\n std::reverse(first, last);\n auto block_last = first;\n do {\n using std::placeholders::_1;\n auto block_first = std::find_if_not(block_last, last, \n std::bind(std::equal_to(),_1, separator));\n block_last = std::find(block_first, last, separator);\n std::reverse(block_first, block_last);\n } while(block_last != last);\n}\n\n//code for a C++03 compliant compiler\ntemplate \nvoid block_reverse_cpp03(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {\n std::reverse(first, last);\n BidirectionalIterator block_last = first;\n do {\n BidirectionalIterator block_first = std::find_if(block_last, last, \n std::bind2nd(std::not_equal_to(), separator));\n block_last = std::find(block_first, last, separator);\n std::reverse(block_first, block_last);\n } while(block_last != last);\n}\n\nint main() {\n std::string str1[] = \n {\n \"---------- Ice and Fire ------------\",\n \"\",\n \"fire, in end will world the say Some\",\n \"ice. in say Some\",\n \"desire of tasted I've what From\",\n \"fire. favor who those with hold I\",\n \"\",\n \"... elided paragraph last ...\",\n \"\",\n \"Frost Robert -----------------------\"\n };\n\n std::for_each(begin(str1), end(str1), [](std::string& s){\n block_reverse_cpp11(begin(s), end(s), ' ');\n std::cout << s << std::endl;\n });\n \n std::for_each(begin(str1), end(str1), [](std::string& s){\n block_reverse_cpp03(begin(s), end(s), ' ');\n std::cout << s << std::endl;\n });\n\n return 0;\n}\n"} {"title": "Rhonda numbers", "language": "C++", "task": "A positive integer '''''n''''' is said to be a Rhonda number to base '''''b''''' if the product of the base '''''b''''' digits of '''''n''''' is equal to '''''b''''' times the sum of '''''n''''''s prime factors.\n\n\n''These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.''\n\n\n'''25662''' is a Rhonda number to base-'''10'''. The prime factorization is '''2 x 3 x 7 x 13 x 47'''; the product of its base-'''10''' digits is equal to the base times the sum of its prime factors:\n\n2 x 5 x 6 x 6 x 2 = 720 = 10 x (2 + 3 + 7 + 13 + 47)\n\nRhonda numbers only exist in bases that are not a prime.\n\n''Rhonda numbers to base 10 '''always''' contain at least 1 digit 5 and '''always''' contain at least 1 even digit.''\n\n\n;Task\n\n* For the non-prime bases '''''b''''' from '''2''' through '''16''' , find and display here, on this page, at least the first '''10''' '''Rhonda numbers''' to base '''''b'''''. Display the found numbers at least in base '''10'''.\n\n\n;Stretch\n\n* Extend out to base '''36'''.\n\n\n;See also\n\n;* Wolfram Mathworld - Rhonda numbers\n;* Numbers Aplenty - Rhonda numbers\n;* OEIS:A100968 - Integers n that are Rhonda numbers to base 4\n;* OEIS:A100969 - Integers n that are Rhonda numbers to base 6\n;* OEIS:A100970 - Integers n that are Rhonda numbers to base 8\n;* OEIS:A100973 - Integers n that are Rhonda numbers to base 9\n;* OEIS:A099542 - Rhonda numbers to base 10\n;* OEIS:A100971 - Integers n that are Rhonda numbers to base 12\n;* OEIS:A100972 - Integers n that are Rhonda numbers to base 14\n;* OEIS:A100974 - Integers n that are Rhonda numbers to base 15\n;* OEIS:A100975 - Integers n that are Rhonda numbers to base 16\n\n;* OEIS:A255735 - Integers n that are Rhonda numbers to base 18\n;* OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)\n;* OEIS:A255736 - Integers that are Rhonda numbers to base 30\n\n;* Related Task: Smith numbers\n\n", "solution": "#include \n#include \n#include \n#include \n\nint digit_product(int base, int n) {\n int product = 1;\n for (; n != 0; n /= base)\n product *= n % base;\n return product;\n}\n\nint prime_factor_sum(int n) {\n int sum = 0;\n for (; (n & 1) == 0; n >>= 1)\n sum += 2;\n for (int p = 3; p * p <= n; p += 2)\n for (; n % p == 0; n /= p)\n sum += p;\n if (n > 1)\n sum += n;\n return sum;\n}\n\nbool is_prime(int n) {\n if (n < 2)\n return false;\n if (n % 2 == 0)\n return n == 2;\n if (n % 3 == 0)\n return n == 3;\n for (int p = 5; p * p <= n; p += 4) {\n if (n % p == 0)\n return false;\n p += 2;\n if (n % p == 0)\n return false;\n }\n return true;\n}\n\nbool is_rhonda(int base, int n) {\n return digit_product(base, n) == base * prime_factor_sum(n);\n}\n\nstd::string to_string(int base, int n) {\n assert(base <= 36);\n static constexpr char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n std::string str;\n for (; n != 0; n /= base)\n str += digits[n % base];\n std::reverse(str.begin(), str.end());\n return str;\n}\n\nint main() {\n const int limit = 15;\n for (int base = 2; base <= 36; ++base) {\n if (is_prime(base))\n continue;\n std::cout << \"First \" << limit << \" Rhonda numbers to base \" << base\n << \":\\n\";\n int numbers[limit];\n for (int n = 1, count = 0; count < limit; ++n) {\n if (is_rhonda(base, n))\n numbers[count++] = n;\n }\n std::cout << \"In base 10:\";\n for (int i = 0; i < limit; ++i)\n std::cout << ' ' << numbers[i];\n std::cout << \"\\nIn base \" << base << ':';\n for (int i = 0; i < limit; ++i)\n std::cout << ' ' << to_string(base, numbers[i]);\n std::cout << \"\\n\\n\";\n }\n}"} {"title": "Roman numerals/Decode", "language": "C++", "task": "Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. \n\nYou don't need to validate the form of the Roman numeral.\n\nModern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, \nstarting with the leftmost decimal digit and skipping any '''0'''s (zeroes). \n\n'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and \n'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).\n \nThe Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nnamespace Roman\n{\n\tint ToInt(char c)\n\t{\n\t\tswitch (c)\n\t\t{\n\t\t\tcase 'I': return 1;\n\t\t\tcase 'V': return 5;\n\t\t\tcase 'X': return 10;\n\t\t\tcase 'L': return 50;\n\t\t\tcase 'C': return 100;\n\t\t\tcase 'D': return 500;\n\t\t\tcase 'M': return 1000;\n\t\t}\n\t\tthrow exception(\"Invalid character\");\n\t}\n\n\tint ToInt(const string& s)\n\t{\n\t\tint retval = 0, pvs = 0;\n\t\tfor (auto pc = s.rbegin(); pc != s.rend(); ++pc)\n\t\t{\n\t\t\tconst int inc = ToInt(*pc);\n\t\t\tretval += inc < pvs ? -inc : inc;\n\t\t\tpvs = inc;\n\t\t}\n\t\treturn retval;\n\t}\n}\n\nint main(int argc, char* argv[])\n{\n\ttry\n\t{\n\t\tcout << \"MCMXC = \" << Roman::ToInt(\"MCMXC\") << \"\\n\";\n\t\tcout << \"MMVIII = \" << Roman::ToInt(\"MMVIII\") << \"\\n\";\n\t\tcout << \"MDCLXVI = \" << Roman::ToInt(\"MDCLXVI\") << \"\\n\";\n\t}\n\tcatch (exception& e)\n\t{\n\t\tcerr << e.what();\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n"} {"title": "Roman numerals/Encode", "language": "C++", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "#include \n#include \n\nstd::string to_roman(int x) {\n if (x <= 0)\n return \"Negative or zero!\";\n auto roman_digit = [](char one, char five, char ten, int x) {\n if (x <= 3)\n return std::string().assign(x, one);\n if (x <= 5)\n return std::string().assign(5 - x, one) + five;\n if (x <= 8)\n return five + std::string().assign(x - 5, one);\n return std::string().assign(10 - x, one) + ten;\n };\n if (x >= 1000)\n return x - 1000 > 0 ? \"M\" + to_roman(x - 1000) : \"M\";\n if (x >= 100) {\n auto s = roman_digit('C', 'D', 'M', x / 100);\n return x % 100 > 0 ? s + to_roman(x % 100) : s;\n }\n if (x >= 10) {\n auto s = roman_digit('X', 'L', 'C', x / 10);\n return x % 10 > 0 ? s + to_roman(x % 10) : s;\n }\n return roman_digit('I', 'V', 'X', x);\n}\n\nint main() {\n for (int i = 0; i < 2018; i++)\n std::cout << i << \" --> \" << to_roman(i) << std::endl;\n}"} {"title": "Runge-Kutta method", "language": "C++", "task": "Given the example Differential equation:\n:y'(t) = t \\times \\sqrt {y(t)}\nWith initial condition:\n:t_0 = 0 and y_0 = y(t_0) = y(0) = 1\nThis equation has an exact solution:\n:y(t) = \\tfrac{1}{16}(t^2 +4)^2\n\n\n;Task\nDemonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.\n* Solve the given differential equation over the range t = 0 \\ldots 10 with a step value of \\delta t=0.1 (101 total points, the first being given)\n* Print the calculated values of y at whole numbered t's (0.0, 1.0, \\ldots 10.0) along with error as compared to the exact solution.\n\n\n;Method summary\nStarting with a given y_n and t_n calculate:\n:\\delta y_1 = \\delta t\\times y'(t_n, y_n)\\quad\n:\\delta y_2 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_1)\n:\\delta y_3 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_2)\n:\\delta y_4 = \\delta t\\times y'(t_n + \\delta t , y_n + \\delta y_3)\\quad\nthen:\n:y_{n+1} = y_n + \\tfrac{1}{6} (\\delta y_1 + 2\\delta y_2 + 2\\delta y_3 + \\delta y_4)\n:t_{n+1} = t_n + \\delta t\\quad\n\n", "solution": "/*\n * compiled with:\n * g++ (Debian 8.3.0-6) 8.3.0\n * \n * g++ -std=c++14 -o rk4 %\n *\n */\n# include \n# include \n \nauto rk4(double f(double, double))\n{\n return [f](double t, double y, double dt) -> double {\n double dy1 { dt * f( t , y ) },\n dy2 { dt * f( t+dt/2, y+dy1/2 ) },\n dy3 { dt * f( t+dt/2, y+dy2/2 ) },\n dy4 { dt * f( t+dt , y+dy3 ) };\n return ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6;\n };\n}\n\nint main(void)\n{\n constexpr\n double TIME_MAXIMUM { 10.0 },\n T_START { 0.0 },\n Y_START { 1.0 },\n DT { 0.1 },\n WHOLE_TOLERANCE { 1e-12 };\n\n auto dy = rk4( [](double t, double y) -> double { return t*sqrt(y); } ) ;\n \n for (\n auto y { Y_START }, t { T_START };\n t <= TIME_MAXIMUM;\n y += dy(t,y,DT), t += DT\n )\n if (ceilf(t)-t < WHOLE_TOLERANCE)\n printf(\"y(%4.1f)\\t=%12.6f \\t error: %12.6e\\n\", t, y, std::fabs(y - pow(t*t+4,2)/16));\n \n return 0;\n}"} {"title": "Ruth-Aaron numbers", "language": "C++", "task": "A '''Ruth-Aaron''' pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.\n\n\nA '''Ruth-Aaron''' triple consists of '''''three''''' consecutive integers with the same properties.\n\n\nThere is a second variant of '''Ruth-Aaron''' numbers, one which uses prime ''factors'' rather than prime ''divisors''. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. \n\n\nIt is common to refer to each '''Ruth-Aaron''' group by the first number in it. \n\n\n;Task\n\n* Find and show, here on this page, the first '''30''' '''Ruth-Aaron numbers''' (factors).\n\n* Find and show, here on this page, the first '''30''' '''Ruth-Aaron numbers''' (divisors).\n\n\n;Stretch\n\n* Find and show the first '''Ruth-Aaron triple''' (factors).\n\n* Find and show the first '''Ruth-Aaron triple''' (divisors).\n\n\n;See also\n\n;*Wikipedia: Ruth-Aaron pair\n;*OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1\n;*OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)\n\n", "solution": "#include \n#include \n\nint prime_factor_sum(int n) {\n int sum = 0;\n for (; (n & 1) == 0; n >>= 1)\n sum += 2;\n for (int p = 3, sq = 9; sq <= n; p += 2) {\n for (; n % p == 0; n /= p)\n sum += p;\n sq += (p + 1) << 2;\n }\n if (n > 1)\n sum += n;\n return sum;\n}\n\nint prime_divisor_sum(int n) {\n int sum = 0;\n if ((n & 1) == 0) {\n sum += 2;\n n >>= 1;\n while ((n & 1) == 0)\n n >>= 1;\n }\n for (int p = 3, sq = 9; sq <= n; p += 2) {\n if (n % p == 0) {\n sum += p;\n n /= p;\n while (n % p == 0)\n n /= p;\n }\n sq += (p + 1) << 2;\n }\n if (n > 1)\n sum += n;\n return sum;\n}\n\nint main() {\n const int limit = 30;\n int dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;\n\n std::cout << \"First \" << limit << \" Ruth-Aaron numbers (factors):\\n\";\n for (int n = 2, count = 0; count < limit; ++n) {\n fsum2 = prime_factor_sum(n);\n if (fsum1 == fsum2) {\n ++count;\n std::cout << std::setw(5) << n - 1\n << (count % 10 == 0 ? '\\n' : ' ');\n }\n fsum1 = fsum2;\n }\n\n std::cout << \"\\nFirst \" << limit << \" Ruth-Aaron numbers (divisors):\\n\";\n for (int n = 2, count = 0; count < limit; ++n) {\n dsum2 = prime_divisor_sum(n);\n if (dsum1 == dsum2) {\n ++count;\n std::cout << std::setw(5) << n - 1\n << (count % 10 == 0 ? '\\n' : ' ');\n }\n dsum1 = dsum2;\n }\n\n dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;\n for (int n = 2;; ++n) {\n int fsum3 = prime_factor_sum(n);\n if (fsum1 == fsum2 && fsum2 == fsum3) {\n std::cout << \"\\nFirst Ruth-Aaron triple (factors): \" << n - 2\n << '\\n';\n break;\n }\n fsum1 = fsum2;\n fsum2 = fsum3;\n }\n for (int n = 2;; ++n) {\n int dsum3 = prime_divisor_sum(n);\n if (dsum1 == dsum2 && dsum2 == dsum3) {\n std::cout << \"\\nFirst Ruth-Aaron triple (divisors): \" << n - 2\n << '\\n';\n break;\n }\n dsum1 = dsum2;\n dsum2 = dsum3;\n }\n}"} {"title": "Sailors, coconuts and a monkey problem", "language": "C++ from C#", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "#include \n\nbool valid(int n, int nuts) {\n for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) {\n if (nuts % n != 1) {\n return false;\n }\n }\n\n return nuts != 0 && (nuts % n == 0);\n}\n\nint main() {\n int x = 0;\n for (int n = 2; n < 10; n++) {\n while (!valid(n, x)) {\n x++;\n }\n std::cout << n << \": \" << x << std::endl;\n }\n\n return 0;\n}"} {"title": "Same fringe", "language": "C++", "task": "Write a routine that will compare the leaves (\"fringe\") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.\n\nAny solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.\n\nAny representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nclass BinaryTree\n{\n // C++ does not have a built in tree type. The binary tree is a recursive\n // data type that is represented by an empty tree or a node the has a value\n // and a left and right sub-tree. A tuple represents the node and unique_ptr\n // represents an empty vs. non-empty tree.\n using Node = tuple;\n unique_ptr m_tree;\n\npublic:\n // Provide ways to make trees\n BinaryTree() = default; // Make an empty tree\n BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)\n : m_tree {make_unique(move(leftChild), value, move(rightChild))} {}\n BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}\n BinaryTree(BinaryTree&& leftChild, int value)\n : BinaryTree(move(leftChild), value, BinaryTree{}){}\n BinaryTree(int value, BinaryTree&& rightChild)\n : BinaryTree(BinaryTree{}, value, move(rightChild)){}\n\n // Test if the tree is empty\n explicit operator bool() const\n {\n return (bool)m_tree;\n }\n\n // Get the value of the root node of the tree\n int Value() const\n {\n return get<1>(*m_tree);\n }\n\n // Get the left child tree\n const BinaryTree& LeftChild() const\n {\n return get<0>(*m_tree);\n }\n\n // Get the right child tree\n const BinaryTree& RightChild() const\n {\n return get<2>(*m_tree);\n }\n};\n\n// Define a promise type to be used for coroutines\nstruct TreeWalker {\n struct promise_type {\n int val;\n\n suspend_never initial_suspend() noexcept {return {};}\n suspend_never return_void() noexcept {return {};}\n suspend_always final_suspend() noexcept {return {};}\n void unhandled_exception() noexcept { }\n\n TreeWalker get_return_object() \n {\n return TreeWalker{coroutine_handle::from_promise(*this)};\n }\n\n suspend_always yield_value(int x) noexcept \n {\n val=x;\n return {};\n }\n };\n\n coroutine_handle coro;\n\n TreeWalker(coroutine_handle h): coro(h) {}\n\n ~TreeWalker()\n {\n if(coro) coro.destroy();\n }\n\n // Define an iterator type to work with the coroutine\n class Iterator\n {\n const coroutine_handle* m_h = nullptr;\n\n public:\n Iterator() = default;\n constexpr Iterator(const coroutine_handle* h) : m_h(h){}\n\n Iterator& operator++()\n {\n m_h->resume();\n return *this;\n }\n\n Iterator operator++(int)\n {\n auto old(*this);\n m_h->resume();\n return old;\n }\n\n int operator*() const\n {\n return m_h->promise().val;\n }\n\n bool operator!=(monostate) const noexcept\n {\n return !m_h->done();\n return m_h && !m_h->done();\n }\n\n bool operator==(monostate) const noexcept\n {\n return !operator!=(monostate{});\n }\n };\n\n constexpr Iterator begin() const noexcept\n {\n return Iterator(&coro);\n }\n\n constexpr monostate end() const noexcept\n {\n return monostate{};\n }\n};\n\n// Allow the iterator to be used like a standard library iterator\nnamespace std {\n template<>\n class iterator_traits\n {\n public:\n using difference_type = std::ptrdiff_t;\n using size_type = std::size_t;\n using value_type = int;\n using pointer = int*;\n using reference = int&;\n using iterator_category = std::input_iterator_tag;\n };\n}\n\n// A coroutine that iterates though all of the fringe nodes\nTreeWalker WalkFringe(const BinaryTree& tree)\n{\n if(tree)\n {\n auto& left = tree.LeftChild();\n auto& right = tree.RightChild();\n if(!left && !right)\n {\n // a fringe node because it has no children\n co_yield tree.Value();\n }\n\n for(auto v : WalkFringe(left))\n {\n co_yield v;\n }\n\n for(auto v : WalkFringe(right))\n {\n co_yield v;\n }\n }\n co_return;\n}\n\n// Print a tree\nvoid PrintTree(const BinaryTree& tree)\n{\n if(tree)\n {\n cout << \"(\";\n PrintTree(tree.LeftChild());\n cout << tree.Value();\n PrintTree(tree.RightChild());\n cout <<\")\";\n }\n}\n\n// Compare two trees\nvoid Compare(const BinaryTree& tree1, const BinaryTree& tree2)\n{\n // Create a lazy range for both trees\n auto walker1 = WalkFringe(tree1);\n auto walker2 = WalkFringe(tree2);\n \n // Compare the ranges.\n bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),\n walker2.begin(), walker2.end());\n \n // Print the results\n PrintTree(tree1);\n cout << (sameFringe ? \" has same fringe as \" : \" has different fringe than \");\n PrintTree(tree2);\n cout << \"\\n\";\n}\n\nint main()\n{\n // Create two trees that that are different but have the same fringe nodes\n BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,\n BinaryTree{77, BinaryTree{9}}});\n BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{\n BinaryTree{3}, 77, BinaryTree{9}}});\n // Create a tree with a different fringe\n BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});\n\n // Compare the trees\n Compare(tree1, tree2);\n Compare(tree1, tree3);\n}"} {"title": "Selectively replace multiple instances of a character within a string", "language": "C++", "task": "Task\nThis is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.\n\nGiven the string: \"abracadabra\", replace programatically:\n\n* the first 'a' with 'A'\n* the second 'a' with 'B'\n* the fourth 'a' with 'C'\n* the fifth 'a' with 'D'\n* the first 'b' with 'E'\n* the second 'r' with 'F'\n\nNote that there is no replacement for the third 'a', second 'b' or first 'r'.\n\nThe answer should, of course, be : \"AErBcadCbFD\".\n\n\n", "solution": "#include \n#include \n#include \n\nint main()\n{\n std::map rep = \n {{'a', \"DCaBA\"}, // replacement string is reversed\n {'b', \"E\"},\n {'r', \"Fr\"}};\n\n std::string magic = \"abracadabra\";\n\n for(auto it = magic.begin(); it != magic.end(); ++it)\n {\n if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())\n {\n *it = f->second.back();\n f->second.pop_back();\n }\n }\n\n std::cout << magic << \"\\n\";\n}"} {"title": "Self-describing numbers", "language": "C++", "task": "{{task}}There are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example, '''2020''' is a four-digit self describing number:\n\n* position 0 has value 2 and there are two 0s in the number;\n* position 1 has value 0 and there are no 1s in the number;\n* position 2 has value 2 and there are two 2s;\n* position 3 has value 0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.\n\n\n;Task Description\n# Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n# As an optional stretch goal - generate and display the set of self-describing numbers.\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-referential sequence]]\n* [[Spelling of ordinal numbers]]\n\n", "solution": "#include \n \n//--------------------------------------------------------------------------------------------------\ntypedef unsigned long long bigint;\n \n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n \n//--------------------------------------------------------------------------------------------------\nclass sdn\n{\npublic:\n bool check( bigint n )\n {\n\tint cc = digitsCount( n );\n\treturn compare( n, cc );\n }\n \n void displayAll( bigint s )\n {\n\tfor( bigint y = 1; y < s; y++ )\n\t if( check( y ) )\n\t\tcout << y << \" is a Self-Describing Number.\" << endl;\n }\n \nprivate:\n bool compare( bigint n, int cc )\n {\n\tbigint a;\n\twhile( cc )\n\t{\n\t cc--; a = n % 10;\n\t if( dig[cc] != a ) return false;\n\t n -= a; n /= 10;\n\t}\n\treturn true;\n }\n \n int digitsCount( bigint n )\n {\n\tint cc = 0; bigint a;\n\tmemset( dig, 0, sizeof( dig ) );\n\twhile( n )\n\t{\n\t a = n % 10; dig[a]++;\n\t cc++ ; n -= a; n /= 10;\n\t}\n\treturn cc;\n }\n \n int dig[10];\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n sdn s;\n s. displayAll( 1000000000000 );\n cout << endl << endl; system( \"pause\" );\n \n bigint n;\n while( true )\n {\n\tsystem( \"cls\" );\n\tcout << \"Enter a positive whole number ( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tif( s.check( n ) ) cout << n << \" is\";\n\telse cout << n << \" is NOT\";\n\tcout << \" a Self-Describing Number!\" << endl << endl;\n\tsystem( \"pause\" );\n }\n \n return 0;\n}\n"} {"title": "Self numbers", "language": "C++ from Java", "task": "A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.\n\nThe task is:\n Display the first 50 self numbers;\n I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.\n\n224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.\n\n;See also: \n\n;*OEIS: A003052 - Self numbers or Colombian numbers\n;*Wikipedia: Self numbers\n\n", "solution": "#include \n#include \n#include \n\nconst int MC = 103 * 1000 * 10000 + 11 * 9 + 1;\nstd::array SV;\n\nvoid sieve() {\n std::array dS;\n for (int a = 9, i = 9999; a >= 0; a--) {\n for (int b = 9; b >= 0; b--) {\n for (int c = 9, s = a + b; c >= 0; c--) {\n for (int d = 9, t = s + c; d >= 0; d--) {\n dS[i--] = t + d;\n }\n }\n }\n }\n for (int a = 0, n = 0; a < 103; a++) {\n for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) {\n for (int c = 0, s = d + dS[b] + n; c < 10000; c++) {\n SV[dS[c] + s++] = true;\n }\n }\n }\n}\n\nint main() {\n sieve();\n\n std::cout << \"The first 50 self numbers are:\\n\";\n for (int i = 0, count = 0; count <= 50; i++) {\n if (!SV[i]) {\n count++;\n if (count <= 50) {\n std::cout << i << ' ';\n } else {\n std::cout << \"\\n\\n Index Self number\\n\";\n }\n }\n }\n for (int i = 0, limit = 1, count = 0; i < MC; i++) {\n if (!SV[i]) {\n if (++count == limit) {\n //System.out.printf(\"%,12d %,13d%n\", count, i);\n std::cout << std::setw(12) << count << \" \" << std::setw(13) << i << '\\n';\n limit *= 10;\n }\n }\n }\n\n return 0;\n}"} {"title": "Semordnilap", "language": "C++", "task": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: ''lager'' and ''regal''\n \n;Task\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nint main() {\n std::ifstream input(\"unixdict.txt\");\n if (input) {\n std::set words; // previous words\n std::string word; // current word\n size_t count = 0; // pair count\n\n while (input >> word) {\n std::string drow(word.rbegin(), word.rend()); // reverse\n if (words.find(drow) == words.end()) {\n // pair not found\n words.insert(word);\n } else {\n // pair found\n if (count++ < 5)\n std::cout << word << ' ' << drow << '\\n';\n }\n }\n std::cout << \"\\nSemordnilap pairs: \" << count << '\\n';\n return 0;\n } else\n return 1; // couldn't open input file\n}"} {"title": "Sequence: nth number with exactly n divisors", "language": "C++ from Java", "task": "Calculate the sequence where each term an is the nth that has '''n''' divisors.\n\n;Task\n\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n;See also\n\n:*OEIS:A073916\n\n;Related tasks\n\n:*[[Sequence: smallest number greater than previous term with exactly n divisors]]\n:*[[Sequence: smallest number with exactly n divisors]]\n\n", "solution": "#include \n#include \n\nstd::vector smallPrimes;\n\nbool is_prime(size_t test) {\n if (test < 2) {\n return false;\n }\n if (test % 2 == 0) {\n return test == 2;\n }\n for (size_t d = 3; d * d <= test; d += 2) {\n if (test % d == 0) {\n return false;\n }\n }\n return true;\n}\n\nvoid init_small_primes(size_t numPrimes) {\n smallPrimes.push_back(2);\n\n int count = 0;\n for (size_t n = 3; count < numPrimes; n += 2) {\n if (is_prime(n)) {\n smallPrimes.push_back(n);\n count++;\n }\n }\n}\n\nsize_t divisor_count(size_t n) {\n size_t count = 1;\n while (n % 2 == 0) {\n n /= 2;\n count++;\n }\n for (size_t d = 3; d * d <= n; d += 2) {\n size_t q = n / d;\n size_t r = n % d;\n size_t dc = 0;\n while (r == 0) {\n dc += count;\n n = q;\n q = n / d;\n r = n % d;\n }\n count += dc;\n }\n if (n != 1) {\n count *= 2;\n }\n return count;\n}\n\nuint64_t OEISA073916(size_t n) {\n if (is_prime(n)) {\n return (uint64_t) pow(smallPrimes[n - 1], n - 1);\n }\n\n size_t count = 0;\n uint64_t result = 0;\n for (size_t i = 1; count < n; i++) {\n if (n % 2 == 1) {\n // The solution for an odd (non-prime) term is always a square number\n size_t root = (size_t) sqrt(i);\n if (root * root != i) {\n continue;\n }\n }\n if (divisor_count(i) == n) {\n count++;\n result = i;\n }\n }\n return result;\n}\n\nint main() {\n const int MAX = 15;\n init_small_primes(MAX);\n for (size_t n = 1; n <= MAX; n++) {\n if (n == 13) {\n std::cout << \"A073916(\" << n << \") = One more bit needed to represent result.\\n\";\n } else {\n std::cout << \"A073916(\" << n << \") = \" << OEISA073916(n) << '\\n';\n }\n }\n\n return 0;\n}"} {"title": "Sequence: smallest number greater than previous term with exactly n divisors", "language": "C++ from C", "task": "Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;See also\n:* OEIS:A069654\n\n\n;Related tasks\n:* [[Sequence: smallest number with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n", "solution": "#include \n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n int count = 0;\n for (int i = 1; i * i <= n; ++i) {\n if (!(n % i)) {\n if (i == n / i)\n count++;\n else\n count += 2;\n }\n }\n return count;\n}\n\nint main() {\n cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n for (int i = 1, next = 1; next <= MAX; ++i) {\n if (next == count_divisors(i)) { \n cout << i << \" \";\n next++;\n }\n }\n cout << endl;\n return 0;\n}"} {"title": "Sequence: smallest number greater than previous term with exactly n divisors", "language": "C++ from Pascal", "task": "Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;See also\n:* OEIS:A069654\n\n\n;Related tasks\n:* [[Sequence: smallest number with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n", "solution": "#include \n#include \n\nusing namespace std::chrono;\n\nconst int MAX = 32;\n \nunsigned int getDividersCnt(unsigned int n) {\n unsigned int d = 3, q, dRes, res = 1;\n while (!(n & 1)) { n >>= 1; res++; }\n while ((d * d) <= n) { q = n / d; if (n % d == 0) { dRes = 0;\n do { dRes += res; n = q; q /= d; } while (n % d == 0);\n res += dRes; } d += 2; } return n != 1 ? res << 1 : res; }\n\nint main() { unsigned int i, nxt, DivCnt;\n printf(\"The first %d anti-primes plus are: \", MAX);\n auto st = steady_clock::now(); i = nxt = 1; do {\n if ((DivCnt = getDividersCnt(i)) == nxt ) { printf(\"%d \", i);\n if ((++nxt > 4) && (getDividersCnt(nxt) == 2))\n i = (1 << (nxt - 1)) - 1; } i++; } while (nxt <= MAX);\n printf(\"%d ms\", (int)(duration(steady_clock::now() - st).count() * 1000));\n}"} {"title": "Sequence: smallest number with exactly n divisors", "language": "C++ from C", "task": "Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "#include \n\n#define MAX 15\n\nusing namespace std;\n\nint count_divisors(int n) {\n int count = 0;\n for (int i = 1; i * i <= n; ++i) {\n if (!(n % i)) {\n if (i == n / i)\n count++;\n else\n count += 2;\n }\n }\n return count;\n}\n\nint main() {\n int i, k, n, seq[MAX];\n for (i = 0; i < MAX; ++i) seq[i] = 0;\n cout << \"The first \" << MAX << \" terms of the sequence are:\" << endl;\n for (i = 1, n = 0; n < MAX; ++i) {\n k = count_divisors(i);\n if (k <= MAX && seq[k - 1] == 0) {\n seq[k - 1] = i;\n ++n;\n }\n }\n for (i = 0; i < MAX; ++i) cout << seq[i] << \" \";\n cout << endl;\n return 0;\n}"} {"title": "Set consolidation", "language": "C++", "task": "Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n;'''Example 1:'''\n:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n;'''Example 2:'''\n:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n;'''Example 3:'''\n:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n;'''Example 4:'''\n:The consolidation of the five sets:\n::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n:Is the two sets:\n::{A, C, B, D}, and {G, F, I, H, K}\n\n'''See also'''\n* Connected component (graph theory)\n* [[Range consolidation]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n// Consolidation using a brute force approach\nvoid SimpleConsolidate(vector>& sets)\n{\n // Loop through the sets in reverse and consolidate them\n for(auto last = sets.rbegin(); last != sets.rend(); ++last)\n for(auto other = last + 1; other != sets.rend(); ++other)\n {\n bool hasIntersection = any_of(last->begin(), last->end(), \n [&](auto val)\n { return other->contains(val); });\n if(hasIntersection)\n {\n other->merge(*last);\n sets.pop_back();\n break;\n }\n }\n}\n\n// As a second approach, use the connected-component-finding-algorithm\n// from the C# entry to consolidate\nstruct Node\n{\n char Value;\n Node* Parent = nullptr;\n}; \n\nNode* FindTop(Node& node)\n{\n auto top = &node;\n while (top != top->Parent) top = top->Parent;\n for(auto element = &node; element->Parent != top; )\n {\n // Point the elements to top to make it faster for the next time\n auto parent = element->Parent;\n element->Parent = top;\n element = parent;\n }\n return top;\n}\n\nvector> FastConsolidate(const vector>& sets)\n{\n unordered_map elements;\n for(auto& set : sets)\n {\n Node* top = nullptr;\n for(auto val : set)\n {\n auto itr = elements.find(val);\n if(itr == elements.end())\n {\n // A new value has been found\n auto& ref = elements[val] = Node{val, nullptr};\n if(!top) top = &ref;\n ref.Parent = top;\n }\n else\n {\n auto newTop = FindTop(itr->second);\n if(top)\n {\n top->Parent = newTop;\n itr->second.Parent = newTop;\n }\n else\n {\n top = newTop;\n }\n }\n }\n } \n\n unordered_map> groupedByTop;\n for(auto& e : elements)\n {\n auto& element = e.second;\n groupedByTop[FindTop(element)->Value].insert(element.Value);\n }\n\n vector> ret;\n for(auto& itr : groupedByTop)\n {\n ret.push_back(move(itr.second));\n }\n\n return ret;\n}\n\nvoid PrintSets(const vector>& sets)\n{\n for(const auto& set : sets)\n {\n cout << \"{ \";\n for(auto value : set){cout << value << \" \";}\n cout << \"} \"; \n }\n cout << \"\\n\";\n}\n\nint main()\n{\n const unordered_set AB{'A', 'B'}, CD{'C', 'D'}, DB{'D', 'B'}, \n HIJ{'H', 'I', 'K'}, FGH{'F', 'G', 'H'};\n \n vector > AB_CD {AB, CD};\n vector > AB_DB {AB, DB};\n vector > AB_CD_DB {AB, CD, DB};\n vector > HIJ_AB_CD_DB_FGH {HIJ, AB, CD, DB, FGH};\n\n PrintSets(FastConsolidate(AB_CD));\n PrintSets(FastConsolidate(AB_DB));\n PrintSets(FastConsolidate(AB_CD_DB));\n PrintSets(FastConsolidate(HIJ_AB_CD_DB_FGH));\n\n SimpleConsolidate(AB_CD);\n SimpleConsolidate(AB_DB);\n SimpleConsolidate(AB_CD_DB);\n SimpleConsolidate(HIJ_AB_CD_DB_FGH);\n\n PrintSets(AB_CD);\n PrintSets(AB_DB);\n PrintSets(AB_CD_DB);\n PrintSets(HIJ_AB_CD_DB_FGH);\n}\n"} {"title": "Set of real numbers", "language": "C++ from Java", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "#include \n#include \n#include \n\n#define _USE_MATH_DEFINES\n#include \n\nenum RangeType {\n CLOSED,\n BOTH_OPEN,\n LEFT_OPEN,\n RIGHT_OPEN\n};\n\nclass RealSet {\nprivate:\n double low, high;\n double interval = 0.00001;\n std::function predicate;\n\npublic:\n RealSet(double low, double high, const std::function& predicate) {\n this->low = low;\n this->high = high;\n this->predicate = predicate;\n }\n\n RealSet(double start, double end, RangeType rangeType) {\n low = start;\n high = end;\n\n switch (rangeType) {\n case CLOSED:\n predicate = [start, end](double d) { return start <= d && d <= end; };\n break;\n case BOTH_OPEN:\n predicate = [start, end](double d) { return start < d && d < end; };\n break;\n case LEFT_OPEN:\n predicate = [start, end](double d) { return start < d && d <= end; };\n break;\n case RIGHT_OPEN:\n predicate = [start, end](double d) { return start <= d && d < end; };\n break;\n default:\n assert(!\"Unexpected range type encountered.\");\n }\n }\n\n bool contains(double d) const {\n return predicate(d);\n }\n\n RealSet unionSet(const RealSet& rhs) const {\n double low2 = fmin(low, rhs.low);\n double high2 = fmax(high, rhs.high);\n return RealSet(\n low2, high2,\n [this, &rhs](double d) { return predicate(d) || rhs.predicate(d); }\n );\n }\n\n RealSet intersect(const RealSet& rhs) const {\n double low2 = fmin(low, rhs.low);\n double high2 = fmax(high, rhs.high);\n return RealSet(\n low2, high2,\n [this, &rhs](double d) { return predicate(d) && rhs.predicate(d); }\n );\n }\n\n RealSet subtract(const RealSet& rhs) const {\n return RealSet(\n low, high,\n [this, &rhs](double d) { return predicate(d) && !rhs.predicate(d); }\n );\n }\n\n double length() const {\n if (isinf(low) || isinf(high)) return -1.0; // error value\n if (high <= low) return 0.0;\n\n double p = low;\n int count = 0;\n do {\n if (predicate(p)) count++;\n p += interval;\n } while (p < high);\n return count * interval;\n }\n\n bool empty() const {\n if (high == low) {\n return !predicate(low);\n }\n return length() == 0.0;\n }\n};\n\nint main() {\n using namespace std;\n\n RealSet a(0.0, 1.0, LEFT_OPEN);\n RealSet b(0.0, 2.0, RIGHT_OPEN);\n RealSet c(1.0, 2.0, LEFT_OPEN);\n RealSet d(0.0, 3.0, RIGHT_OPEN);\n RealSet e(0.0, 1.0, BOTH_OPEN);\n RealSet f(0.0, 1.0, CLOSED);\n RealSet g(0.0, 0.0, CLOSED);\n\n for (int i = 0; i <= 2; ++i) {\n cout << \"(0, 1] \u222a [0, 2) contains \" << i << \" is \" << boolalpha << a.unionSet(b).contains(i) << \"\\n\";\n cout << \"[0, 2) \u2229 (1, 2] contains \" << i << \" is \" << boolalpha << b.intersect(c).contains(i) << \"\\n\";\n cout << \"[0, 3) - (0, 1) contains \" << i << \" is \" << boolalpha << d.subtract(e).contains(i) << \"\\n\";\n cout << \"[0, 3) - [0, 1] contains \" << i << \" is \" << boolalpha << d.subtract(f).contains(i) << \"\\n\";\n cout << endl;\n }\n\n cout << \"[0, 0] is empty is \" << boolalpha << g.empty() << \"\\n\";\n cout << endl;\n\n RealSet aa(\n 0.0, 10.0,\n [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x * x)) > 0.5; }\n );\n RealSet bb(\n 0.0, 10.0,\n [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x)) > 0.5; }\n );\n auto cc = aa.subtract(bb);\n cout << \"Approximate length of A - B is \" << cc.length() << endl;\n\n return 0;\n}"} {"title": "Set right-adjacent bits", "language": "C++", "task": "Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000, \nand a zero or more integer n :\n* Output the result of setting the n bits to the right of any set bit in b \n(if those bits are present in b and therefore also preserving the width, e).\n \n'''Some examples:''' \n\n Set of examples showing how one bit in a nibble gets changed:\n \n n = 2; Width e = 4:\n \n Input b: 1000\n Result: 1110\n \n Input b: 0100\n Result: 0111\n \n Input b: 0010\n Result: 0011\n \n Input b: 0000\n Result: 0000\n \n Set of examples with the same input with set bits of varying distance apart:\n \n n = 0; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 010000000000100000000010000000010000000100000010000010000100010010\n \n n = 1; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011000000000110000000011000000011000000110000011000011000110011011\n \n n = 2; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011100000000111000000011100000011100000111000011100011100111011111\n \n n = 3; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011110000000111100000011110000011110000111100011110011110111111111\n\n'''Task:'''\n\n* Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e.\n* Use it to show, here, the results for the input examples above.\n* Print the output aligned in a way that allows easy checking by eye of the binary input vs output.\n\n", "solution": "#include \n#include \n\nvoid setRightAdjacent(std::string text, int32_t number) {\n\tstd::cout << \"n = \" << number << \", Width = \" << text.size() << \", Input: \" << text << std::endl;\n\n\tstd::string result = text;\n\tfor ( uint32_t i = 0; i < result.size(); i++ ) {\n\t\tif ( text[i] == '1' ) {\n\t\t\tfor ( uint32_t j = i + 1; j <= i + number && j < result.size(); j++ ) {\n\t\t\t\tresult[j] = '1';\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << std::string(16 + std::to_string(text.size()).size(), ' ') << \"Result: \" + result << \"\\n\" << std::endl;\n}\n\nint main() {\n\tsetRightAdjacent(\"1000\", 2);\n\tsetRightAdjacent(\"0100\", 2);\n\tsetRightAdjacent(\"0010\", 2);\n\tsetRightAdjacent(\"0000\", 2);\n\n\tstd::string test = \"010000000000100000000010000000010000000100000010000010000100010010\";\n\tsetRightAdjacent(test, 0);\n\tsetRightAdjacent(test, 1);\n\tsetRightAdjacent(test, 2);\n\tsetRightAdjacent(test, 3);\n}\n\n"} {"title": "Shoelace formula for polygonal area", "language": "C++ from D", "task": "Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:\n\nabs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -\n (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])\n ) / 2\n(Where abs returns the absolute value)\n\n;Task:\nWrite a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:\n (3,4), (5,11), (12,8), (9,5), and (5,6) \n\n\nShow the answer here, on this page.\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\ndouble shoelace(vector> points) {\n\tdouble leftSum = 0.0;\n\tdouble rightSum = 0.0;\n\n\tfor (int i = 0; i < points.size(); ++i) {\n\t\tint j = (i + 1) % points.size();\n\t\tleftSum += points[i].first * points[j].second;\n\t\trightSum += points[j].first * points[i].second;\n\t}\n\n\treturn 0.5 * abs(leftSum - rightSum);\n}\n\nvoid main() {\n\tvector> points = {\n\t\tmake_pair( 3, 4),\n\t\tmake_pair( 5, 11),\n\t\tmake_pair(12, 8),\n\t\tmake_pair( 9, 5),\n\t\tmake_pair( 5, 6),\n\t};\n\n\tauto ans = shoelace(points);\n\tcout << ans << endl;\n}"} {"title": "Shortest common supersequence", "language": "C++ from Java", "task": "The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task.\n\n\n;;Task:\nGiven two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique.\n\nDemonstrate this by printing s where u = \"abcbdab\" and v = \"bdcaba\".\n\n\n\n;Also see:\n* Wikipedia: shortest common supersequence \n\n", "solution": "#include \n\nstd::string scs(std::string x, std::string y) {\n if (x.empty()) {\n return y;\n }\n if (y.empty()) {\n return x;\n }\n if (x[0] == y[0]) {\n return x[0] + scs(x.substr(1), y.substr(1));\n }\n if (scs(x, y.substr(1)).size() <= scs(x.substr(1), y).size()) {\n return y[0] + scs(x, y.substr(1));\n } else {\n return x[0] + scs(x.substr(1), y);\n }\n}\n\nint main() {\n auto res = scs(\"abcbdab\", \"bdcaba\");\n std::cout << res << '\\n';\n return 0;\n}"} {"title": "Show ASCII table", "language": "C++", "task": "Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.\n\n\n\n", "solution": "#include \n#include \n#include \n\ninline constexpr auto HEIGHT = 16;\ninline constexpr auto WIDTH = 6;\ninline constexpr auto ASCII_START = 32;\n// ASCII special characters\ninline constexpr auto SPACE = 32;\ninline constexpr auto DELETE = 127;\n\nstd::string displayAscii(char ascii) {\n switch (ascii) {\n case SPACE: return \"Spc\";\n case DELETE: return \"Del\";\n default: return std::string(1, ascii);\n }\n}\n\nint main() {\n for (std::size_t row = 0; row < HEIGHT; ++row) {\n for (std::size_t col = 0; col < WIDTH; ++col) {\n const auto ascii = ASCII_START + row + col * HEIGHT; \n std::cout << std::right << std::setw(3) << ascii << \" : \" << std::left << std::setw(6) << displayAscii(ascii); \n }\n std::cout << '\\n';\n }\n}"} {"title": "Sierpinski pentagon", "language": "C++ from D", "task": "Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.\n\n\n;See also\n* Sierpinski pentagon\n\n", "solution": "#include \n#include \n\n#define _USE_MATH_DEFINES\n#include \n\nconstexpr double degrees(double deg) {\n const double tau = 2.0 * M_PI;\n return deg * tau / 360.0;\n}\n\nconst double part_ratio = 2.0 * cos(degrees(72));\nconst double side_ratio = 1.0 / (part_ratio + 2.0);\n\n/// Define a position\nstruct Point {\n double x, y;\n\n friend std::ostream& operator<<(std::ostream& os, const Point& p);\n};\n\nstd::ostream& operator<<(std::ostream& os, const Point& p) {\n auto f(std::cout.flags());\n os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';\n std::cout.flags(f);\n return os;\n}\n\n/// Mock turtle implementation sufficiant to handle \"drawing\" the pentagons\nstruct Turtle {\nprivate:\n Point pos;\n double theta;\n bool tracing;\n\npublic:\n Turtle() : theta(0.0), tracing(false) {\n pos.x = 0.0;\n pos.y = 0.0;\n }\n\n Turtle(double x, double y) : theta(0.0), tracing(false) {\n pos.x = x;\n pos.y = y;\n }\n\n Point position() {\n return pos;\n }\n void position(const Point& p) {\n pos = p;\n }\n\n double heading() {\n return theta;\n }\n void heading(double angle) {\n theta = angle;\n }\n\n /// Move the turtle through space\n void forward(double dist) {\n auto dx = dist * cos(theta);\n auto dy = dist * sin(theta);\n\n pos.x += dx;\n pos.y += dy;\n\n if (tracing) {\n std::cout << pos;\n }\n }\n\n /// Turn the turtle\n void right(double angle) {\n theta -= angle;\n }\n\n /// Start/Stop exporting the points of the polygon\n void begin_fill() {\n if (!tracing) {\n std::cout << \"\\n\";\n tracing = false;\n }\n }\n};\n\n/// Use the provided turtle to draw a pentagon of the specified size\nvoid pentagon(Turtle& turtle, double size) {\n turtle.right(degrees(36));\n turtle.begin_fill();\n for (size_t i = 0; i < 5; i++) {\n turtle.forward(size);\n turtle.right(degrees(72));\n }\n turtle.end_fill();\n}\n\n/// Draw a sierpinski pentagon of the desired order\nvoid sierpinski(int order, Turtle& turtle, double size) {\n turtle.heading(0.0);\n auto new_size = size * side_ratio;\n\n if (order-- > 1) {\n // create four more turtles\n for (size_t j = 0; j < 4; j++) {\n turtle.right(degrees(36));\n\n double small = size * side_ratio / part_ratio;\n auto distList = { small, size, size, small };\n auto dist = *(distList.begin() + j);\n\n Turtle spawn{ turtle.position().x, turtle.position().y };\n spawn.heading(turtle.heading());\n spawn.forward(dist);\n\n // recurse for each spawned turtle\n sierpinski(order, spawn, new_size);\n }\n\n // recurse for the original turtle\n sierpinski(order, turtle, new_size);\n } else {\n // The bottom has been reached for this turtle\n pentagon(turtle, size);\n }\n if (order > 0) {\n std::cout << '\\n';\n }\n}\n\n/// Run the generation of a P(5) sierpinksi pentagon\nint main() {\n const int order = 5;\n double size = 500;\n\n Turtle turtle{ size / 2.0, size };\n\n std::cout << \"\\n\";\n std::cout << \"\\n\";\n std::cout << \"\\n\";\n\n size *= part_ratio;\n sierpinski(order, turtle, size);\n\n std::cout << \"\";\n}"} {"title": "Sierpinski triangle/Graphical", "language": "C++", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": "#include \n#include \n#include \n \nconst int BMP_SIZE = 612;\n \nclass myBitmap {\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap() {\n DeleteObject( pen ); DeleteObject( brush );\n DeleteDC( hdc ); DeleteObject( bmp );\n }\n bool create( int w, int h ) {\n BITMAPINFO bi;\n ZeroMemory( &bi, sizeof( bi ) );\n bi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n HDC dc = GetDC( GetConsoleWindow() );\n bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n if( !bmp ) return false;\n hdc = CreateCompatibleDC( dc );\n SelectObject( hdc, bmp );\n ReleaseDC( GetConsoleWindow(), dc );\n width = w; height = h;\n return true;\n }\n void clear( BYTE clr = 0 ) {\n memset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n void setBrushColor( DWORD bClr ) {\n if( brush ) DeleteObject( brush );\n brush = CreateSolidBrush( bClr );\n SelectObject( hdc, brush );\n }\n void setPenColor( DWORD c ) {\n clr = c; createPen();\n }\n void setPenWidth( int w ) {\n wid = w; createPen();\n }\n void saveBitmap( std::string path ) {\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap;\n DWORD wb;\n GetObject( bmp, sizeof( bitmap ), &bitmap );\n DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, \n FILE_ATTRIBUTE_NORMAL, NULL );\n WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n CloseHandle( file );\n delete [] dwpBits;\n }\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\nprivate:\n void createPen() {\n if( pen ) DeleteObject( pen );\n pen = CreatePen( PS_SOLID, wid, clr );\n SelectObject( hdc, pen );\n }\n HBITMAP bmp; HDC hdc;\n HPEN pen; HBRUSH brush;\n void *pBits; int width, height, wid;\n DWORD clr;\n};\nclass sierpinski {\npublic:\n void draw( int o ) {\n colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;\n colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;\n bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); \n drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );\n bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); \n LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );\n LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( \"./st.bmp\" );\n }\nprivate:\n void drawTri( HDC dc, float l, float t, float r, float b, int i ) {\n float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; \n if( i ) {\n drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );\n drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );\n drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );\n }\n bmp.setPenColor( colors[i % 6] );\n MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL );\n LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) );\n LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );\n LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) );\n }\n myBitmap bmp;\n DWORD colors[6];\n};\nint main(int argc, char* argv[]) {\n sierpinski s; s.draw( 12 );\n return 0;\n}\n"} {"title": "Smith numbers", "language": "C++", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as ''joke'' numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: [Smith number].\n* from MathWorld: [Smith number]. \n* from OEIS A6753: [OEIS sequence A6753].\n* from OEIS A104170: [Number of Smith numbers below 10^n]. \n* from The Prime pages: [Smith numbers].\n\n", "solution": "#include \n#include \n#include \n\nvoid primeFactors( unsigned n, std::vector& r ) {\n int f = 2; if( n == 1 ) r.push_back( 1 );\n else {\n while( true ) {\n if( !( n % f ) ) {\n r.push_back( f );\n n /= f; if( n == 1 ) return;\n }\n else f++;\n }\n }\n}\nunsigned sumDigits( unsigned n ) {\n unsigned sum = 0, m;\n while( n ) {\n m = n % 10; sum += m;\n n -= m; n /= 10;\n }\n return sum;\n}\nunsigned sumDigits( std::vector& v ) {\n unsigned sum = 0;\n for( std::vector::iterator i = v.begin(); i != v.end(); i++ ) {\n sum += sumDigits( *i );\n }\n return sum;\n}\nvoid listAllSmithNumbers( unsigned n ) {\n std::vector pf;\n for( unsigned i = 4; i < n; i++ ) {\n primeFactors( i, pf ); if( pf.size() < 2 ) continue;\n if( sumDigits( i ) == sumDigits( pf ) )\n std::cout << std::setw( 4 ) << i << \" \";\n pf.clear();\n }\n std::cout << \"\\n\\n\";\n}\nint main( int argc, char* argv[] ) {\n listAllSmithNumbers( 10000 );\n return 0;\n}\n"} {"title": "Soloway's recurring rainfall", "language": "C++", "task": "Soloway's Recurring Rainfall is commonly used to assess general programming knowledge by requiring basic program structure, input/output, and program exit procedure.\n\n'''The problem:'''\n\nWrite a program that will read in integers and output their average. Stop reading when the value 99999 is input.\n\nFor languages that aren't traditionally interactive, the program can read in values as makes sense and stopping once 99999 is encountered. The classic rainfall problem comes from identifying success of Computer Science programs with their students, so the original problem statement is written above -- though it may not strictly apply to a given language in the modern era.\n\n'''Implementation Details:'''\n* Only Integers are to be accepted as input\n* Output should be floating point\n* Rainfall can be negative (https://www.geographyrealm.com/what-is-negative-rainfall/)\n* For languages where the user is inputting data, the number of data inputs can be \"infinite\"\n* A complete implementation should handle error cases reasonably (asking the user for more input, skipping the bad value when encountered, etc)\n\nThe purpose of this problem, as originally proposed in the 1980's through its continued use today, is to just show fundamentals of CS: iteration, branching, program structure, termination, management of data types, input/output (where applicable), etc with things like input validation or management of numerical limits being more \"advanced\". It isn't meant to literally be a rainfall calculator so implementations should strive to implement the solution clearly and simply.\n\n'''References:'''\n* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf\n* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf\n* https://en.wikipedia.org/wiki/Moving_average#Cumulative_average\n\n\n", "solution": "#include \n#include \n\nint main()\n{\n\tfloat currentAverage = 0;\n\tunsigned int currentEntryNumber = 0;\n\t\n\tfor (;;)\n\t{\n\t\tint entry;\n\t\t\n\t\tstd::cout << \"Enter rainfall int, 99999 to quit: \";\n\t\tstd::cin >> entry;\n\t\t\n\t\tif (!std::cin.fail())\n\t\t{\n\t\t\tif (entry == 99999)\n\t\t\t{\n\t\t\t\tstd::cout << \"User requested quit.\" << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurrentEntryNumber++;\n\t\t\t\tcurrentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage;\n\t\t\t\t\n\t\t\t\tstd::cout << \"New Average: \" << currentAverage << std::endl;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"Invalid input\" << std::endl;\n\t\t\tstd::cin.clear();\n\t\t\tstd::cin.ignore(std::numeric_limits::max(), '\\n');\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n"} {"title": "Solve a Hidato puzzle", "language": "C++", "task": "The task is to write a program which solves Hidato (aka Hidoku) puzzles.\n\nThe rules are:\n* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.\n** The grid is not necessarily rectangular.\n** The grid may have holes in it.\n** The grid is always connected.\n** The number \"1\" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.\n** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.\n* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from \"1\" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).\n** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.\n** A square may only contain one number.\n* In a proper Hidato puzzle, the solution is unique.\n\nFor example the following problem\nSample Hidato problem, from Wikipedia\n\nhas the following solution, with path marked on it:\n\nSolution to sample Hidato problem\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]];\n\n", "solution": "#include \n#include \n#include \n#include \n\n//------------------------------------------------------------------------------\nusing namespace std;\n\n//------------------------------------------------------------------------------\nstruct node\n{\n int val;\n unsigned char neighbors;\n};\n//------------------------------------------------------------------------------\nclass hSolver\n{\npublic:\n hSolver()\n {\n\tdx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1;\n\tdy[0] = -1; dy[1] = -1; dy[2] = -1; dy[3] = 0; dy[4] = 0; dy[5] = 1; dy[6] = 1; dy[7] = 1;\n }\n\n void solve( vector& puzz, int max_wid )\n {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = 0;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\tweHave = new bool[len + 1]; memset( weHave, 0, len + 1 );\n\t\t\n\tfor( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t if( ( *i ) == \"*\" ) { arr[c++].val = -1; continue; }\n\t arr[c].val = atoi( ( *i ).c_str() );\n\t if( arr[c].val > 0 ) weHave[arr[c].val] = true;\n\t if( max < arr[c].val ) max = arr[c].val;\n\t c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t if( ( *i ) == \".\" )\n\t {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t }\n\t c++;\n\t}\n\tdelete [] arr;\n\tdelete [] weHave;\n }\n\nprivate:\n bool search( int x, int y, int w )\n {\n\tif( w == max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\tif( weHave[w] )\n\t{\n\t for( int d = 0; d < 8; d++ )\n\t {\n\t\tif( n->neighbors & ( 1 << d ) )\n\t\t{\n\t\t int a = x + dx[d], b = y + dy[d];\n\t\t if( arr[a + b * wid].val == w )\n\t\t if( search( a, b, w + 1 ) ) return true;\n\t\t}\n\t }\n\t return false;\n\t}\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t if( n->neighbors & ( 1 << d ) )\n\t {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t arr[a + b * wid].val = w;\n\t\t if( search( a, b, w + 1 ) ) return true;\n\t\t arr[a + b * wid].val = 0;\n\t\t}\n\t }\n\t}\n\treturn false;\n }\n\n unsigned char getNeighbors( int x, int y )\n {\n\tunsigned char c = 0; int m = -1, a, b;\n\tfor( int yy = -1; yy < 2; yy++ )\n\t for( int xx = -1; xx < 2; xx++ )\n\t {\n\t\tif( !yy && !xx ) continue;\n\t\tm++; a = x + xx, b = y + yy;\n\t\tif( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t\tif( arr[a + b * wid].val > -1 ) c |= ( 1 << m );\n\t }\n\treturn c;\n }\n\n void solveIt()\n {\n\tint x, y; findStart( x, y );\n\tif( x < 0 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, 2 );\n }\n\n void findStart( int& x, int& y )\n {\n\tfor( int b = 0; b < hei; b++ )\n\t for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 1 ) { x = a; y = b; return; }\n\tx = y = -1;\n }\n\n int wid, hei, max, dx[8], dy[8];\n node* arr;\n bool* weHave;\n};\n//------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n int wid;\n string p = \". 33 35 . . * * * . . 24 22 . * * * . . . 21 . . * * . 26 . 13 40 11 * * 27 . . . 9 . 1 * * * . . 18 . . * * * * * . 7 . . * * * * * * 5 .\"; wid = 8;\n //string p = \"54 . 60 59 . 67 . 69 . . 55 . . 63 65 . 72 71 51 50 56 62 . * * * * . . . 14 * * 17 . * 48 10 11 * 15 . 18 . 22 . 46 . * 3 . 19 23 . . 44 . 5 . 1 33 32 . . 43 7 . 36 . 27 . 31 42 . . 38 . 35 28 . 30\"; wid = 9;\n //string p = \". 58 . 60 . . 63 66 . 57 55 59 53 49 . 65 . 68 . 8 . . 50 . 46 45 . 10 6 . * * * . 43 70 . 11 12 * * * 72 71 . . 14 . * * * 30 39 . 15 3 17 . 28 29 . . 40 . . 19 22 . . 37 36 . 1 20 . 24 . 26 . 34 33\"; wid = 9;\n\n istringstream iss( p ); vector puzz;\n copy( istream_iterator( iss ), istream_iterator(), back_inserter >( puzz ) );\n hSolver s; s.solve( puzz, wid );\n\n int c = 0;\n for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t cout << ( *i ) << \" \";\n\t}\n\telse cout << \" \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n }\n cout << endl << endl;\n return system( \"pause\" );\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Solve a Holy Knight's tour", "language": "C++", "task": "Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct node\n{\n int val;\n unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n nSolver()\n {\n\tdx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2;\n\tdx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2;\n\tdx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; \n\tdx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1;\n }\n\n void solve( vector& puzz, int max_wid )\n {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t arr[c].val = atoi( ( *i ).c_str() );\n\t c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t if( ( *i ) == \".\" )\n\t {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t }\n\t c++;\n\t}\n\tdelete [] arr;\n }\n\nprivate:\n bool search( int x, int y, int w )\n {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t if( n->neighbors & ( 1 << d ) )\n\t {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t arr[a + b * wid].val = w;\n\t\t if( search( a, b, w + 1 ) ) return true;\n\t\t arr[a + b * wid].val = 0;\n\t\t}\n\t }\n\t}\n\treturn false;\n }\n\n unsigned char getNeighbors( int x, int y )\n {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t a = x + dx[xx], b = y + dy[xx];\n\t if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n }\n\n void solveIt()\n {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n }\n\n void findStart( int& x, int& y, int& z )\n {\n\tz = 99999;\n\tfor( int b = 0; b < hei; b++ )\n\t for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) \n\t\t{ \n\t\t x = a; y = b;\n\t\t z = arr[a + wid * b].val;\n\t\t}\n\n }\n\n int wid, hei, max, dx[8], dy[8];\n node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n int wid; string p;\n //p = \"* . . . * * * * * . * . . * * * * . . . . . . . . . . * * . * . . * . * * . . . 1 . . . . . . * * * . . * . * * * * * . . . * *\"; wid = 8;\n p = \"* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * \"; wid = 13;\n istringstream iss( p ); vector puzz;\n copy( istream_iterator( iss ), istream_iterator(), back_inserter >( puzz ) );\n nSolver s; s.solve( puzz, wid );\n int c = 0;\n for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t cout << ( *i ) << \" \";\n }\n\telse cout << \" \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n }\n cout << endl << endl;\n return system( \"pause\" );\n}\n"} {"title": "Solve a Hopido puzzle", "language": "C++", "task": "Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:\n\n\"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7x7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!\"\n\nKnowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.\n\nExample:\n\n . 0 0 . 0 0 .\n 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0\n . 0 0 0 0 0 .\n . . 0 0 0 . .\n . . . 0 . . .\n\nExtra credits are available for other interesting designs.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct node\n{\n int val;\n unsigned char neighbors;\n};\n\nclass nSolver\n{\npublic:\n nSolver()\n {\n\tdx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2;\n\tdx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2;\n\tdx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; \n\tdx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3;\n }\n\n void solve( vector& puzz, int max_wid )\n {\n\tif( puzz.size() < 1 ) return;\n\twid = max_wid; hei = static_cast( puzz.size() ) / wid;\n\tint len = wid * hei, c = 0; max = len;\n\tarr = new node[len]; memset( arr, 0, len * sizeof( node ) );\n\n\tfor( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t if( ( *i ) == \"*\" ) { max--; arr[c++].val = -1; continue; }\n\t arr[c].val = atoi( ( *i ).c_str() );\n\t c++;\n\t}\n\n\tsolveIt(); c = 0;\n\tfor( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n\t{\n\t if( ( *i ) == \".\" )\n\t {\n\t\tostringstream o; o << arr[c].val;\n\t\t( *i ) = o.str();\n\t }\n\t c++;\n\t}\n\tdelete [] arr;\n }\n\nprivate:\n bool search( int x, int y, int w )\n {\n\tif( w > max ) return true;\n\n\tnode* n = &arr[x + y * wid];\n\tn->neighbors = getNeighbors( x, y );\n\n\tfor( int d = 0; d < 8; d++ )\n\t{\n\t if( n->neighbors & ( 1 << d ) )\n\t {\n\t\tint a = x + dx[d], b = y + dy[d];\n\t\tif( arr[a + b * wid].val == 0 )\n\t\t{\n\t\t arr[a + b * wid].val = w;\n\t\t if( search( a, b, w + 1 ) ) return true;\n\t\t arr[a + b * wid].val = 0;\n\t\t}\n\t }\n\t}\n\treturn false;\n }\n\n unsigned char getNeighbors( int x, int y )\n {\n\tunsigned char c = 0; int a, b;\n\tfor( int xx = 0; xx < 8; xx++ )\n\t{\n\t a = x + dx[xx], b = y + dy[xx];\n\t if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;\n\t if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx );\n\t}\n\treturn c;\n }\n\n void solveIt()\n {\n\tint x, y, z; findStart( x, y, z );\n\tif( z == 99999 ) { cout << \"\\nCan't find start point!\\n\"; return; }\n\tsearch( x, y, z + 1 );\n }\n\n void findStart( int& x, int& y, int& z )\n {\n\tfor( int b = 0; b < hei; b++ )\n\t for( int a = 0; a < wid; a++ )\n\t\tif( arr[a + wid * b].val == 0 ) \n\t\t{ \n\t\t x = a; y = b; z = 1;\n\t\t arr[a + wid * b].val = z;\n\t\t return;\n\t\t}\n }\n\n int wid, hei, max, dx[8], dy[8];\n node* arr;\n};\n\nint main( int argc, char* argv[] )\n{\n int wid; string p;\n p = \"* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *\"; wid = 7;\n istringstream iss( p ); vector puzz;\n copy( istream_iterator( iss ), istream_iterator(), back_inserter >( puzz ) );\n nSolver s; s.solve( puzz, wid );\n int c = 0;\n for( vector::iterator i = puzz.begin(); i != puzz.end(); i++ )\n {\n\tif( ( *i ) != \"*\" && ( *i ) != \".\" )\n\t{\n\t if( atoi( ( *i ).c_str() ) < 10 ) cout << \"0\";\n\t cout << ( *i ) << \" \";\n\t}\n\telse cout << \" \";\n\tif( ++c >= wid ) { cout << endl; c = 0; }\n }\n cout << endl << endl;\n return system( \"pause\" );\n}\n"} {"title": "Solve a Numbrix puzzle", "language": "C++", "task": "Numbrix puzzles are similar to Hidato. \nThe most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). \nPublished puzzles also tend not to have holes in the grid and may not always indicate the end node. \nTwo examples follow:\n\n;Example 1\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 0 46 45 0 55 74 0 0\n 0 38 0 0 43 0 0 78 0\n 0 35 0 0 0 0 0 71 0\n 0 0 33 0 0 0 59 0 0\n 0 17 0 0 0 0 0 67 0\n 0 18 0 0 11 0 0 64 0\n 0 0 24 21 0 1 2 0 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 49 50 51 52 53 54 75 76 81\n 48 47 46 45 44 55 74 77 80\n 37 38 39 40 43 56 73 78 79\n 36 35 34 41 42 57 72 71 70\n 31 32 33 14 13 58 59 68 69\n 30 17 16 15 12 61 60 67 66\n 29 18 19 20 11 62 63 64 65\n 28 25 24 21 10 1 2 3 4\n 27 26 23 22 9 8 7 6 5\n\n;Example 2\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 11 12 15 18 21 62 61 0\n 0 6 0 0 0 0 0 60 0\n 0 33 0 0 0 0 0 57 0\n 0 32 0 0 0 0 0 56 0\n 0 37 0 1 0 0 0 73 0\n 0 38 0 0 0 0 0 72 0\n 0 43 44 47 48 51 76 77 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 9 10 13 14 19 20 63 64 65\n 8 11 12 15 18 21 62 61 66\n 7 6 5 16 17 22 59 60 67\n 34 33 4 3 24 23 58 57 68\n 35 32 31 2 25 54 55 56 69\n 36 37 30 1 26 53 74 73 70\n 39 38 29 28 27 52 75 72 71\n 40 43 44 47 48 51 76 77 78\n 41 42 45 46 49 50 81 80 79\n\n;Task\nWrite a program to solve puzzles of this ilk, \ndemonstrating your program by solving the above examples. \nExtra credit for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\ntypedef bitset<4> hood_t;\n\nstruct node\n{\n\tint val;\n\thood_t neighbors;\n};\n\nclass nSolver\n{\npublic:\n\n\tvoid solve(vector& puzz, int max_wid)\n\t{\n\t\tif (puzz.size() < 1) return;\n\t\twid = max_wid; \n\t\thei = static_cast(puzz.size()) / wid;\n\t\tmax = wid * hei;\n\t\tint len = max, c = 0;\n\t\tarr = vector(len, node({ 0, 0 }));\n\t\tweHave = vector(len + 1, false);\n\n\t\tfor (const auto& s : puzz)\n\t\t{\n\t\t\tif (s == \"*\") { max--; arr[c++].val = -1; continue; }\n\t\t\tarr[c].val = atoi(s.c_str());\n\t\t\tif (arr[c].val > 0) weHave[arr[c].val] = true;\n\t\t\tc++;\n\t\t}\n\n\t\tsolveIt(); c = 0;\n\t\tfor (auto&& s : puzz)\n\t\t{\n\t\t\tif (s == \".\")\n\t\t\t\ts = std::to_string(arr[c].val);\n\t\t\tc++;\n\t\t}\n\t}\n\nprivate:\n\tbool search(int x, int y, int w, int dr)\n\t{\n\t\tif ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;\n\n\t\tnode& n = arr[x + y * wid];\n\t\tn.neighbors = getNeighbors(x, y);\n\t\tif (weHave[w])\n\t\t{\n\t\t\tfor (int d = 0; d < 4; d++)\n\t\t\t{\n\t\t\t\tif (n.neighbors[d])\n\t\t\t\t{\n\t\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\t\tif (arr[a + b * wid].val == w)\n\t\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int d = 0; d < 4; d++)\n\t\t{\n\t\t\tif (n.neighbors[d])\n\t\t\t{\n\t\t\t\tint a = x + dx[d], b = y + dy[d];\n\t\t\t\tif (arr[a + b * wid].val == 0)\n\t\t\t\t{\n\t\t\t\t\tarr[a + b * wid].val = w;\n\t\t\t\t\tif (search(a, b, w + dr, dr)) \n\t\t\t\t\t\treturn true;\n\t\t\t\t\tarr[a + b * wid].val = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\thood_t getNeighbors(int x, int y)\n\t{\n\t\thood_t retval;\n\t\tfor (int xx = 0; xx < 4; xx++)\n\t\t{\n\t\t\tint a = x + dx[xx], b = y + dy[xx];\n\t\t\tif (a < 0 || b < 0 || a >= wid || b >= hei) \n\t\t\t\tcontinue;\n\t\t\tif (arr[a + b * wid].val > -1)\n\t\t\t\tretval.set(xx);\n\t\t}\n\t\treturn retval;\n\t}\n\n\tvoid solveIt()\n\t{\n\t\tint x, y, z; findStart(x, y, z);\n\t\tif (z == 99999) { cout << \"\\nCan't find start point!\\n\"; return; }\n\t\tsearch(x, y, z + 1, 1);\n\t\tif (z > 1) search(x, y, z - 1, -1);\n\t}\n\n\tvoid findStart(int& x, int& y, int& z)\n\t{\n\t\tz = 99999;\n\t\tfor (int b = 0; b < hei; b++)\n\t\tfor (int a = 0; a < wid; a++)\n\t\tif (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)\n\t\t{\n\t\t\tx = a; y = b;\n\t\t\tz = arr[a + wid * b].val;\n\t\t}\n\n\t}\n\n\tvector dx = vector({ -1, 1, 0, 0 });\n\tvector dy = vector({ 0, 0, -1, 1 });\n\tint wid, hei, max;\n\tvector arr;\n\tvector weHave;\n};\n\n//------------------------------------------------------------------------------\nint main(int argc, char* argv[])\n{\n\tint wid; string p;\n\t//p = \". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .\"; wid = 9;\n\t//p = \". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .\"; wid = 9;\n\tp = \"17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45\"; wid = 9;\n\n\tistringstream iss(p); vector puzz;\n\tcopy(istream_iterator(iss), istream_iterator(), back_inserter >(puzz));\n\tnSolver s; s.solve(puzz, wid);\n\n\tint c = 0;\n\tfor (const auto& s : puzz)\n\t{\n\t\tif (s != \"*\" && s != \".\")\n\t\t{\n\t\t\tif (atoi(s.c_str()) < 10) cout << \"0\";\n\t\t\tcout << s << \" \";\n\t\t}\n\t\telse cout << \" \";\n\t\tif (++c >= wid) { cout << endl; c = 0; }\n\t}\n\tcout << endl << endl;\n\treturn system(\"pause\");\n}\n"} {"title": "Sparkline in unicode", "language": "C++", "task": "A sparkline is a graph of successive values laid out horizontally \nwhere the height of the line is proportional to the values in succession.\n\n\n;Task:\nUse the following series of Unicode characters to create a program \nthat takes a series of numbers separated by one or more whitespace or comma characters \nand generates a sparkline-type bar graph of the values on a single line of output.\n\nThe eight characters: '########'\n(Unicode values U+2581 through U+2588).\n\nUse your program to show sparklines for the following input, \nhere on this page:\n# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\n# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \n:(note the mix of separators in this second case)!\n\n;Notes: \n* A space is not part of the generated sparkline.\n* The sparkline may be accompanied by simple statistics of the data such as its range.\n* A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:\n\n:: \"0, 1, 19, 20\" -> ####\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> ######\n:: (Aiming to use just three spark levels)\n\n:: It may be helpful to include these cases in output tests.\n* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nclass Sparkline {\n public:\n Sparkline(std::wstring &cs) : charset( cs ){\n }\n virtual ~Sparkline(){\n }\n\n void print(std::string spark){\n const char *delim = \", \";\n std::vector data;\n // Get first non-delimiter\n std::string::size_type last = spark.find_first_not_of(delim, 0);\n // Get end of token\n std::string::size_type pos = spark.find_first_of(delim, last);\n\n while( pos != std::string::npos || last != std::string::npos ){\n std::string tok = spark.substr(last, pos-last);\n // Convert to float:\n std::stringstream ss(tok);\n float entry;\n ss >> entry;\n\n data.push_back( entry );\n\n last = spark.find_first_not_of(delim, pos);\n pos = spark.find_first_of(delim, last);\n }\n\n // Get range of dataset\n float min = *std::min_element( data.begin(), data.end() );\n float max = *std::max_element( data.begin(), data.end() );\n\n float skip = (charset.length()-1) / (max - min);\n\n std::wcout<::const_iterator it;\n for(it = data.begin(); it != data.end(); it++){\n float v = ( (*it) - min ) * skip; \n std::wcout<\n#include \n#include \n\ntypedef std::uint64_t integer;\n\nstruct number_names {\n const char* cardinal;\n const char* ordinal;\n};\n\nconst number_names small[] = {\n { \"zero\", \"zeroth\" }, { \"one\", \"first\" }, { \"two\", \"second\" },\n { \"three\", \"third\" }, { \"four\", \"fourth\" }, { \"five\", \"fifth\" },\n { \"six\", \"sixth\" }, { \"seven\", \"seventh\" }, { \"eight\", \"eighth\" },\n { \"nine\", \"ninth\" }, { \"ten\", \"tenth\" }, { \"eleven\", \"eleventh\" },\n { \"twelve\", \"twelfth\" }, { \"thirteen\", \"thirteenth\" },\n { \"fourteen\", \"fourteenth\" }, { \"fifteen\", \"fifteenth\" },\n { \"sixteen\", \"sixteenth\" }, { \"seventeen\", \"seventeenth\" },\n { \"eighteen\", \"eighteenth\" }, { \"nineteen\", \"nineteenth\" }\n};\n\nconst number_names tens[] = {\n { \"twenty\", \"twentieth\" }, { \"thirty\", \"thirtieth\" },\n { \"forty\", \"fortieth\" }, { \"fifty\", \"fiftieth\" },\n { \"sixty\", \"sixtieth\" }, { \"seventy\", \"seventieth\" },\n { \"eighty\", \"eightieth\" }, { \"ninety\", \"ninetieth\" }\n};\n\nstruct named_number {\n const char* cardinal;\n const char* ordinal;\n integer number;\n};\n\nconst named_number named_numbers[] = {\n { \"hundred\", \"hundredth\", 100 },\n { \"thousand\", \"thousandth\", 1000 },\n { \"million\", \"millionth\", 1000000 },\n { \"billion\", \"billionth\", 1000000000 },\n { \"trillion\", \"trillionth\", 1000000000000 },\n { \"quadrillion\", \"quadrillionth\", 1000000000000000ULL },\n { \"quintillion\", \"quintillionth\", 1000000000000000000ULL }\n};\n\nconst char* get_name(const number_names& n, bool ordinal) {\n return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst char* get_name(const named_number& n, bool ordinal) {\n return ordinal ? n.ordinal : n.cardinal;\n}\n\nconst named_number& get_named_number(integer n) {\n constexpr size_t names_len = std::size(named_numbers);\n for (size_t i = 0; i + 1 < names_len; ++i) {\n if (n < named_numbers[i + 1].number)\n return named_numbers[i];\n }\n return named_numbers[names_len - 1];\n}\n\nstd::string number_name(integer n, bool ordinal) {\n std::string result;\n if (n < 20)\n result = get_name(small[n], ordinal);\n else if (n < 100) {\n if (n % 10 == 0) {\n result = get_name(tens[n/10 - 2], ordinal);\n } else {\n result = get_name(tens[n/10 - 2], false);\n result += \"-\";\n result += get_name(small[n % 10], ordinal);\n }\n } else {\n const named_number& num = get_named_number(n);\n integer p = num.number;\n result = number_name(n/p, false);\n result += \" \";\n if (n % p == 0) {\n result += get_name(num, ordinal);\n } else {\n result += get_name(num, false);\n result += \" \";\n result += number_name(n % p, ordinal);\n }\n }\n return result;\n}\n\nvoid test_ordinal(integer n) {\n std::cout << n << \": \" << number_name(n, true) << '\\n';\n}\n\nint main() {\n test_ordinal(1);\n test_ordinal(2);\n test_ordinal(3);\n test_ordinal(4);\n test_ordinal(5);\n test_ordinal(11);\n test_ordinal(15);\n test_ordinal(21);\n test_ordinal(42);\n test_ordinal(65);\n test_ordinal(98);\n test_ordinal(100);\n test_ordinal(101);\n test_ordinal(272);\n test_ordinal(300);\n test_ordinal(750);\n test_ordinal(23456);\n test_ordinal(7891233);\n test_ordinal(8007006005004003LL);\n return 0;\n}"} {"title": "Sphenic numbers", "language": "C++", "task": "Definitions\nA '''sphenic number''' is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below).\n\nFor the purposes of this task, a '''sphenic triplet''' is a group of three sphenic numbers which are consecutive. \n\nNote that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct.\n\n;Examples\n30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one.\n\n[1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers.\n\n;Task\nCalculate and show here:\n\n1. All sphenic numbers less than 1,000.\n\n2. All sphenic triplets less than 10,000.\n\n;Stretch\n\n3. How many sphenic numbers are there less than 1 million?\n\n4. How many sphenic triplets are there less than 1 million?\n\n5. What is the 200,000th sphenic number and its 3 prime factors?\n\n6. What is the 5,000th sphenic triplet?\n\nHint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6.\n\n;References\n\n* Wikipedia: Sphenic number\n* OEIS:A007304 - Sphenic numbers\n* OEIS:A165936 - Sphenic triplets (in effect)\n\n;Related tasks\n* [[Almost prime]]\n* [[Square-free integers]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::vector prime_sieve(int limit) {\n std::vector sieve(limit, true);\n if (limit > 0)\n sieve[0] = false;\n if (limit > 1)\n sieve[1] = false;\n for (int i = 4; i < limit; i += 2)\n sieve[i] = false;\n for (int p = 3, sq = 9; sq < limit; p += 2) {\n if (sieve[p]) {\n for (int q = sq; q < limit; q += p << 1)\n sieve[q] = false;\n }\n sq += (p + 1) << 2;\n }\n return sieve;\n}\n\nstd::vector prime_factors(int n) {\n std::vector factors;\n if (n > 1 && (n & 1) == 0) {\n factors.push_back(2);\n while ((n & 1) == 0)\n n >>= 1;\n }\n for (int p = 3; p * p <= n; p += 2) {\n if (n % p == 0) {\n factors.push_back(p);\n while (n % p == 0)\n n /= p;\n }\n }\n if (n > 1)\n factors.push_back(n);\n return factors;\n}\n\nint main() {\n const int limit = 1000000;\n const int imax = limit / 6;\n std::vector sieve = prime_sieve(imax + 1);\n std::vector sphenic(limit + 1, false);\n for (int i = 0; i <= imax; ++i) {\n if (!sieve[i])\n continue;\n int jmax = std::min(imax, limit / (i * i));\n if (jmax <= i)\n break;\n for (int j = i + 1; j <= jmax; ++j) {\n if (!sieve[j])\n continue;\n int p = i * j;\n int kmax = std::min(imax, limit / p);\n if (kmax <= j)\n break;\n for (int k = j + 1; k <= kmax; ++k) {\n if (!sieve[k])\n continue;\n assert(p * k <= limit);\n sphenic[p * k] = true;\n }\n }\n }\n\n std::cout << \"Sphenic numbers < 1000:\\n\";\n for (int i = 0, n = 0; i < 1000; ++i) {\n if (!sphenic[i])\n continue;\n ++n;\n std::cout << std::setw(3) << i << (n % 15 == 0 ? '\\n' : ' ');\n }\n\n std::cout << \"\\nSphenic triplets < 10,000:\\n\";\n for (int i = 0, n = 0; i < 10000; ++i) {\n if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {\n ++n;\n std::cout << \"(\" << i - 2 << \", \" << i - 1 << \", \" << i << \")\"\n << (n % 3 == 0 ? '\\n' : ' ');\n }\n }\n\n int count = 0, triplets = 0, s200000 = 0, t5000 = 0;\n for (int i = 0; i < limit; ++i) {\n if (!sphenic[i])\n continue;\n ++count;\n if (count == 200000)\n s200000 = i;\n if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {\n ++triplets;\n if (triplets == 5000)\n t5000 = i;\n }\n }\n\n std::cout << \"\\nNumber of sphenic numbers < 1,000,000: \" << count << '\\n';\n std::cout << \"Number of sphenic triplets < 1,000,000: \" << triplets << '\\n';\n\n auto factors = prime_factors(s200000);\n assert(factors.size() == 3);\n std::cout << \"The 200,000th sphenic number: \" << s200000 << \" = \"\n << factors[0] << \" * \" << factors[1] << \" * \" << factors[2]\n << '\\n';\n\n std::cout << \"The 5,000th sphenic triplet: (\" << t5000 - 2 << \", \"\n << t5000 - 1 << \", \" << t5000 << \")\\n\";\n}"} {"title": "Split a character string based on change of character", "language": "C++", "task": "Split a (character) string into comma (plus a blank) delimited\nstrings based on a change of character (left to right).\n\nShow the output here (use the 1st example below).\n\n\nBlanks should be treated as any other character (except\nthey are problematic to display clearly). The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "// Solution for http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character\n#include\n#include\n\nauto split(const std::string& input, const std::string& delim){\n\tstd::string res;\n\tfor(auto ch : input){\n\t\tif(!res.empty() && ch != res.back())\n\t\t\tres += delim;\n\t\tres += ch;\n\t}\n\treturn res;\n}\n\nint main(){\n\tstd::cout << split(\"gHHH5 ))YY++,,,///\\\\\", \", \") << std::endl;\n}"} {"title": "Square-free integers", "language": "C++", "task": "Write a function to test if a number is ''square-free''.\n\n\nA ''square-free'' is an integer which is divisible by no perfect square other\nthan '''1''' (unity).\n\nFor this task, only positive square-free numbers will be used.\n\n\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n::* '''1''' ---> '''145''' (inclusive)\n::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)\n\n\n(One trillion = 1,000,000,000,000)\n\n\nShow here (on this page) the count of square-free integers from:\n::* '''1''' ---> one hundred (inclusive)\n::* '''1''' ---> one thousand (inclusive)\n::* '''1''' ---> ten thousand (inclusive)\n::* '''1''' ---> one hundred thousand (inclusive)\n::* '''1''' ---> one million (inclusive)\n\n\n;See also:\n:* the Wikipedia entry: square-free integer\n\n", "solution": "#include \n#include \n#include \n\nusing integer = uint64_t;\n\nbool square_free(integer n) {\n if (n % 4 == 0)\n return false;\n for (integer p = 3; p * p <= n; p += 2) {\n integer count = 0;\n for (; n % p == 0; n /= p) {\n if (++count > 1)\n return false;\n }\n }\n return true;\n}\n\nvoid print_square_free_numbers(integer from, integer to) {\n std::cout << \"Square-free numbers between \" << from\n << \" and \" << to << \":\\n\";\n std::string line;\n for (integer i = from; i <= to; ++i) {\n if (square_free(i)) {\n if (!line.empty())\n line += ' ';\n line += std::to_string(i);\n if (line.size() >= 80) {\n std::cout << line << '\\n';\n line.clear();\n }\n }\n }\n if (!line.empty())\n std::cout << line << '\\n';\n}\n\nvoid print_square_free_count(integer from, integer to) {\n integer count = 0;\n for (integer i = from; i <= to; ++i) {\n if (square_free(i))\n ++count;\n }\n std::cout << \"Number of square-free numbers between \"\n << from << \" and \" << to << \": \" << count << '\\n';\n}\n\nint main() {\n print_square_free_numbers(1, 145);\n print_square_free_numbers(1000000000000LL, 1000000000145LL);\n print_square_free_count(1, 100);\n print_square_free_count(1, 1000);\n print_square_free_count(1, 10000);\n print_square_free_count(1, 100000);\n print_square_free_count(1, 1000000);\n return 0;\n}"} {"title": "Square but not cube", "language": "C++ from C", "task": "Show the first '''30''' positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.\n\n", "solution": "#include \n#include \n\nint main() {\n int n = 1;\n int count = 0;\n int sq;\n int cr;\n\n for (; count < 30; ++n) {\n sq = n * n;\n cr = cbrt(sq);\n if (cr * cr * cr != sq) {\n count++;\n std::cout << sq << '\\n';\n } else {\n std::cout << sq << \" is square and cube\\n\";\n }\n }\n\n return 0;\n}"} {"title": "Stair-climbing puzzle", "language": "C++", "task": "From Chung-Chieh Shan (LtU):\n\nYour stair-climbing robot has a very simple low-level API: the \"step\" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The \"step\" function detects what happens and returns a boolean flag: true on success, false on failure. \n\nWrite a function \"step_up\" that climbs one step up [from the initial position] (by repeating \"step\" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make \"step_up\"? Can you avoid using variables (even immutable ones) and numbers?\n\nHere's a pseudo-code of a simple recursive solution without using variables:\n\nfunc step_up()\n{\n if not step() {\n step_up();\n step_up();\n }\n}\n\nInductive proof that step_up() steps up one step, if it terminates:\n* Base case (if the step() call returns true): it stepped up one step. QED\n* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED\n\n\nThe second (tail) recursion above can be turned into an iteration, as follows:\n\nfunc step_up()\n{\n while not step() {\n step_up();\n }\n}\n\n", "solution": "void step_up()\n{\n for (int i = 0; i < 1; step()? ++i : --i);\n}"} {"title": "Statistics/Normal distribution", "language": "C++", "task": "The derive normally distributed random numbers from a uniform generator.\n\n\n;The task:\n# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.\n# Mention any native language support for the generation of normally distributed random numbers.\n\n\n;Reference:\n* You may refer to code in [[Statistics/Basic]] if available.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nint main( ) {\n std::random_device myseed ;\n std::mt19937 engine ( myseed( ) ) ;\n std::normal_distribution<> normDistri ( 2 , 3 ) ;\n std::map normalFreq ;\n int sum = 0 ; //holds the sum of the randomly created numbers\n double mean = 0.0 ;\n double stddev = 0.0 ;\n for ( int i = 1 ; i < 10001 ; i++ ) \n ++normalFreq[ normDistri ( engine ) ] ;\n for ( auto MapIt : normalFreq ) {\n sum += MapIt.first * MapIt.second ;\n }\n mean = sum / 10000 ;\n stddev = sqrt( sum / 10000 ) ;\n std::cout << \"The mean of the distribution is \" << mean << \" , the \" ;\n std::cout << \"standard deviation \" << stddev << \" !\\n\" ;\n std::cout << \"And now the histogram:\\n\" ;\n for ( auto MapIt : normalFreq ) {\n std::cout << std::left << std::setw( 4 ) << MapIt.first << \n\t std::string( MapIt.second / 100 , '*' ) << std::endl ;\n }\n return 0 ;\n}"} {"title": "Stern-Brocot sequence", "language": "C++", "task": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].\n\n# The first and second members of the sequence are both 1:\n#* 1, 1\n# Start by considering the second member of the sequence\n# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n#* 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* --- Expanding another loop we get: ---\n#*\n# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n#* 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1, 3, 2\n# Consider the next member of the series, (the fourth member i.e. 1)\n\n\n;The task is to:\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\n\n;Related tasks:\n:* [[Fusc sequence]].\n:* [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "#include \n#include \n#include \n#include \n\nunsigned gcd( unsigned i, unsigned j ) {\n return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;\n}\nvoid createSequence( std::vector& seq, int c ) {\n if( 1500 == seq.size() ) return;\n unsigned t = seq.at( c ) + seq.at( c + 1 );\n seq.push_back( t );\n seq.push_back( seq.at( c + 1 ) );\n createSequence( seq, c + 1 );\n}\nint main( int argc, char* argv[] ) {\n std::vector seq( 2, 1 );\n createSequence( seq, 0 );\n\n std::cout << \"First fifteen members of the sequence:\\n \";\n for( unsigned x = 0; x < 15; x++ ) {\n std::cout << seq[x] << \" \"; \n }\n\n std::cout << \"\\n\\n\"; \n for( unsigned x = 1; x < 11; x++ ) {\n std::vector::iterator i = std::find( seq.begin(), seq.end(), x );\n if( i != seq.end() ) {\n std::cout << std::setw( 3 ) << x << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n }\n }\n\n std::cout << \"\\n\";\n std::vector::iterator i = std::find( seq.begin(), seq.end(), 100 );\n if( i != seq.end() ) {\n std::cout << 100 << \" is at pos. #\" << 1 + distance( seq.begin(), i ) << \"\\n\";\n }\n\n std::cout << \"\\n\";\n unsigned g;\n bool f = false;\n for( int x = 0, y = 1; x < 1000; x++, y++ ) {\n g = gcd( seq[x], seq[y] );\n\tif( g != 1 ) f = true;\n std::cout << std::setw( 4 ) << x + 1 << \": GCD (\" << seq[x] << \", \" \n << seq[y] << \") = \" << g << ( g != 1 ? \" <-- ERROR\\n\" : \"\\n\" );\n }\n std::cout << \"\\n\" << ( f ? \"THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!\" : \"CORRECT: ALL GCDs ARE '1'!\" ) << \"\\n\\n\";\n return 0;\n}\n"} {"title": "Stream merge", "language": "C++ from C#", "task": " 2-stream merge\n: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.\n: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.\n\n; ''N''-stream merge\n: The same as above, but reading from ''N'' sources.\n: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].\n\n\nAssume streams are very big. You must not suck them whole in the memory, but read them as streams.\n\n", "solution": "//#include \n#include \n#include \n\ntemplate \nvoid merge2(const C& c1, const C& c2, const A& action) {\n auto i1 = std::cbegin(c1);\n auto i2 = std::cbegin(c2);\n\n while (i1 != std::cend(c1) && i2 != std::cend(c2)) {\n if (*i1 <= *i2) {\n action(*i1);\n i1 = std::next(i1);\n } else {\n action(*i2);\n i2 = std::next(i2);\n }\n }\n while (i1 != std::cend(c1)) {\n action(*i1);\n i1 = std::next(i1);\n }\n while (i2 != std::cend(c2)) {\n action(*i2);\n i2 = std::next(i2);\n }\n}\n\ntemplate \nvoid mergeN(const A& action, std::initializer_list all) {\n using I = typename C::const_iterator;\n using R = std::pair;\n\n std::vector vit;\n for (auto& c : all) {\n auto p = std::make_pair(std::cbegin(c), std::cend(c));\n vit.push_back(p);\n }\n\n bool done;\n R* least;\n do {\n done = true;\n\n auto it = vit.begin();\n auto end = vit.end();\n least = nullptr;\n\n // search for the first non-empty range to use for comparison\n while (it != end && it->first == it->second) {\n it++;\n }\n if (it != end) {\n least = &(*it);\n }\n while (it != end) {\n // search for the next non-empty range to use for comaprison\n while (it != end && it->first == it->second) {\n it++;\n }\n if (least != nullptr && it != end\n && it->first != it->second\n && *(it->first) < *(least->first)) {\n // found a smaller value\n least = &(*it);\n }\n if (it != end) {\n it++;\n }\n }\n if (least != nullptr && least->first != least->second) {\n done = false;\n action(*(least->first));\n least->first = std::next(least->first);\n }\n } while (!done);\n}\n\nvoid display(int num) {\n std::cout << num << ' ';\n}\n\nint main() {\n std::vector v1{ 0, 3, 6 };\n std::vector v2{ 1, 4, 7 };\n std::vector v3{ 2, 5, 8 };\n\n merge2(v2, v1, display);\n std::cout << '\\n';\n\n mergeN(display, { v1 });\n std::cout << '\\n';\n\n mergeN(display, { v3, v2, v1 });\n std::cout << '\\n';\n}"} {"title": "Strip control codes and extended characters from a string", "language": "C++", "task": "Strip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* a string with control codes stripped (but extended characters not stripped)\n:* a string with control codes and extended characters stripped\n\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127. \n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace boost::lambda ;\n\nstruct MyRandomizer {\n char operator( )( ) {\n return static_cast( rand( ) % 256 ) ;\n }\n} ;\n\nstd::string deleteControls ( std::string startstring ) {\n std::string noControls( \" \" ) ;//creating space for \n //the standard algorithm remove_copy_if\n std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noControls.begin( ) ,\n\t ll_static_cast( _1 ) < 32 && ll_static_cast( _1 ) == 127 ) ;\n return noControls ;\n}\n\nstd::string deleteExtended( std::string startstring ) {\n std::string noExtended ( \" \" ) ;//same as above\n std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noExtended.begin( ) ,\n\t ll_static_cast( _1 ) > 127 || ll_static_cast( _1 ) < 32 ) ;\n return noExtended ;\n}\n \nint main( ) {\n std::string my_extended_string ;\n for ( int i = 0 ; i < 40 ; i++ ) //we want the extended string to be 40 characters long\n my_extended_string.append( \" \" ) ;\n srand( time( 0 ) ) ;\n std::generate_n( my_extended_string.begin( ) , 40 , MyRandomizer( ) ) ;\n std::string no_controls( deleteControls( my_extended_string ) ) ;\n std::string no_extended ( deleteExtended( my_extended_string ) ) ;\n std::cout << \"string with all characters: \" << my_extended_string << std::endl ;\n std::cout << \"string without control characters: \" << no_controls << std::endl ;\n std::cout << \"string without extended characters: \" << no_extended << std::endl ;\n return 0 ;\n}"} {"title": "Subleq", "language": "C++", "task": "One-Instruction Set Computer (OISC). \n\nIt is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. \n\n;Task\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:\n::::* simple numeric values \n::::* memory addresses \n::::* characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine. \n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.\n:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.\n:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.\n:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.\n:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.\n:# If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).\n\nFor purposes of this task, show the output of your solution when fed the below \"Hello, world!\" program. \n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\nstart:\n 0f 11 ff subleq (zero), (message), -1\n 11 ff ff subleq (message), -1, -1 ; output character at message\n 10 01 ff subleq (neg1), (start+1), -1\n 10 03 ff subleq (neg1), (start+3), -1\n 0f 0f 00 subleq (zero), (zero), start\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n\n", "solution": "#include \n#include \n#include \n#include \n\nclass subleq {\npublic:\n void load_and_run( std::string file ) {\n std::ifstream f( file.c_str(), std::ios_base::in );\n std::istream_iterator i_v, i_f( f );\n std::copy( i_f, i_v, std::back_inserter( memory ) );\n f.close();\n run();\n }\n\nprivate:\n void run() {\n int pc = 0, next, a, b, c;\n char z;\n do {\n next = pc + 3;\n a = memory[pc]; b = memory[pc + 1]; c = memory[pc + 2];\n if( a == -1 ) {\n std::cin >> z; memory[b] = static_cast( z );\n } else if( b == -1 ) {\n std::cout << static_cast( memory[a] );\n } else {\n memory[b] -= memory[a];\n if( memory[b] <= 0 ) next = c;\n }\n pc = next;\n } while( pc >= 0 );\n }\n\n std::vector memory;\n};\n\nint main( int argc, char* argv[] ) {\n subleq s;\n if( argc > 1 ) {\n s.load_and_run( argv[1] );\n } else {\n std::cout << \"usage: subleq \\n\";\n }\n return 0;\n}\n"} {"title": "Substring/Top and tail", "language": "C++", "task": "The task is to demonstrate how to remove the first and last characters from a string. \n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. \n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. \n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n", "solution": "#include \n#include \n\nint main( ) {\n std::string word( \"Premier League\" ) ;\n std::cout << \"Without first letter: \" << word.substr( 1 ) << \" !\\n\" ;\n std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \" !\\n\" ;\n std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \" !\\n\" ;\n return 0 ;\n}"} {"title": "Sum and product puzzle", "language": "C++ from C", "task": "* Wikipedia: Sum and Product Puzzle\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::ostream &operator<<(std::ostream &os, std::vector> &v) {\n for (auto &p : v) {\n auto sum = p.first + p.second;\n auto prod = p.first * p.second;\n os << '[' << p.first << \", \" << p.second << \"] S=\" << sum << \" P=\" << prod;\n }\n return os << '\\n';\n}\n\nvoid print_count(const std::vector> &candidates) {\n auto c = candidates.size();\n if (c == 0) {\n std::cout << \"no candidates\\n\";\n } else if (c == 1) {\n std::cout << \"one candidate\\n\";\n } else {\n std::cout << c << \" candidates\\n\";\n }\n}\n\nauto setup() {\n std::vector> candidates;\n\n // numbers must be greater than 1\n for (int x = 2; x <= 98; x++) {\n // numbers must be unique, and sum no more than 100\n for (int y = x + 1; y <= 98; y++) {\n if (x + y <= 100) {\n candidates.push_back(std::make_pair(x, y));\n }\n }\n }\n\n return candidates;\n}\n\nvoid remove_by_sum(std::vector> &candidates, const int sum) {\n candidates.erase(std::remove_if(\n candidates.begin(), candidates.end(),\n [sum](const std::pair &pair) {\n auto s = pair.first + pair.second;\n return s == sum;\n }\n ), candidates.end());\n}\n\nvoid remove_by_prod(std::vector> &candidates, const int prod) {\n candidates.erase(std::remove_if(\n candidates.begin(), candidates.end(),\n [prod](const std::pair &pair) {\n auto p = pair.first * pair.second;\n return p == prod;\n }\n ), candidates.end());\n}\n\nvoid statement1(std::vector> &candidates) {\n std::map uniqueMap;\n\n std::for_each(\n candidates.cbegin(), candidates.cend(),\n [&uniqueMap](const std::pair &pair) {\n auto prod = pair.first * pair.second;\n uniqueMap[prod]++;\n }\n );\n\n bool loop;\n do {\n loop = false;\n for (auto &pair : candidates) {\n auto prod = pair.first * pair.second;\n if (uniqueMap[prod] == 1) {\n auto sum = pair.first + pair.second;\n remove_by_sum(candidates, sum);\n\n loop = true;\n break;\n }\n }\n } while (loop);\n}\n\nvoid statement2(std::vector> &candidates) {\n std::map uniqueMap;\n\n std::for_each(\n candidates.cbegin(), candidates.cend(),\n [&uniqueMap](const std::pair &pair) {\n auto prod = pair.first * pair.second;\n uniqueMap[prod]++;\n }\n );\n\n bool loop;\n do {\n loop = false;\n for (auto &pair : candidates) {\n auto prod = pair.first * pair.second;\n if (uniqueMap[prod] > 1) {\n remove_by_prod(candidates, prod);\n\n loop = true;\n break;\n }\n }\n } while (loop);\n}\n\nvoid statement3(std::vector> &candidates) {\n std::map uniqueMap;\n\n std::for_each(\n candidates.cbegin(), candidates.cend(),\n [&uniqueMap](const std::pair &pair) {\n auto sum = pair.first + pair.second;\n uniqueMap[sum]++;\n }\n );\n\n bool loop;\n do {\n loop = false;\n for (auto &pair : candidates) {\n auto sum = pair.first + pair.second;\n if (uniqueMap[sum] > 1) {\n remove_by_sum(candidates, sum);\n\n loop = true;\n break;\n }\n }\n } while (loop);\n}\n\nint main() {\n auto candidates = setup();\n print_count(candidates);\n\n statement1(candidates);\n print_count(candidates);\n\n statement2(candidates);\n print_count(candidates);\n\n statement3(candidates);\n print_count(candidates);\n\n std::cout << candidates;\n\n return 0;\n}"} {"title": "Sum digits of an integer", "language": "C++", "task": "Take a Natural Number in a given base and return the sum of its digits:\n:* '''1'''10 sums to '''1'''\n:* '''1234'''10 sums to '''10'''\n:* '''fe'''16 sums to '''29'''\n:* '''f0e'''16 sums to '''29'''\n\n", "solution": "#include \n#include \nint SumDigits(const unsigned long long int digits, const int BASE = 10) {\n int sum = 0;\n unsigned long long int x = digits;\n for (int i = log(digits)/log(BASE); i>0; i--){\n const double z = std::pow(BASE,i);\n\t const unsigned long long int t = x/z;\n\t sum += t;\n\t x -= t*z;\n }\n return x+sum;\n}\n\nint main() {\n std::cout << SumDigits(1) << ' '\n << SumDigits(12345) << ' '\n << SumDigits(123045) << ' '\n << SumDigits(0xfe, 16) << ' '\n << SumDigits(0xf0e, 16) << std::endl;\n return 0;\n}"} {"title": "Sum multiples of 3 and 5", "language": "C++", "task": "The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. \n\nShow output for ''n'' = 1000.\n\nThis is is the same as Project Euler problem 1.\n\n'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.\n\n", "solution": "#include \n\n//--------------------------------------------------------------------------------------------------\ntypedef unsigned long long bigInt;\n\nusing namespace std;\n//--------------------------------------------------------------------------------------------------\nclass m35\n{\npublic:\n void doIt( bigInt i )\n {\n\tbigInt sum = 0;\n\tfor( bigInt a = 1; a < i; a++ )\n\t if( !( a % 3 ) || !( a % 5 ) ) sum += a;\n\n\tcout << \"Sum is \" << sum << \" for n = \" << i << endl << endl;\n }\n\t\n // this method uses less than half iterations than the first one\n void doIt_b( bigInt i )\n {\n\tbigInt sum = 0;\n\tfor( bigInt a = 0; a < 28; a++ )\n\t{\n\t if( !( a % 3 ) || !( a % 5 ) )\n\t {\n\t\tsum += a;\n\t\tfor( bigInt s = 30; s < i; s += 30 )\n\t\t if( a + s < i ) sum += ( a + s );\n\n\t }\n\t}\n\tcout << \"Sum is \" << sum << \" for n = \" << i << endl << endl;\n }\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n m35 m; m.doIt( 1000 );\n return system( \"pause\" );\n}\n"} {"title": "Sum of elements below main diagonal of matrix", "language": "C++", "task": "Find and display the sum of elements that are below the main diagonal of a matrix.\n\nThe matrix should be a square matrix.\n\n\n::: --- Matrix to be used: ---\n\n [[1,3,7,8,10],\n [2,4,16,14,4],\n [3,1,9,18,11],\n [12,14,17,18,20],\n [7,1,3,9,5]] \n\n", "solution": "#include \n#include \n\ntemplate\nT sum_below_diagonal(const std::vector>& matrix) {\n T sum = 0;\n for (std::size_t y = 0; y < matrix.size(); y++)\n for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)\n sum += matrix[y][x];\n return sum;\n}\n\nint main() {\n std::vector> matrix = {\n {1,3,7,8,10},\n {2,4,16,14,4},\n {3,1,9,18,11},\n {12,14,17,18,20},\n {7,1,3,9,5}\n };\n \n std::cout << sum_below_diagonal(matrix) << std::endl;\n return 0;\n}"} {"title": "Summarize and say sequence", "language": "C++", "task": "There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:\n 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...\nThe terms generated grow in length geometrically and never converge.\n\nAnother way to generate a self-referential sequence is to summarize the previous term.\n\nCount how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.\n 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... \nSort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.\n\nDepending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)\n\n\n;Task:\nFind all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. \n\nSeed Value(s): 9009 9090 9900\n\nIterations: 21 \n\nSequence: (same for all three seeds except for first element)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-describing numbers]]\n* [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::map _map;\nstd::vector _result;\nsize_t longest = 0;\n\nvoid make_sequence( std::string n ) {\n _map.clear();\n for( std::string::iterator i = n.begin(); i != n.end(); i++ )\n _map.insert( std::make_pair( *i, _map[*i]++ ) );\n\n std::string z;\n for( std::map::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {\n char c = ( *i ).second + 48;\n z.append( 1, c );\n z.append( 1, i->first );\n }\n\n if( longest <= z.length() ) {\n longest = z.length();\n if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {\n _result.push_back( z );\n make_sequence( z );\n }\n }\n}\nint main( int argc, char* argv[] ) {\n std::vector tests;\n tests.push_back( \"9900\" ); tests.push_back( \"9090\" ); tests.push_back( \"9009\" );\n for( std::vector::iterator i = tests.begin(); i != tests.end(); i++ ) {\n make_sequence( *i );\n std::cout << \"[\" << *i << \"] Iterations: \" << _result.size() + 1 << \"\\n\";\n for( std::vector::iterator j = _result.begin(); j != _result.end(); j++ ) {\n std::cout << *j << \"\\n\";\n }\n std::cout << \"\\n\\n\";\n }\n return 0;\n}\n"} {"title": "Summarize primes", "language": "C++", "task": "Considering in order of length, n, all sequences of consecutive\nprimes, p, from 2 onwards, where p < 1000 and n>0, select those\nsequences whose sum is prime, and for these display the length of the\nsequence, the last item in the sequence, and the sum.\n\n", "solution": "#include \n\nbool is_prime(int n) {\n if (n < 2) {\n return false;\n }\n\n if (n % 2 == 0) {\n return n == 2;\n }\n if (n % 3 == 0) {\n return n == 3;\n }\n\n int i = 5;\n while (i * i <= n) {\n if (n % i == 0) {\n return false;\n }\n i += 2;\n\n if (n % i == 0) {\n return false;\n }\n i += 4;\n }\n\n return true;\n}\n\nint main() {\n const int start = 1;\n const int stop = 1000;\n\n int sum = 0;\n int count = 0;\n int sc = 0;\n\n for (int p = start; p < stop; p++) {\n if (is_prime(p)) {\n count++;\n sum += p;\n if (is_prime(sum)) {\n printf(\"The sum of %3d primes in [2, %3d] is %5d which is also prime\\n\", count, p, sum);\n sc++;\n }\n }\n }\n printf(\"There are %d summerized primes in [%d, %d)\\n\", sc, start, stop);\n\n return 0;\n}"} {"title": "Super-d numbers", "language": "C++ from D", "task": "A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where\n 2 <= d <= 9\nFor instance, 753 is a super-3 number because 3 x 7533 = 1280873331.\n\n\n'''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers.\n\n\n;Extra credit:\n:* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional).\n\n\n;See also:\n:* Wolfram MathWorld - Super-d Number.\n:* OEIS: A014569 - Super-3 Numbers.\n\n", "solution": "#include \n#include \n#include \n\nuint64_t ipow(uint64_t base, uint64_t exp) {\n uint64_t result = 1;\n while (exp) {\n if (exp & 1) {\n result *= base;\n }\n exp >>= 1;\n base *= base;\n }\n return result;\n}\n\nint main() {\n using namespace std;\n\n vector rd{ \"22\", \"333\", \"4444\", \"55555\", \"666666\", \"7777777\", \"88888888\", \"999999999\" };\n\n for (uint64_t ii = 2; ii < 5; ii++) {\n cout << \"First 10 super-\" << ii << \" numbers:\\n\";\n int count = 0;\n\n for (uint64_t j = 3; /* empty */; j++) {\n auto k = ii * ipow(j, ii);\n auto kstr = to_string(k);\n auto needle = rd[(size_t)(ii - 2)];\n auto res = kstr.find(needle);\n if (res != string::npos) {\n count++;\n cout << j << ' ';\n if (count == 10) {\n cout << \"\\n\\n\";\n break;\n }\n }\n }\n }\n\n return 0;\n}\n"} {"title": "Super-d numbers", "language": "C++ from C", "task": "A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where\n 2 <= d <= 9\nFor instance, 753 is a super-3 number because 3 x 7533 = 1280873331.\n\n\n'''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers.\n\n\n;Extra credit:\n:* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional).\n\n\n;See also:\n:* Wolfram MathWorld - Super-d Number.\n:* OEIS: A014569 - Super-3 Numbers.\n\n", "solution": "#include \n#include \n\nusing big_int = mpz_class;\n\nint main() {\n for (unsigned int d = 2; d <= 9; ++d) {\n std::cout << \"First 10 super-\" << d << \" numbers:\\n\";\n std::string digits(d, '0' + d);\n big_int bignum;\n for (unsigned int count = 0, n = 1; count < 10; ++n) {\n mpz_ui_pow_ui(bignum.get_mpz_t(), n, d);\n bignum *= d;\n auto str(bignum.get_str());\n if (str.find(digits) != std::string::npos) {\n std::cout << n << ' ';\n ++count;\n }\n }\n std::cout << '\\n';\n }\n return 0;\n}"} {"title": "Super-d numbers", "language": "C++ from C#", "task": "A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where\n 2 <= d <= 9\nFor instance, 753 is a super-3 number because 3 x 7533 = 1280873331.\n\n\n'''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers.\n\n\n;Extra credit:\n:* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional).\n\n\n;See also:\n:* Wolfram MathWorld - Super-d Number.\n:* OEIS: A014569 - Super-3 Numbers.\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\nusing namespace chrono;\n\nstruct LI { uint64_t a, b, c, d, e; }; const uint64_t Lm = 1e18;\nauto st = steady_clock::now(); LI k[10][10];\n\nstring padZ(uint64_t x, int n = 18) { string r = to_string(x);\n return string(max((int)(n - r.length()), 0), '0') + r; }\n\nuint64_t ipow(uint64_t b, uint64_t e) { uint64_t r = 1;\n while (e) { if (e & 1) r *= b; e >>= 1; b *= b; } return r; }\n\nuint64_t fa(uint64_t x) { // factorial\n uint64_t r = 1; while (x > 1) r *= x--; return r; }\n\nvoid set(LI &d, uint64_t s) { // d = s\n d.a = s; d.b = d.c = d.d = d.e = 0; }\n\nvoid inc(LI &d, LI s) { // d += s\n d.a += s.a; while (d.a >= Lm) { d.a -= Lm; d.b++; }\n d.b += s.b; while (d.b >= Lm) { d.b -= Lm; d.c++; }\n d.c += s.c; while (d.c >= Lm) { d.c -= Lm; d.d++; }\n d.d += s.d; while (d.d >= Lm) { d.d -= Lm; d.e++; }\n d.e += s.e;\n}\n\nstring scale(uint32_t s, LI &x) { // multiplies x by s, converts to string\n uint64_t A = x.a * s, B = x.b * s, C = x.c * s, D = x.d * s, E = x.e * s; \n while (A >= Lm) { A -= Lm; B++; }\n while (B >= Lm) { B -= Lm; C++; }\n while (C >= Lm) { C -= Lm; D++; }\n while (D >= Lm) { D -= Lm; E++; }\n if (E > 0) return to_string(E) + padZ(D) + padZ(C) + padZ(B) + padZ(A);\n if (D > 0) return to_string(D) + padZ(C) + padZ(B) + padZ(A);\n if (C > 0) return to_string(C) + padZ(B) + padZ(A);\n if (B > 0) return to_string(B) + padZ(A);\n return to_string(A);\n}\n\nvoid fun(int d) {\n auto m = k[d]; string s = string(d, '0' + d); printf(\"%d: \", d);\n for (int i = d, c = 0; c < 10; i++) {\n if (scale((uint32_t)d, m[0]).find(s) != string::npos) {\n printf(\"%d \", i); ++c; }\n for (int j = d, k = d - 1; j > 0; j = k--) inc(m[k], m[j]);\n } printf(\"%ss\\n\", to_string(duration(steady_clock::now() - st).count()).substr(0,5).c_str());\n}\n\nstatic void init() {\n for (int v = 1; v < 10; v++) {\n uint64_t f[v + 1], l[v + 1];\n for (int j = 0; j <= v; j++) {\n if (j == v) for (int y = 0; y <= v; y++)\n set(k[v][y], v != y ? (uint64_t)f[y] : fa(v));\n l[0] = f[0]; f[0] = ipow(j + 1, v);\n for (int a = 0, b = 1; b <= v; a = b++) {\n l[b] = f[b]; f[b] = f[a] - l[a];\n }\n }\n } \n}\n\nint main() {\n init();\n for (int i = 2; i <= 9; i++) fun(i);\n}\n"} {"title": "Superpermutation minimisation", "language": "C++ from Kotlin", "task": "A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.\n\nFor example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. \nThe permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.\n\nA too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.\n\nA little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.\n\nThe \"too obvious\" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.\n\nShow descriptions and comparisons of algorithms used here, and select the \"Best\" algorithm as being the one generating shorter superpermutations.\n\nThe problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.\n\n\n\n\n;Reference:\n* The Minimal Superpermutation Problem. by Nathaniel Johnston.\n* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.\n* Superpermutations - Numberphile. A video\n* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.\n* New Superpermutations Discovered! Standupmaths & Numberphile.\n\n", "solution": "#include \n#include \n#include \n\nconstexpr int MAX = 12;\n\nstatic std::vector sp;\nstatic std::array count;\nstatic int pos = 0;\n\nint factSum(int n) {\n int s = 0;\n int x = 0;\n int f = 1;\n while (x < n) {\n f *= ++x;\n s += f;\n }\n return s;\n}\n\nbool r(int n) {\n if (n == 0) {\n return false;\n }\n char c = sp[pos - n];\n if (--count[n] == 0) {\n count[n] = n;\n if (!r(n - 1)) {\n return false;\n }\n }\n sp[pos++] = c;\n return true;\n}\n\nvoid superPerm(int n) {\n pos = n;\n int len = factSum(n);\n if (len > 0) {\n sp.resize(len);\n }\n for (size_t i = 0; i <= n; i++) {\n count[i] = i;\n }\n for (size_t i = 1; i <= n; i++) {\n sp[i - 1] = '0' + i;\n }\n while (r(n)) {}\n}\n\nint main() {\n for (size_t n = 0; n < MAX; n++) {\n superPerm(n);\n std::cout << \"superPerm(\" << n << \") len = \" << sp.size() << '\\n';\n }\n\n return 0;\n}"} {"title": "Tarjan", "language": "C++", "task": "{{wikipedia|Graph}}\n\n\n\nTarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph. \n\nIt runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm. \n\nTarjan's Algorithm is named for its discoverer, Robert Tarjan.\n\n\n;References:\n* The article on Wikipedia.\n\nSee also: [[Kosaraju]]\n\n", "solution": "//\n// C++ implementation of Tarjan's strongly connected components algorithm\n// See https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm\n//\n#include \n#include \n#include \n#include \n#include \n\nstruct noncopyable {\n noncopyable() {}\n noncopyable(const noncopyable&) = delete;\n noncopyable& operator=(const noncopyable&) = delete;\n};\n\ntemplate \nclass tarjan;\n\ntemplate \nclass vertex : private noncopyable {\npublic:\n explicit vertex(const T& t) : data_(t) {}\n void add_neighbour(vertex* v) {\n neighbours_.push_back(v);\n }\n void add_neighbours(const std::initializer_list& vs) {\n neighbours_.insert(neighbours_.end(), vs);\n }\n const T& get_data() {\n return data_;\n }\nprivate:\n friend tarjan;\n T data_;\n int index_ = -1;\n int lowlink_ = -1;\n bool on_stack_ = false;\n std::vector neighbours_;\n};\n\ntemplate \nclass graph : private noncopyable {\npublic:\n vertex* add_vertex(const T& t) {\n vertexes_.emplace_back(t);\n return &vertexes_.back();\n }\nprivate:\n friend tarjan;\n std::list> vertexes_;\n};\n\ntemplate \nclass tarjan : private noncopyable {\npublic:\n using component = std::vector*>;\n std::list run(graph& graph) {\n index_ = 0;\n stack_.clear();\n strongly_connected_.clear();\n for (auto& v : graph.vertexes_) {\n if (v.index_ == -1)\n strongconnect(&v);\n }\n return strongly_connected_;\n }\nprivate:\n void strongconnect(vertex* v) {\n v->index_ = index_;\n v->lowlink_ = index_;\n ++index_;\n stack_.push_back(v);\n v->on_stack_ = true;\n for (auto w : v->neighbours_) {\n if (w->index_ == -1) {\n strongconnect(w);\n v->lowlink_ = std::min(v->lowlink_, w->lowlink_);\n }\n else if (w->on_stack_) {\n v->lowlink_ = std::min(v->lowlink_, w->index_);\n }\n }\n if (v->lowlink_ == v->index_) {\n strongly_connected_.push_back(component());\n component& c = strongly_connected_.back();\n for (;;) {\n auto w = stack_.back();\n stack_.pop_back();\n w->on_stack_ = false;\n c.push_back(w);\n if (w == v)\n break;\n }\n }\n }\n int index_ = 0;\n std::list*> stack_;\n std::list strongly_connected_;\n};\n\ntemplate \nvoid print_vector(const std::vector*>& vec) {\n if (!vec.empty()) {\n auto i = vec.begin();\n std::cout << (*i)->get_data();\n for (++i; i != vec.end(); ++i)\n std::cout << ' ' << (*i)->get_data();\n }\n std::cout << '\\n';\n}\n\nint main() {\n graph g;\n auto andy = g.add_vertex(\"Andy\");\n auto bart = g.add_vertex(\"Bart\");\n auto carl = g.add_vertex(\"Carl\");\n auto dave = g.add_vertex(\"Dave\");\n auto earl = g.add_vertex(\"Earl\");\n auto fred = g.add_vertex(\"Fred\");\n auto gary = g.add_vertex(\"Gary\");\n auto hank = g.add_vertex(\"Hank\");\n\n andy->add_neighbour(bart);\n bart->add_neighbour(carl);\n carl->add_neighbour(andy);\n dave->add_neighbours({bart, carl, earl});\n earl->add_neighbours({dave, fred});\n fred->add_neighbours({carl, gary});\n gary->add_neighbour(fred);\n hank->add_neighbours({earl, gary, hank});\n\n tarjan t;\n for (auto&& s : t.run(g))\n print_vector(s);\n return 0;\n}"} {"title": "Tau function", "language": "C++", "task": "Given a positive integer, count the number of its positive divisors.\n\n\n;Task\nShow the result for the first '''100''' positive integers.\n\n\n;Related task\n* [[Tau number]]\n\n", "solution": "#include \n#include \n\n// See https://en.wikipedia.org/wiki/Divisor_function\nunsigned int divisor_count(unsigned int n) {\n unsigned int total = 1;\n // Deal with powers of 2 first\n for (; (n & 1) == 0; n >>= 1)\n ++total;\n // Odd prime factors up to the square root\n for (unsigned int p = 3; p * p <= n; p += 2) {\n unsigned int count = 1;\n for (; n % p == 0; n /= p)\n ++count;\n total *= count;\n }\n // If n > 1 then it's prime\n if (n > 1)\n total *= 2;\n return total;\n}\n\nint main() {\n const unsigned int limit = 100;\n std::cout << \"Count of divisors for the first \" << limit << \" positive integers:\\n\";\n for (unsigned int n = 1; n <= limit; ++n) {\n std::cout << std::setw(3) << divisor_count(n);\n if (n % 20 == 0)\n std::cout << '\\n';\n }\n}"} {"title": "Teacup rim text", "language": "C++", "task": "On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*). \n\nIt occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word. \n\nSo start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''.\n\nThat got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu. \n\nFor English, we will use the unixdict (now) located at: unixdict.txt. \n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\n\n;Task:\nSearch for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.) \n\nHaving listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc. \n\nThe words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.) \n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''. \n\nAll of the possible permutations, using this particular permutation technique, must be words in the list. \n\nThe set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method. \n\nDisplay one line for each set of teacup rim words.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\n// filename is expected to contain one lowercase word per line\nstd::set load_dictionary(const std::string& filename) {\n std::ifstream in(filename);\n if (!in)\n throw std::runtime_error(\"Cannot open file \" + filename);\n std::set words;\n std::string word;\n while (getline(in, word))\n words.insert(word);\n return words;\n}\n\nvoid find_teacup_words(const std::set& words) {\n std::vector teacup_words;\n std::set found;\n for (auto w = words.begin(); w != words.end(); ++w) {\n std::string word = *w;\n size_t len = word.size();\n if (len < 3 || found.find(word) != found.end())\n continue;\n teacup_words.clear();\n teacup_words.push_back(word);\n for (size_t i = 0; i + 1 < len; ++i) {\n std::rotate(word.begin(), word.begin() + 1, word.end());\n if (word == *w || words.find(word) == words.end())\n break;\n teacup_words.push_back(word);\n }\n if (teacup_words.size() == len) {\n found.insert(teacup_words.begin(), teacup_words.end());\n std::cout << teacup_words[0];\n for (size_t i = 1; i < len; ++i)\n std::cout << ' ' << teacup_words[i];\n std::cout << '\\n';\n }\n }\n}\n\nint main(int argc, char** argv) {\n if (argc != 2) {\n std::cerr << \"usage: \" << argv[0] << \" dictionary\\n\";\n return EXIT_FAILURE;\n }\n try {\n find_teacup_words(load_dictionary(argv[1]));\n } catch (const std::exception& ex) {\n std::cerr << ex.what() << '\\n';\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}"} {"title": "Temperature conversion", "language": "C++", "task": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: \nRankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n \n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\n\n;Task\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. \n\n\n;Example:\n\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n\n", "solution": "#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nclass converter\n{\npublic:\n converter() : KTC( 273.15f ), KTDel( 3.0f / 2.0f ), KTF( 9.0f / 5.0f ), KTNew( 33.0f / 100.0f ),\n KTRank( 9.0f / 5.0f ), KTRe( 4.0f / 5.0f ), KTRom( 21.0f / 40.0f ) {}\n\n void convert( float kelvin )\n {\n float cel = kelvin - KTC,\n del = ( 373.15f - kelvin ) * KTDel,\n fah = kelvin * KTF - 459.67f,\n net = cel * KTNew,\n rnk = kelvin * KTRank,\n rea = cel * KTRe, \n rom = cel * KTRom + 7.5f;\n\n cout << endl << left\n << \"TEMPERATURES:\" << endl \n << \"===============\" << endl << setw( 13 )\n << \"CELSIUS:\" << cel << endl << setw( 13 )\n << \"DELISLE:\" << del << endl << setw( 13 )\n << \"FAHRENHEIT:\" << fah << endl << setw( 13 )\n << \"KELVIN:\" << kelvin << endl << setw( 13 )\n << \"NEWTON:\" << net << endl << setw( 13 )\n << \"RANKINE:\" << rnk << endl << setw( 13 )\n << \"REAUMUR:\" << rea << endl << setw( 13 )\n << \"ROMER:\" << rom << endl << endl << endl;\n }\nprivate:\n const float KTRank, KTC, KTF, KTRe, KTDel, KTNew, KTRom;\n};\n//--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n converter con;\n float k;\n while( true )\n {\n cout << \"Enter the temperature in Kelvin to convert: \";\n cin >> k;\n con.convert( k );\n system( \"pause\" );\n system( \"cls\" );\n }\n return 0;\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Test integerness", "language": "C++", "task": "{| class=\"wikitable\"\n|-\n! colspan=2 | Input\n! colspan=2 | Output\n! rowspan=2 | Comment\n|-\n! Type\n! Value\n! exact\n! tolerance = 0.00001\n|-\n| rowspan=3 | decimal\n| 25.000000\n| colspan=2 | true\n| \n|-\n| 24.999999\n| false\n| true\n| \n|-\n| 25.000100\n| colspan=2 | false\n| \n|-\n| rowspan=4 | floating-point\n| -2.1e120\n| colspan=2 | true\n| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.\n|-\n| -5e-2\n| colspan=2 | false\n| \n|-\n| NaN\n| colspan=2 | false\n| \n|-\n| Inf\n| colspan=2 | false\n| This one is debatable. If your code considers it an integer, that's okay too.\n|-\n| rowspan=2 | complex\n| 5.0+0.0i\n| colspan=2 | true\n| \n|-\n| 5-5i\n| colspan=2 | false\n| \n|}\n\n(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)\n\n\n", "solution": "#include \n#include \n#include \n\ntemplate\nstruct Precision\n{\npublic:\n\tstatic Type GetEps()\n\t{\n\t\treturn eps;\n\t}\n\n\tstatic void SetEps(Type e)\n\t{\n\t\teps = e;\n\t}\n\nprivate:\n\tstatic Type eps;\n};\n\ntemplate Type Precision::eps = static_cast(1E-7);\n\ntemplate\nbool IsDoubleEqual(DigType d1, DigType d2)\n{\n\treturn (fabs(d1 - d2) < Precision::GetEps());\n}\n\ntemplate\nDigType IntegerPart(DigType value)\n{\n\treturn (value > 0) ? floor(value) : ceil(value);\n}\n\ntemplate\nDigType FractionPart(DigType value)\n{\n\treturn fabs(IntegerPart(value) - value);\n}\n\ntemplate\nbool IsInteger(const Type& value)\n{\n\treturn false;\n}\n\n#define GEN_CHECK_INTEGER(type)\t\t\t\\\ntemplate<>\t\t\t\t\t\\\nbool IsInteger(const type& value) \\\n{\t\t\t\t\t\t\\\n\treturn true;\t\t\t\t\\\n}\n\n#define GEN_CHECK_CMPL_INTEGER(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger >(const std::complex& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn value.imag() == zero;\t\t\t\t\t\\\n}\n\n#define GEN_CHECK_REAL(type)\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger(const type& value)\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual(FractionPart(value), zero);\t\\\n}\n\n#define GEN_CHECK_CMPL_REAL(type)\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\\\nbool IsInteger >(const std::complex& value)\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\ttype zero = type();\t\t\t\t\t\t\\\n\treturn IsDoubleEqual(value.imag(), zero);\t\t\t\\\n}\n\n#define GEN_INTEGER(type)\t\t\\\n\tGEN_CHECK_INTEGER(type)\t\t\\\n\tGEN_CHECK_CMPL_INTEGER(type)\n\n#define GEN_REAL(type)\t\t\t\\\n\tGEN_CHECK_REAL(type)\t\t\\\n\tGEN_CHECK_CMPL_REAL(type)\n\n\nGEN_INTEGER(char)\nGEN_INTEGER(unsigned char)\nGEN_INTEGER(short)\nGEN_INTEGER(unsigned short)\nGEN_INTEGER(int)\nGEN_INTEGER(unsigned int)\nGEN_INTEGER(long)\nGEN_INTEGER(unsigned long)\nGEN_INTEGER(long long)\nGEN_INTEGER(unsigned long long)\n\nGEN_REAL(float)\nGEN_REAL(double)\nGEN_REAL(long double)\n\ntemplate\ninline void TestValue(const Type& value)\n{\n\tstd::cout << \"Value: \" << value << \" of type: \" << typeid(Type).name() << \" is integer - \" << std::boolalpha << IsInteger(value) << std::endl;\n}\n\nint main()\n{\n\tchar c = -100;\n\tunsigned char uc = 200;\n\tshort s = c;\n\tunsigned short us = uc;\n\tint i = s;\n\tunsigned int ui = us;\n\tlong long ll = i;\n\tunsigned long long ull = ui;\n\n\tstd::complex ci1(2, 0);\n\tstd::complex ci2(2, 4);\n\tstd::complex ci3(-2, 4);\n\tstd::complex cs1(2, 0);\n\tstd::complex cs2(2, 4);\n\tstd::complex cs3(-2, 4);\n\n\tstd::complex cd1(2, 0);\n\tstd::complex cf1(2, 4);\n\tstd::complex cd2(-2, 4);\n\n\tfloat f1 = 1.0;\n\tfloat f2 = -2.0;\n\tfloat f3 = -2.4f;\n\tfloat f4 = 1.23e-5f;\n\tfloat f5 = 1.23e-10f;\n\tdouble d1 = f5;\n\n\tTestValue(c);\n\tTestValue(uc);\n\tTestValue(s);\n\tTestValue(us);\n\tTestValue(i);\n\tTestValue(ui);\n\tTestValue(ll);\n\tTestValue(ull);\n\n\tTestValue(ci1);\n\tTestValue(ci2);\n\tTestValue(ci3);\n\tTestValue(cs1);\n\tTestValue(cs2);\n\tTestValue(cs3);\n\n\tTestValue(cd1);\n\tTestValue(cd2);\n\tTestValue(cf1);\n\n\tTestValue(f1);\n\tTestValue(f2);\n\tTestValue(f3);\n\tTestValue(f4);\n\tTestValue(f5);\n\tstd::cout << \"Set float precision: 1e-15f\\n\";\n\tPrecision::SetEps(1e-15f);\n\tTestValue(f5);\n\tTestValue(d1);\n\treturn 0;\n}\n"} {"title": "Textonyms", "language": "C++", "task": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n\n;Task:\nWrite a program that finds textonyms in a list of words such as \n[[Textonyms/wordlist]] or \nunixdict.txt.\n\nThe task should produce a report:\n\n There are #{0} words in #{1} which can be represented by the digit key mapping.\n They require #{2} digit combinations to represent them.\n #{3} digit combinations represent Textonyms.\n\nWhere:\n #{0} is the number of words in the list which can be represented by the digit key mapping.\n #{1} is the URL of the wordlist being used.\n #{2} is the number of digit combinations required to represent the words in #{0}.\n #{3} is the number of #{2} which represent more than one word.\n\nAt your discretion show a couple of examples of your solution displaying Textonyms. \n\nE.G.:\n\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n\n;Extra credit:\nUse a word list and keypad mapping other than English.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nstruct Textonym_Checker {\nprivate:\n int total;\n int elements;\n int textonyms;\n int max_found;\n std::vector max_strings;\n std::unordered_map> values;\n\n int get_mapping(std::string &result, const std::string &input)\n {\n static std::unordered_map mapping = {\n {'A', '2'}, {'B', '2'}, {'C', '2'},\n {'D', '3'}, {'E', '3'}, {'F', '3'},\n {'G', '4'}, {'H', '4'}, {'I', '4'},\n {'J', '5'}, {'K', '5'}, {'L', '5'},\n {'M', '6'}, {'N', '6'}, {'O', '6'},\n {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},\n {'T', '8'}, {'U', '8'}, {'V', '8'},\n {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}\n };\n\n result = input;\n for (char &c : result) {\n if (!isalnum(c)) return 0;\n if (isalpha(c)) c = mapping[toupper(c)];\n }\n\n return 1;\n }\n\npublic:\n Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }\n\n ~Textonym_Checker() { }\n\n void add(const std::string &str) {\n std::string mapping;\n total++;\n\n if (!get_mapping(mapping, str)) return;\n\n const int num_strings = values[mapping].size();\n\n if (num_strings == 1) textonyms++;\n elements++;\n\n if (num_strings > max_found) {\n max_strings.clear();\n max_strings.push_back(mapping);\n max_found = num_strings;\n }\n else if (num_strings == max_found)\n max_strings.push_back(mapping);\n\n values[mapping].push_back(str);\n }\n\n void results(const std::string &filename) {\n std::cout << \"Read \" << total << \" words from \" << filename << \"\\n\\n\";\n\n std::cout << \"There are \" << elements << \" words in \" << filename;\n std::cout << \" which can be represented by the digit key mapping.\\n\";\n std::cout << \"They require \" << values.size() <<\n \" digit combinations to represent them.\\n\";\n std::cout << textonyms << \" digit combinations represent Textonyms.\\n\\n\";\n std::cout << \"The numbers mapping to the most words map to \";\n std::cout << max_found + 1 << \" words each:\\n\";\n\n for (auto it1 : max_strings) {\n std::cout << '\\t' << it1 << \" maps to: \";\n for (auto it2 : values[it1])\n std::cout << it2 << \" \";\n std::cout << '\\n';\n }\n std::cout << '\\n';\n }\n\n void match(const std::string &str) {\n auto match = values.find(str);\n\n if (match == values.end()) {\n std::cout << \"Key '\" << str << \"' not found\\n\";\n }\n else {\n std::cout << \"Key '\" << str << \"' matches: \";\n for (auto it : values[str])\n std::cout << it << \" \";\n std::cout << '\\n';\n }\n }\n};\n\nint main()\n{\n auto filename = \"unixdict.txt\";\n std::ifstream input(filename);\n Textonym_Checker tc;\n\n if (input.is_open()) {\n std::string line;\n while (getline(input, line))\n tc.add(line);\n }\n\n input.close();\n\n tc.results(filename);\n tc.match(\"001\");\n tc.match(\"228\");\n tc.match(\"27484247\");\n tc.match(\"7244967473642\");\n}"} {"title": "The Name Game", "language": "C++ from C#", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "#include \n#include \n#include \n#include \n\nstatic void printVerse(const std::string& name) {\n std::string x = name;\n std::transform(x.begin(), x.end(), x.begin(), ::tolower);\n x[0] = toupper(x[0]);\n\n std::string y;\n switch (x[0]) {\n case 'A':\n case 'E':\n case 'I':\n case 'O':\n case 'U':\n y = x;\n std::transform(y.begin(), y.end(), y.begin(), ::tolower);\n break;\n default:\n y = x.substr(1);\n break;\n }\n\n std::string b(\"b\" + y);\n std::string f(\"f\" + y);\n std::string m(\"m\" + y);\n\n switch (x[0]) {\n case 'B':\n b = y;\n break;\n case 'F':\n f = y;\n break;\n case 'M':\n m = y;\n break;\n default:\n break;\n }\n\n printf(\"%s, %s, bo-%s\\n\", x.c_str(), x.c_str(), b.c_str());\n printf(\"Banana-fana fo-%s\\n\", f.c_str());\n printf(\"Fee-fi-mo-%s\\n\", m.c_str());\n printf(\"%s!\\n\\n\", x.c_str());\n}\n\nint main() {\n using namespace std;\n\n vector nameList{ \"Gary\", \"Earl\", \"Billy\", \"Felix\", \"Mary\", \"Steve\" };\n for (auto& name : nameList) {\n printVerse(name);\n }\n\n return 0;\n}"} {"title": "The Twelve Days of Christmas", "language": "C++", "task": "Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found here. \n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n", "solution": "#include \n#include \n#include \nusing namespace std;\n\nint main()\n{\n const array days\n {\n \"first\",\n \"second\",\n \"third\",\n \"fourth\",\n \"fifth\",\n \"sixth\",\n \"seventh\",\n \"eighth\",\n \"ninth\",\n \"tenth\",\n \"eleventh\",\n \"twelfth\"\n };\n \n const array gifts\n {\n \"And a partridge in a pear tree\",\n \"Two turtle doves\",\n \"Three french hens\",\n \"Four calling birds\",\n \"FIVE GOLDEN RINGS\",\n \"Six geese a-laying\",\n \"Seven swans a-swimming\",\n \"Eight maids a-milking\",\n \"Nine ladies dancing\",\n \"Ten lords a-leaping\",\n \"Eleven pipers piping\",\n \"Twelve drummers drumming\"\n };\n\n for(int i = 0; i < days.size(); ++i)\n {\n cout << \"On the \" << days[i] << \" day of christmas, my true love gave to me\\n\";\n\n if(i == 0)\n {\n cout << \"A partridge in a pear tree\\n\";\n }\n else\n {\n int j = i + 1;\n while(j-- > 0) cout << gifts[j] << '\\n';\n }\n\n cout << '\\n';\n }\n\n return 0;\n}"} {"title": "Thue-Morse", "language": "C++", "task": "Create a Thue-Morse sequence.\n\n\n;See also\n* YouTube entry: The Fairest Sharing Sequence Ever\n* YouTube entry: Math and OCD - My story with the Thue-Morse sequence\n* Task: [[Fairshare between two and more]]\n\n", "solution": "#include \n#include \n#include \nint main( int argc, char* argv[] ) {\n std::vector t;\n t.push_back( 0 );\n size_t len = 1;\n std::cout << t[0] << \"\\n\";\n do {\n for( size_t x = 0; x < len; x++ )\n t.push_back( t[x] ? 0 : 1 );\n std::copy( t.begin(), t.end(), std::ostream_iterator( std::cout ) );\n std::cout << \"\\n\";\n len = t.size();\n } while( len < 60 );\n return 0;\n}\n"} {"title": "Top rank per group", "language": "C++", "task": "Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\n\nstruct Employee\n{\n std::string Name;\n std::string ID;\n unsigned long Salary;\n std::string Department;\n Employee(std::string _Name = \"\", std::string _ID = \"\", unsigned long _Salary = 0, std::string _Department = \"\")\n : Name(_Name), ID(_ID), Salary(_Salary), Department(_Department)\n { }\n\n void display(std::ostream& out) const\n {\n out << Name << \"\\t\" << ID << \"\\t\" << Salary << \"\\t\" << Department << std::endl;\n }\n};\n\n// We'll tell std::set to use this to sort our employees.\nstruct CompareEarners\n{\n bool operator()(const Employee& e1, const Employee& e2)\n {\n return (e1.Salary > e2.Salary);\n }\n};\n\n// A few typedefs to make the code easier to type, read and maintain.\ntypedef std::list EMPLOYEELIST;\n\n// Notice the CompareEarners; We're telling std::set to user our specified comparison mechanism\n// to sort its contents.\ntypedef std::set DEPARTMENTPAYROLL;\n\ntypedef std::map DEPARTMENTLIST;\n\nvoid initialize(EMPLOYEELIST& Employees)\n{\n // Initialize our employee list data source.\n Employees.push_back(Employee(\"Tyler Bennett\", \"E10297\", 32000, \"D101\"));\n Employees.push_back(Employee(\"John Rappl\", \"E21437\", 47000, \"D050\"));\n Employees.push_back(Employee(\"George Woltman\", \"E21437\", 53500, \"D101\"));\n Employees.push_back(Employee(\"Adam Smith\", \"E21437\", 18000, \"D202\"));\n Employees.push_back(Employee(\"Claire Buckman\", \"E39876\", 27800, \"D202\"));\n Employees.push_back(Employee(\"David McClellan\", \"E04242\", 41500, \"D101\"));\n Employees.push_back(Employee(\"Rich Holcomb\", \"E01234\", 49500, \"D202\"));\n Employees.push_back(Employee(\"Nathan Adams\", \"E41298\", 21900, \"D050\"));\n Employees.push_back(Employee(\"Richard Potter\", \"E43128\", 15900, \"D101\"));\n Employees.push_back(Employee(\"David Motsinger\", \"E27002\", 19250, \"D202\"));\n Employees.push_back(Employee(\"Tim Sampair\", \"E03033\", 27000, \"D101\"));\n Employees.push_back(Employee(\"Kim Arlich\", \"E10001\", 57000, \"D190\"));\n Employees.push_back(Employee(\"Timothy Grove\", \"E16398\", 29900, \"D190\"));\n}\n\nvoid group(EMPLOYEELIST& Employees, DEPARTMENTLIST& Departments)\n{\n // Loop through all of our employees.\n for( EMPLOYEELIST::iterator iEmployee = Employees.begin();\n Employees.end() != iEmployee;\n ++iEmployee )\n {\n DEPARTMENTPAYROLL& groupSet = Departments[iEmployee->Department];\n\n // Add our employee to this group.\n groupSet.insert(*iEmployee);\n }\n}\n\nvoid present(DEPARTMENTLIST& Departments, unsigned int N)\n{\n // Loop through all of our departments\n for( DEPARTMENTLIST::iterator iDepartment = Departments.begin();\n Departments.end() != iDepartment;\n ++iDepartment )\n {\n std::cout << \"In department \" << iDepartment->first << std::endl;\n std::cout << \"Name\\t\\tID\\tSalary\\tDepartment\" << std::endl;\n // Get the top three employees for each employee\n unsigned int rank = 1;\n for( DEPARTMENTPAYROLL::iterator iEmployee = iDepartment->second.begin();\n ( iDepartment->second.end() != iEmployee) && (rank <= N);\n ++iEmployee, ++rank )\n {\n iEmployee->display(std::cout);\n }\n std::cout << std::endl;\n }\n}\n\nint main(int argc, char* argv[])\n{\n // Our container for our list of employees.\n EMPLOYEELIST Employees;\n\n // Fill our list of employees\n initialize(Employees);\n\n // Our departments. \n DEPARTMENTLIST Departments;\n\n // Sort our employees into their departments.\n // This will also rank them.\n group(Employees, Departments);\n\n // Display the top 3 earners in each department.\n present(Departments, 3);\n\n return 0;\n}"} {"title": "Topswops", "language": "C++", "task": "Topswops is a card game created by John Conway in the 1970's.\n\n\nAssume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. \n\nA round is composed of reversing the first m cards where m is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. \n\n\nFor our example the swaps produce:\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n\nFor a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.\n\n\nFor a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.\n\n\n;Task:\nThe task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.\n\n\n;Note:\nTopswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.\n\n\n;Related tasks:\n* [[Number reversal game]]\n* [[Sorting algorithms/Pancake sort]]\n\n", "solution": "#include \n#include \n#include \n#include \n\nint topswops(int n) {\n std::vector list(n);\n std::iota(std::begin(list), std::end(list), 1);\n int max_steps = 0;\n do {\n auto temp_list = list;\n for (int steps = 1; temp_list[0] != 1; ++steps) {\n std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);\n if (steps > max_steps) max_steps = steps;\n }\n } while (std::next_permutation(std::begin(list), std::end(list)));\n return max_steps;\n}\n\nint main() {\n for (int i = 1; i <= 10; ++i) {\n std::cout << i << \": \" << topswops(i) << std::endl;\n }\n return 0;\n}"} {"title": "Trabb Pardo\u2013Knuth algorithm", "language": "C++", "task": "The TPK algorithm is an early example of a programming chrestomathy. \nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. \nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n '''ask''' for 11 numbers to be read into a sequence ''S''\n '''reverse''' sequence ''S''\n '''for each''' ''item'' '''in''' sequence ''S''\n ''result'' ''':=''' '''call''' a function to do an ''operation''\n '''if''' ''result'' overflows\n '''alert''' user\n '''else'''\n '''print''' ''result''\n\nThe task is to implement the algorithm:\n# Use the function: f(x) = |x|^{0.5} + 5x^3\n# The overflow condition is an answer of greater than 400.\n# The 'user alert' should not stop processing of other items of the sequence.\n# Print a prompt before accepting '''eleven''', textual, numeric inputs.\n# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.\n# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nint main( ) {\n std::vector input( 11 ) , results( 11 ) ;\n std::cout << \"Please enter 11 numbers!\\n\" ;\n for ( int i = 0 ; i < input.size( ) ; i++ ) \n std::cin >> input[i];\n \n std::transform( input.begin( ) , input.end( ) , results.begin( ) ,\n\t [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;\n for ( int i = 10 ; i > -1 ; i-- ) {\n std::cout << \"f( \" << std::setw( 3 ) << input[ i ] << \" ) : \" ; \n if ( results[ i ] > 400 ) \n\t std::cout << \"too large!\" ;\n else \n\t std::cout << results[ i ] << \" !\" ;\n std::cout << std::endl ;\n }\n return 0 ;\n}"} {"title": "Tree datastructures", "language": "C++", "task": "The following shows a tree of data with nesting denoted by visual levels of indentation:\nRosettaCode\n rocks\n code\n comparison\n wiki\n mocks\n trolling\n\nA common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this '''the nest form'''.\n# E.g. if child nodes are surrounded by brackets\n# and separated by commas then:\nRosettaCode(rocks(code, ...), ...)\n# But only an _example_\n\nAnother datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this '''the indent form'''.\n0 RosettaCode\n1 rocks\n2 code\n...\n\n;Task:\n# Create/use a nest datastructure format and textual representation for arbitrary trees.\n# Create/use an indent datastructure format and textual representation for arbitrary trees.\n# Create methods/classes/proceedures/routines etc to:\n## Change from a nest tree datastructure to an indent one.\n## Change from an indent tree datastructure to a nest one\n# Use the above to encode the example at the start into the nest format, and show it.\n# transform the initial nest format to indent format and show it.\n# transform the indent format to final nest format and show it.\n# Compare initial and final nest formats which should be the same.\n\n;Note:\n* It's all about showing aspects of the contrasting datastructures as they hold the tree.\n* Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier.\n\n\nShow all output on this page.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass nest_tree;\n\nbool operator==(const nest_tree&, const nest_tree&);\n\nclass nest_tree {\npublic:\n explicit nest_tree(const std::string& name) : name_(name) {}\n nest_tree& add_child(const std::string& name) {\n children_.emplace_back(name);\n return children_.back();\n }\n void print(std::ostream& out) const {\n print(out, 0);\n }\n const std::string& name() const {\n return name_;\n }\n const std::list& children() const {\n return children_;\n }\n bool equals(const nest_tree& n) const {\n return name_ == n.name_ && children_ == n.children_;\n }\nprivate:\n void print(std::ostream& out, int level) const {\n std::string indent(level * 4, ' ');\n out << indent << name_ << '\\n';\n for (const nest_tree& child : children_)\n child.print(out, level + 1);\n }\n std::string name_;\n std::list children_;\n};\n\nbool operator==(const nest_tree& a, const nest_tree& b) {\n return a.equals(b);\n}\n\nclass indent_tree {\npublic:\n explicit indent_tree(const nest_tree& n) {\n items_.emplace_back(0, n.name());\n from_nest(n, 0);\n }\n void print(std::ostream& out) const {\n for (const auto& item : items_)\n std::cout << item.first << ' ' << item.second << '\\n';\n }\n nest_tree to_nest() const {\n nest_tree n(items_[0].second);\n to_nest_(n, 1, 0);\n return n;\n }\nprivate:\n void from_nest(const nest_tree& n, int level) {\n for (const nest_tree& child : n.children()) {\n items_.emplace_back(level + 1, child.name());\n from_nest(child, level + 1);\n }\n }\n size_t to_nest_(nest_tree& n, size_t pos, int level) const {\n while (pos < items_.size() && items_[pos].first == level + 1) {\n nest_tree& child = n.add_child(items_[pos].second);\n pos = to_nest_(child, pos + 1, level + 1);\n }\n return pos;\n }\n std::vector> items_;\n};\n\nint main() {\n nest_tree n(\"RosettaCode\");\n auto& child1 = n.add_child(\"rocks\");\n auto& child2 = n.add_child(\"mocks\");\n child1.add_child(\"code\");\n child1.add_child(\"comparison\");\n child1.add_child(\"wiki\");\n child2.add_child(\"trolling\");\n \n std::cout << \"Initial nest format:\\n\";\n n.print(std::cout);\n \n indent_tree i(n);\n std::cout << \"\\nIndent format:\\n\";\n i.print(std::cout);\n \n nest_tree n2(i.to_nest());\n std::cout << \"\\nFinal nest format:\\n\";\n n2.print(std::cout);\n\n std::cout << \"\\nAre initial and final nest formats equal? \"\n << std::boolalpha << n.equals(n2) << '\\n';\n \n return 0;\n}"} {"title": "Tree from nesting levels", "language": "C++", "task": "Given a flat list of integers greater than zero, representing object nesting\nlevels, e.g. [1, 2, 4],\ngenerate a tree formed from nested lists of those nesting level integers where:\n* Every int appears, in order, at its depth of nesting.\n* If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item\n\n\nThe generated tree data structure should ideally be in a languages nested list format that can\nbe used for further calculations rather than something just calculated for printing.\n\n\nAn input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]]\nwhere 1 is at depth1, 2 is two deep and 4 is nested 4 deep.\n\n[1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. \nAll the nesting integers are in the same order but at the correct nesting\nlevels.\n\nSimilarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1]\n\n;Task:\nGenerate and show here the results for the following inputs:\n:* []\n:* [1, 2, 4]\n:* [3, 1, 3, 1]\n:* [1, 2, 3, 1]\n:* [3, 2, 1, 3]\n:* [3, 3, 3, 1, 1, 3, 3, 3]\n", "solution": "#include \n#include \n#include \n#include \n\nusing namespace std;\n\n// Make a tree that is a vector of either values or other trees\nvector MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)\n{\n vector tree;\n while (first < last && depth <= *first)\n {\n if(*first == depth)\n {\n // add a single value\n tree.push_back(*first);\n ++first;\n }\n else // (depth < *b)\n {\n // add a subtree\n tree.push_back(MakeTree(first, last, depth + 1));\n first = find(first + 1, last, depth); \n }\n }\n \n return tree;\n}\n\n// Print an input vector or tree\nvoid PrintTree(input_iterator auto first, input_iterator auto last)\n{\n cout << \"[\";\n for(auto it = first; it != last; ++it)\n {\n if(it != first) cout << \", \";\n if constexpr (is_integral_v>)\n {\n // for printing the input vector\n cout << *it;\n }\n else\n {\n // for printing the tree\n if(it->type() == typeid(unsigned int))\n {\n // a single value\n cout << any_cast(*it);\n }\n else\n {\n // a subtree\n const auto& subTree = any_cast>(*it);\n PrintTree(subTree.begin(), subTree.end());\n }\n }\n }\n cout << \"]\";\n}\n\nint main(void) \n{\n auto execises = vector> {\n {},\n {1, 2, 4},\n {3, 1, 3, 1},\n {1, 2, 3, 1},\n {3, 2, 1, 3},\n {3, 3, 3, 1, 1, 3, 3, 3}\n };\n \n for(const auto& e : execises)\n {\n auto tree = MakeTree(e.begin(), e.end());\n PrintTree(e.begin(), e.end());\n cout << \" Nests to:\\n\"; \n PrintTree(tree.begin(), tree.end());\n cout << \"\\n\\n\";\n }\n}\n"} {"title": "Tropical algebra overloading", "language": "C++", "task": "In algebra, a max tropical semiring (also called a max-plus algebra) is the semiring\n(R -Inf, , ) containing the ring of real numbers R augmented by negative infinity,\nthe max function (returns the greater of two real numbers), and addition.\n\nIn max tropical algebra, x y = max(x, y) and x y = x + y. The identity for \nis -Inf (the max of any number with -infinity is that number), and the identity for is 0.\n\n;Task:\n\n* Define functions or, if the language supports the symbols as operators, operators for and that fit the above description. If the language does not support and as operators but allows overloading operators for a new object type, you may instead overload + and * for a new min tropical albrbraic type. If you cannot overload operators in the language used, define ordinary functions for the purpose. \n\nShow that 2 -2 is 0, -0.001 -Inf is -0.001, 0 -Inf is -Inf, 1.5 -1 is 1.5, and -0.5 0 is -0.5.\n\n* Define exponentiation as serial , and in general that a to the power of b is a * b, where a is a real number and b must be a positive integer. Use either | or similar up arrow or the carat ^, as an exponentiation operator if this can be used to overload such \"exponentiation\" in the language being used. Calculate 5 | 7 using this definition.\n\n* Max tropical algebra is distributive, so that\n\n a (b c) equals a b b c, \n\nwhere has precedence over . Demonstrate that 5 (8 7) equals 5 8 5 7.\n\n* If the language used does not support operator overloading, you may use ordinary function names such as tropicalAdd(x, y) and tropicalMul(x, y).\n\n\n;See also\n:;*[Tropical algebra]\n:;*[Tropical geometry review article]\n:;*[Operator overloading]\n\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\nclass TropicalAlgebra\n{\n // use an unset std::optional to represent -infinity\n optional m_value;\n \npublic:\n friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);\n friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;\n \n // create a point that is initialized to -infinity\n TropicalAlgebra() = default;\n\n // construct with a value\n explicit TropicalAlgebra(double value) noexcept\n : m_value{value} {}\n\n // add a value to this one ( p+=q ). it is common to also overload \n // the += operator when overloading +\n TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept\n {\n if(!m_value)\n {\n // this point is -infinity so the other point is max\n *this = rhs;\n }\n else if (!rhs.m_value)\n {\n // since rhs is -infinity this point is max\n }\n else\n {\n // both values are valid, find the max\n *m_value = max(*rhs.m_value, *m_value);\n }\n\n return *this;\n }\n \n // multiply this value by another (p *= q)\n TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept\n {\n if(!m_value)\n {\n // since this value is -infinity this point does not need to be\n // modified\n }\n else if (!rhs.m_value)\n {\n // the other point is -infinity, make this -infinity too\n *this = rhs;\n }\n else\n {\n *m_value += *rhs.m_value;\n }\n\n return *this;\n }\n};\n\n// add values (p + q)\ninline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n // implemented using the += operator defined above\n lhs += rhs;\n return lhs;\n}\n\n// multiply values (p * q)\ninline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept\n{\n lhs *= rhs;\n return lhs;\n}\n\n// pow is the idomatic way for exponentiation in C++\ninline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept\n{\n auto result = base;\n for(unsigned int i = 1; i < exponent; i++)\n {\n // compute the power by successive multiplication \n result *= base;\n }\n return result;\n}\n\n// print the point\nostream& operator<<(ostream& os, const TropicalAlgebra& pt)\n{\n if(!pt.m_value) cout << \"-Inf\\n\";\n else cout << *pt.m_value << \"\\n\";\n return os;\n}\n\nint main(void) {\n const TropicalAlgebra a(-2);\n const TropicalAlgebra b(-1);\n const TropicalAlgebra c(-0.5);\n const TropicalAlgebra d(-0.001);\n const TropicalAlgebra e(0);\n const TropicalAlgebra h(1.5);\n const TropicalAlgebra i(2);\n const TropicalAlgebra j(5);\n const TropicalAlgebra k(7);\n const TropicalAlgebra l(8);\n const TropicalAlgebra m; // -Inf\n \n cout << \"2 * -2 == \" << i * a;\n cout << \"-0.001 + -Inf == \" << d + m;\n cout << \"0 * -Inf == \" << e * m;\n cout << \"1.5 + -1 == \" << h + b;\n cout << \"-0.5 * 0 == \" << c * e;\n cout << \"pow(5, 7) == \" << pow(j, 7);\n cout << \"5 * (8 + 7)) == \" << j * (l + k);\n cout << \"5 * 8 + 5 * 7 == \" << j * l + j * k;\n}\n\n"} {"title": "Truncate a file", "language": "C++", "task": "Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).\n\n\nTruncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be \"binary safe\", leaving the contents of the untruncated part of the file unchanged.\n\nIf the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. \n\nOn some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. \n\nThis task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.\n\n", "solution": "#include \n#include \n\nusing namespace std;\n\nvoid truncateFile(string filename, int max_size) {\n std::ifstream input( filename, std::ios::binary );\n char buffer;\n string outfile = filename + \".trunc\";\n ofstream appendFile(outfile, ios_base::out);\n for(int i=0; i\n#include \n#include \n#include \n#include \n\nstruct var {\n char name;\n bool value;\n};\nstd::vector vars;\n\ntemplate\nT pop(std::stack &s) {\n auto v = s.top();\n s.pop();\n return v;\n}\n\nbool is_operator(char c) {\n return c == '&' || c == '|' || c == '!' || c == '^';\n}\n\nbool eval_expr(const std::string &expr) {\n std::stack sob;\n for (auto e : expr) {\n if (e == 'T') {\n sob.push(true);\n } else if (e == 'F') {\n sob.push(false);\n } else {\n auto it = std::find_if(vars.cbegin(), vars.cend(), [e](const var &v) { return v.name == e; });\n if (it != vars.cend()) {\n sob.push(it->value);\n } else {\n int before = sob.size();\n switch (e) {\n case '&':\n sob.push(pop(sob) & pop(sob));\n break;\n case '|':\n sob.push(pop(sob) | pop(sob));\n break;\n case '!':\n sob.push(!pop(sob));\n break;\n case '^':\n sob.push(pop(sob) ^ pop(sob));\n break;\n default:\n throw std::exception(\"Non-conformant character in expression.\");\n }\n }\n }\n }\n if (sob.size() != 1) {\n throw std::exception(\"Stack should contain exactly one element.\");\n }\n return sob.top();\n}\n\nvoid set_vars(int pos, const std::string &expr) {\n if (pos > vars.size()) {\n throw std::exception(\"Argument to set_vars can't be greater than the number of variables.\");\n }\n if (pos == vars.size()) {\n for (auto &v : vars) {\n std::cout << (v.value ? \"T \" : \"F \");\n }\n std::cout << (eval_expr(expr) ? 'T' : 'F') << '\\n'; //todo implement evaluation\n } else {\n vars[pos].value = false;\n set_vars(pos + 1, expr);\n vars[pos].value = true;\n set_vars(pos + 1, expr);\n }\n}\n\n/* removes whitespace and converts to upper case */\nstd::string process_expr(const std::string &src) {\n std::stringstream expr;\n\n for (auto c : src) {\n if (!isspace(c)) {\n expr << (char)toupper(c);\n }\n }\n\n return expr.str();\n}\n\nint main() {\n std::cout << \"Accepts single-character variables (except for 'T' and 'F',\\n\";\n std::cout << \"which specify explicit true or false values), postfix, with\\n\";\n std::cout << \"&|!^ for and, or, not, xor, respectively; optionally\\n\";\n std::cout << \"seperated by whitespace. Just enter nothing to quit.\\n\";\n\n while (true) {\n std::cout << \"\\nBoolean expression: \";\n\n std::string input;\n std::getline(std::cin, input);\n\n auto expr = process_expr(input);\n if (expr.length() == 0) {\n break;\n }\n\n vars.clear();\n for (auto e : expr) {\n if (!is_operator(e) && e != 'T' && e != 'F') {\n vars.push_back({ e, false });\n }\n }\n std::cout << '\\n';\n if (vars.size() == 0) {\n std::cout << \"No variables were entered.\\n\";\n } else {\n for (auto &v : vars) {\n std::cout << v.name << \" \";\n }\n std::cout << expr << '\\n';\n\n auto h = vars.size() * 3 + expr.length();\n for (size_t i = 0; i < h; i++) {\n std::cout << '=';\n }\n std::cout << '\\n';\n\n set_vars(0, expr);\n }\n }\n\n return 0;\n}"} {"title": "Two bullet roulette", "language": "C++ from C", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nclass Roulette {\nprivate:\n std::array cylinder;\n\n std::mt19937 gen;\n std::uniform_int_distribution<> distrib;\n\n int next_int() {\n return distrib(gen);\n }\n\n void rshift() {\n std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());\n }\n\n void unload() {\n std::fill(cylinder.begin(), cylinder.end(), false);\n }\n\n void load() {\n while (cylinder[0]) {\n rshift();\n }\n cylinder[0] = true;\n rshift();\n }\n\n void spin() {\n int lim = next_int();\n for (int i = 1; i < lim; i++) {\n rshift();\n }\n }\n\n bool fire() {\n auto shot = cylinder[0];\n rshift();\n return shot;\n }\n\npublic:\n Roulette() {\n std::random_device rd;\n gen = std::mt19937(rd());\n distrib = std::uniform_int_distribution<>(1, 6);\n\n unload();\n }\n\n int method(const std::string &s) {\n unload();\n for (auto c : s) {\n switch (c) {\n case 'L':\n load();\n break;\n case 'S':\n spin();\n break;\n case 'F':\n if (fire()) {\n return 1;\n }\n break;\n }\n }\n return 0;\n }\n};\n\nstd::string mstring(const std::string &s) {\n std::stringstream ss;\n bool first = true;\n\n auto append = [&ss, &first](const std::string s) {\n if (first) {\n first = false;\n } else {\n ss << \", \";\n }\n ss << s;\n };\n\n for (auto c : s) {\n switch (c) {\n case 'L':\n append(\"load\");\n break;\n case 'S':\n append(\"spin\");\n break;\n case 'F':\n append(\"fire\");\n break;\n }\n }\n\n return ss.str();\n}\n\nvoid test(const std::string &src) {\n const int tests = 100000;\n int sum = 0;\n\n Roulette r;\n for (int t = 0; t < tests; t++) {\n sum += r.method(src);\n }\n\n double pc = 100.0 * sum / tests;\n\n std::cout << std::left << std::setw(40) << mstring(src) << \" produces \" << pc << \"% deaths.\\n\";\n}\n\nint main() {\n test(\"LSLSFSF\");\n test(\"LSLSFF\");\n test(\"LLSFSF\");\n test(\"LLSFF\");\n\n return 0;\n}"} {"title": "UPC", "language": "C++ from Kotlin", "task": "Goal: \nConvert UPC bar codes to decimal.\n\n\nSpecifically:\n\nThe UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... \n\nHere, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink).\n\n\n;Sample input:\nBelow, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:\n\n # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \n # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \n # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \n # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \n # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \n # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \n # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \n # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \n # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \n # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \n\nSome of these were entered upside down, and one entry has a timing error.\n\n\n;Task:\nImplement code to find the corresponding decimal representation of each, rejecting the error. \n\nExtra credit for handling the rows entered upside down (the other option is to reject them).\n\n\n;Notes:\nEach digit is represented by 7 bits:\n\n 0: 0 0 0 1 1 0 1\n 1: 0 0 1 1 0 0 1\n 2: 0 0 1 0 0 1 1\n 3: 0 1 1 1 1 0 1\n 4: 0 1 0 0 0 1 1\n 5: 0 1 1 0 0 0 1\n 6: 0 1 0 1 1 1 1\n 7: 0 1 1 1 0 1 1\n 8: 0 1 1 0 1 1 1\n 9: 0 0 0 1 0 1 1\n\nOn the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''. \nOn the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1''' \nAlternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code.\n\n\n\n;The UPC-A bar code structure:\n::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly), \n::* then has a ''' # # ''' sequence marking the start of the sequence, \n::* then has the six \"left hand\" digits, \n::* then has a ''' # # ''' sequence in the middle, \n::* then has the six \"right hand digits\", \n::* then has another ''' # # ''' (end sequence), and finally, \n::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).\n\n\nFinally, the last digit is a checksum digit which may be used to help detect errors. \n\n\n;Verification:\nMultiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.\n\nThe sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::string trim(const std::string &str) {\n auto s = str;\n\n //rtrim\n auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace(ch, std::locale::classic()); });\n s.erase(it1.base(), s.end());\n\n //ltrim\n auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace(ch, std::locale::classic()); });\n s.erase(s.begin(), it2);\n\n return s;\n}\n\ntemplate \nstd::ostream &operator<<(std::ostream &os, const std::vector &v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n return os << ']';\n}\n\nconst std::map LEFT_DIGITS = {\n {\" ## #\", 0},\n {\" ## #\", 1},\n {\" # ##\", 2},\n {\" #### #\", 3},\n {\" # ##\", 4},\n {\" ## #\", 5},\n {\" # ####\", 6},\n {\" ### ##\", 7},\n {\" ## ###\", 8},\n {\" # ##\", 9}\n};\n\nconst std::map RIGHT_DIGITS = {\n {\"### # \", 0},\n {\"## ## \", 1},\n {\"## ## \", 2},\n {\"# # \", 3},\n {\"# ### \", 4},\n {\"# ### \", 5},\n {\"# # \", 6},\n {\"# # \", 7},\n {\"# # \", 8},\n {\"### # \", 9}\n};\n\nconst std::string END_SENTINEL = \"# #\";\nconst std::string MID_SENTINEL = \" # # \";\n\nvoid decodeUPC(const std::string &input) {\n auto decode = [](const std::string &candidate) {\n using OT = std::vector;\n OT output;\n size_t pos = 0;\n\n auto part = candidate.substr(pos, END_SENTINEL.length());\n if (part == END_SENTINEL) {\n pos += END_SENTINEL.length();\n } else {\n return std::make_pair(false, OT{});\n }\n\n for (size_t i = 0; i < 6; i++) {\n part = candidate.substr(pos, 7);\n pos += 7;\n\n auto e = LEFT_DIGITS.find(part);\n if (e != LEFT_DIGITS.end()) {\n output.push_back(e->second);\n } else {\n return std::make_pair(false, output);\n }\n }\n\n part = candidate.substr(pos, MID_SENTINEL.length());\n if (part == MID_SENTINEL) {\n pos += MID_SENTINEL.length();\n } else {\n return std::make_pair(false, OT{});\n }\n\n for (size_t i = 0; i < 6; i++) {\n part = candidate.substr(pos, 7);\n pos += 7;\n\n auto e = RIGHT_DIGITS.find(part);\n if (e != RIGHT_DIGITS.end()) {\n output.push_back(e->second);\n } else {\n return std::make_pair(false, output);\n }\n }\n\n part = candidate.substr(pos, END_SENTINEL.length());\n if (part == END_SENTINEL) {\n pos += END_SENTINEL.length();\n } else {\n return std::make_pair(false, OT{});\n }\n\n int sum = 0;\n for (size_t i = 0; i < output.size(); i++) {\n if (i % 2 == 0) {\n sum += 3 * output[i];\n } else {\n sum += output[i];\n }\n }\n return std::make_pair(sum % 10 == 0, output);\n };\n\n auto candidate = trim(input);\n\n auto out = decode(candidate);\n if (out.first) {\n std::cout << out.second << '\\n';\n } else {\n std::reverse(candidate.begin(), candidate.end());\n out = decode(candidate);\n if (out.first) {\n std::cout << out.second << \" Upside down\\n\";\n } else if (out.second.size()) {\n std::cout << \"Invalid checksum\\n\";\n } else {\n std::cout << \"Invalid digit(s)\\n\";\n }\n }\n}\n\nint main() {\n std::vector barcodes = {\n \" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \",\n \" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \",\n \" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \",\n \" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \",\n \" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \",\n \" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \",\n \" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \",\n \" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \",\n \" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \",\n \" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \",\n };\n for (auto &barcode : barcodes) {\n decodeUPC(barcode);\n }\n return 0;\n}"} {"title": "URL encoding", "language": "C++", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "#include \n#include \n\nint main( ) {\n QByteArray text ( \"http://foo bar/\" ) ;\n QByteArray encoded( text.toPercentEncoding( ) ) ;\n std::cout << encoded.data( ) << '\\n' ;\n return 0 ;\n}"} {"title": "Unbias a random generator", "language": "C++ from C#", "task": "Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.\n\n;Task details:\n* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.\n* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.\n* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).\n\n\nThe actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.\n\nThis task is an implementation of Von Neumann debiasing, first described in a 1951 paper.\n\n", "solution": "#include \n#include \n\nstd::default_random_engine generator;\nbool biased(int n) {\n std::uniform_int_distribution distribution(1, n);\n return distribution(generator) == 1;\n}\n\nbool unbiased(int n) {\n bool flip1, flip2;\n\n /* Flip twice, and check if the values are the same.\n * If so, flip again. Otherwise, return the value of the first flip. */\n\n do {\n flip1 = biased(n);\n flip2 = biased(n);\n } while (flip1 == flip2);\n\n return flip1;\n}\n\nint main() {\n for (size_t n = 3; n <= 6; n++) {\n int biasedZero = 0;\n int biasedOne = 0;\n int unbiasedZero = 0;\n int unbiasedOne = 0;\n\n for (size_t i = 0; i < 100000; i++) {\n if (biased(n)) {\n biasedOne++;\n } else {\n biasedZero++;\n }\n if (unbiased(n)) {\n unbiasedOne++;\n } else {\n unbiasedZero++;\n }\n }\n\n std::cout << \"(N = \" << n << \")\\n\";\n std::cout << \"Biased:\\n\";\n std::cout << \" 0 = \" << biasedZero << \"; \" << biasedZero / 1000.0 << \"%\\n\";\n std::cout << \" 1 = \" << biasedOne << \"; \" << biasedOne / 1000.0 << \"%\\n\";\n std::cout << \"Unbiased:\\n\";\n std::cout << \" 0 = \" << unbiasedZero << \"; \" << unbiasedZero / 1000.0 << \"%\\n\";\n std::cout << \" 1 = \" << unbiasedOne << \"; \" << unbiasedOne / 1000.0 << \"%\\n\";\n std::cout << '\\n';\n }\n return 0;\n}"} {"title": "Universal Turing machine", "language": "C++", "task": "One of the foundational mathematical constructs behind computer science \nis the universal Turing Machine. \n\n\n(Alan Turing introduced the idea of such a machine in 1936-1937.)\n\nIndeed one way to definitively prove that a language \nis turing-complete \nis to implement a universal Turing machine in it.\n\n\n;Task:\nSimulate such a machine capable \nof taking the definition of any other Turing machine and executing it. \n \nOf course, you will not have an infinite tape, \nbut you should emulate this as much as is possible. \n\nThe three permissible actions on the tape are \"left\", \"right\" and \"stay\".\n\nTo test your universal Turing machine (and prove your programming language \nis Turing complete!), you should execute the following two Turing machines \nbased on the following definitions.\n\n\n'''Simple incrementer'''\n* '''States:''' q0, qf\n* '''Initial state:''' q0\n* '''Terminating states:''' qf\n* '''Permissible symbols:''' B, 1\n* '''Blank symbol:''' B\n* '''Rules:'''\n** (q0, 1, 1, right, q0)\n** (q0, B, 1, stay, qf)\n\n\nThe input for this machine should be a tape of 1 1 1\n\n\n'''Three-state busy beaver'''\n* '''States:''' a, b, c, halt\n* '''Initial state:''' a\n* '''Terminating states:''' halt\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (a, 0, 1, right, b)\n** (a, 1, 1, left, c)\n** (b, 0, 1, left, a)\n** (b, 1, 1, right, b)\n** (c, 0, 1, left, b)\n** (c, 1, 1, stay, halt)\n\n\nThe input for this machine should be an empty tape.\n\n\n'''Bonus:'''\n\n'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''\n* '''States:''' A, B, C, D, E, H\n* '''Initial state:''' A\n* '''Terminating states:''' H\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (A, 0, 1, right, B)\n** (A, 1, 1, left, C)\n** (B, 0, 1, right, C)\n** (B, 1, 1, right, B)\n** (C, 0, 1, right, D)\n** (C, 1, 0, left, E)\n** (D, 0, 1, left, A)\n** (D, 1, 1, left, D)\n** (E, 0, 1, stay, H)\n** (E, 1, 0, left, A)\n\n\nThe input for this machine should be an empty tape.\n\nThis machine runs for more than 47 millions steps.\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n//--------------------------------------------------------------------------------------------------\ntypedef unsigned int uint;\nusing namespace std;\nconst uint TAPE_MAX_LEN = 49152;\n//--------------------------------------------------------------------------------------------------\nstruct action { char write, direction; };\n//--------------------------------------------------------------------------------------------------\nclass tape\n{\npublic:\n tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }\n void reset() { clear( '0' ); headPos = _sp; }\n char read(){ return _t[headPos]; }\n void input( string a ){ if( a == \"\" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }\n void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }\n void action( const action* a ) { write( a->write ); move( a->direction ); }\n void print( int c = 10 ) \n {\n\tint ml = static_cast( MAX_LEN ), st = static_cast( headPos ) - c, ed = static_cast( headPos ) + c + 1, tx;\n\tfor( int x = st; x < ed; x++ ) \n\t{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } \n\tcout << endl << setw( c + 1 ) << \"^\" << endl; \n }\nprivate:\n void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }\n void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }\n string _t; uint headPos, _sp; char blk; const uint MAX_LEN;\n};\n//--------------------------------------------------------------------------------------------------\nclass state\n{\npublic:\n bool operator ==( const string o ) { return o == name; }\n string name, next; char symbol, write, direction;\n};\n//--------------------------------------------------------------------------------------------------\nclass actionTable\n{\npublic:\n bool loadTable( string file )\n {\n\treset();\n\tifstream mf; mf.open( file.c_str() ); if( mf.is_open() )\n\t{\n\t string str; state stt;\n\t while( mf.good() )\n\t {\n\t\tgetline( mf, str ); if( str[0] == '\\'' ) break;\n\t\tparseState( str, stt ); states.push_back( stt );\n\t }\n\t while( mf.good() )\n\t {\n\t\tgetline( mf, str ); if( str == \"\" ) continue;\n\t\tif( str[0] == '!' ) blank = str.erase( 0, 1 )[0];\n\t\tif( str[0] == '^' ) curState = str.erase( 0, 1 );\n\t\tif( str[0] == '>' ) input = str.erase( 0, 1 );\n\t }\n\t mf.close(); return true;\n\t}\n\tcout << \"Could not open \" << file << endl; return false;\n }\n\n bool action( char symbol, action& a )\n {\n\tvector::iterator f = states.begin();\n\twhile( true )\n\t{\n\t f = find( f, states.end(), curState );\n\t if( f == states.end() ) return false;\n\t if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )\n\t { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }\n\t f++;\n\t}\n\treturn true;\n }\n void reset() { states.clear(); blank = '0'; curState = input = \"\"; }\n string getInput() { return input; }\n char getBlank() { return blank; }\nprivate:\n void parseState( string str, state& stt )\n {\n\tstring a[5]; int idx = 0;\n\tfor( string::iterator si = str.begin(); si != str.end(); si++ )\n\t{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }\n\tstt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];\n }\n vector states; char blank; string curState, input;\n};\n//--------------------------------------------------------------------------------------------------\nclass utm\n{\npublic:\n utm() { files[0] = \"incrementer.utm\"; files[1] = \"busy_beaver.utm\"; files[2] = \"sort.utm\"; }\n void start()\n {\n\twhile( true )\n\t{\n\t reset(); int t = showMenu(); if( t == 0 ) return;\n\t if( !at.loadTable( files[t - 1] ) ) return; startMachine();\n\t}\n }\nprivate:\n void simulate()\n {\n\tchar r; action a;\n\twhile( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }\n\tcout << endl << endl; system( \"pause\" );\n }\n\n int showMenu()\n {\n\tint t = -1;\n\twhile( t < 0 || t > 3 )\n\t{\n\t system( \"cls\" ); cout << \"1. Incrementer\\n2. Busy beaver\\n3. Sort\\n\\n0. Quit\";\n\t cout << endl << endl << \"Choose an action \"; cin >> t;\n\t}\n\treturn t;\n }\n\n void reset() { tp.reset(); at.reset(); }\n void startMachine() { system( \"cls\" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }\n\n tape tp; actionTable at; string files[7];\n};\n//--------------------------------------------------------------------------------------------------\nint main( int a, char* args[] ){ utm mm; mm.start(); return 0; }\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Validate International Securities Identification Number", "language": "C++", "task": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. \n\n\n;Task:\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, ''and'' the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n;Details:\nThe format of an ISIN is as follows:\n\n\n\n+------------- a 2-character ISO country code (A-Z)\n| +----------- a 9-character security code (A-Z, 0-9)\n| | +-- a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.\n# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)\n\n\n;Test cases:\n:::: {| class=\"wikitable\"\n! ISIN\n! Validity\n! Comment\n|-\n| US0378331005 || valid || \n|-\n| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.\n|-\n| U50378331005 || not valid || The substitution typo is caught by the format constraint.\n|-\n| US03378331005 || not valid || The duplication typo is caught by the format constraint.\n|-\n| AU0000XVGZA3 || valid || \n|-\n| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.\n|-\n| FR0000988040 || valid || \n|}\n\n(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* Interactive online ISIN validator\n* Wikipedia article: International Securities Identification Number\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nbool CheckFormat(const std::string& isin)\n{\n\tstd::regex isinRegEpx(R\"([A-Z]{2}[A-Z0-9]{9}[0-9])\");\n\tstd::smatch match;\n\treturn std::regex_match(isin, match, isinRegEpx);\n}\n\nstd::string CodeISIN(const std::string& isin)\n{\n\tstd::string coded;\n\tint offset = 'A' - 10;\n\tfor (auto ch : isin)\n\t{\n\t\tif (ch >= 'A' && ch <= 'Z')\n\t\t{\n\t\t\tstd::stringstream ss;\n\t\t\tss << static_cast(ch) - offset;\n\t\t\tcoded += ss.str();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcoded.push_back(ch);\n\t\t}\n\t}\n\n\treturn std::move(coded);\n}\n\nbool CkeckISIN(const std::string& isin)\n{\n\tif (!CheckFormat(isin))\n\t\treturn false;\n\n\tstd::string coded = CodeISIN(isin);\n// from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#C.2B.2B11\n\treturn luhn(coded);\n}\n\n\n#include \n#include \n\nint main()\n{\n\tstd::string isins[] = { \"US0378331005\", \"US0373831005\", \"U50378331005\",\n\t\t\t\t\t\t\t\"US03378331005\", \"AU0000XVGZA3\", \"AU0000VXGZA3\",\n\t\t\t\t\t\t\t\"FR0000988040\" };\n\tfor (const auto& isin : isins)\n\t{\n\t\tstd::cout << isin << std::boolalpha << \" - \" << CkeckISIN(isin) <\n#include \n\nclass van_eck_generator {\npublic:\n int next() {\n int result = last_term;\n auto iter = last_pos.find(last_term);\n int next_term = (iter != last_pos.end()) ? index - iter->second : 0;\n last_pos[last_term] = index;\n last_term = next_term;\n ++index;\n return result;\n }\nprivate:\n int index = 0;\n int last_term = 0;\n std::map last_pos;\n};\n\nint main() {\n van_eck_generator gen;\n int i = 0;\n std::cout << \"First 10 terms of the Van Eck sequence:\\n\";\n for (; i < 10; ++i)\n std::cout << gen.next() << ' ';\n for (; i < 990; ++i)\n gen.next();\n std::cout << \"\\nTerms 991 to 1000 of the sequence:\\n\";\n for (; i < 1000; ++i)\n std::cout << gen.next() << ' ';\n std::cout << '\\n';\n return 0;\n}"} {"title": "Van der Corput sequence", "language": "C++ from Raku", "task": "When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.\n\nSo in the following table:\n 0.\n 1.\n 10.\n 11.\n ...\nthe binary number \"10\" is 1 \\times 2^1 + 0 \\times 2^0.\n\nYou can also have binary digits to the right of the \"point\", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. \nThe weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.\n\nIf you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.\n\n .0\n .1\n .01\n .11\n ...\n\nThe third member of the sequence, binary 0.01, is therefore 0 \\times 2^{-1} + 1 \\times 2^{-2} or 1/4.\n\n Monte Carlo simulations. \nThis sequence is also a superset of the numbers representable by the \"fraction\" field of an old IEEE floating point standard. In that standard, the \"fraction\" field represented the fractional part of a binary number beginning with \"1.\" e.g. 1.101001101.\n\n'''Hint'''\n\nA ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:\n>>> def base10change(n, base):\n\tdigits = []\n\twhile n:\n\t\tn,remainder = divmod(n, base)\n\t\tdigits.insert(0, remainder)\n\treturn digits\n\n>>> base10change(11, 2)\n[1, 0, 1, 1]\nthe above showing that 11 in decimal is 1\\times 2^3 + 0\\times 2^2 + 1\\times 2^1 + 1\\times 2^0.\nReflected this would become .1101 or 1\\times 2^{-1} + 1\\times 2^{-2} + 0\\times 2^{-3} + 1\\times 2^{-4}\n\n\n;Task description:\n* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.\n* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).\n\n* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.\n\n\n\n;See also:\n* The Basic Low Discrepancy Sequences\n* [[Non-decimal radices/Convert]]\n* Van der Corput sequence\n\n", "solution": "#include \n#include \n\ndouble vdc(int n, double base = 2)\n{\n double vdc = 0, denom = 1;\n while (n)\n {\n vdc += fmod(n, base) / (denom *= base);\n n /= base; // note: conversion from 'double' to 'int'\n }\n return vdc;\n}\n\nint main() \n{\n for (double base = 2; base < 6; ++base)\n {\n std::cout << \"Base \" << base << \"\\n\";\n for (int n = 0; n < 10; ++n)\n {\n std::cout << vdc(n, base) << \" \";\n }\n std::cout << \"\\n\\n\";\n }\n}"} {"title": "Variable declaration reset", "language": "C++", "task": "A decidely non-challenging task to highlight a potential difference between programming languages.\n\nUsing a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. \nThe purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.\nThere is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences.\nShould your first attempt bomb with \"unassigned variable\" exceptions, feel free to code it as (say)\n // int prev // crashes with unassigned variable\n int prev = -1 // predictably no output\nIf your programming language does not support block scope (eg assembly) it should be omitted from this task.\n\n", "solution": "#include \n#include \n\nint main()\n{\n constexpr std::array s {1,2,2,3,4,4,5};\n\n if(!s.empty())\n {\n int previousValue = s[0];\n\n for(size_t i = 1; i < s.size(); ++i)\n {\n // in C++, variables in block scope are reset at each iteration\n const int currentValue = s[i];\n\n if(i > 0 && previousValue == currentValue)\n {\n std::cout << i << \"\\n\";\n }\n\n previousValue = currentValue;\n }\n }\n}\n\n"} {"title": "Vector products", "language": "C++", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). \n\nIf you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.\n\nGiven the vectors:\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \nthen the following common vector products are defined:\n* '''The dot product''' (a scalar quantity)\n:::: A * B = a1b1 + a2b2 + a3b3 \n* '''The cross product''' (a vector quantity)\n:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) \n* '''The scalar triple product''' (a scalar quantity)\n:::: A * (B x C) \n* '''The vector triple product''' (a vector quantity)\n:::: A x (B x C) \n\n\n;Task:\nGiven the three vectors: \n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n# Create a named function/subroutine/method to compute the dot product of two vectors.\n# Create a function to compute the cross product of two vectors.\n# Optionally create a function to compute the scalar triple product of three vectors.\n# Optionally create a function to compute the vector triple product of three vectors.\n# Compute and display: a * b\n# Compute and display: a x b\n# Compute and display: a * (b x c), the scalar triple product.\n# Compute and display: a x (b x c), the vector triple product.\n\n\n;References:\n* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.\n* Wikipedia dot product. \n* Wikipedia cross product. \n* Wikipedia triple product.\n\n\n;Related tasks:\n* [[Dot product]]\n* [[Quaternion type]]\n\n", "solution": "#include \n\ntemplate< class T >\nclass D3Vector {\n\ntemplate< class U >\nfriend std::ostream & operator<<( std::ostream & , const D3Vector & ) ; \n\npublic :\n D3Vector( T a , T b , T c ) {\n x = a ;\n y = b ;\n z = c ;\n }\n\n T dotproduct ( const D3Vector & rhs ) {\n T scalar = x * rhs.x + y * rhs.y + z * rhs.z ;\n return scalar ;\n }\n\n D3Vector crossproduct ( const D3Vector & rhs ) {\n T a = y * rhs.z - z * rhs.y ;\n T b = z * rhs.x - x * rhs.z ;\n T c = x * rhs.y - y * rhs.x ;\n D3Vector product( a , b , c ) ;\n return product ;\n }\n\n D3Vector triplevec( D3Vector & a , D3Vector & b ) {\n return crossproduct ( a.crossproduct( b ) ) ;\n }\n\n T triplescal( D3Vector & a, D3Vector & b ) {\n return dotproduct( a.crossproduct( b ) ) ;\n }\n\nprivate :\n T x , y , z ; \n} ;\n\ntemplate< class T >\nstd::ostream & operator<< ( std::ostream & os , const D3Vector & vec ) {\n os << \"( \" << vec.x << \" , \" << vec.y << \" , \" << vec.z << \" )\" ;\n return os ;\n}\n\nint main( ) {\n D3Vector a( 3 , 4 , 5 ) , b ( 4 , 3 , 5 ) , c( -5 , -12 , -13 ) ;\n std::cout << \"a . b : \" << a.dotproduct( b ) << \"\\n\" ;\n std::cout << \"a x b : \" << a.crossproduct( b ) << \"\\n\" ;\n std::cout << \"a . b x c : \" << a.triplescal( b , c ) << \"\\n\" ;\n std::cout << \"a x b x c : \" << a.triplevec( b , c ) << \"\\n\" ;\n return 0 ;\n}"} {"title": "Verhoeff algorithm", "language": "C++", "task": "Description\nThe Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. \n\nAs the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. \n\n;Task:\nWrite routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.\n\nThe more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.\n\nWrite your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.\n\nUse your routines to calculate check digits for the integers: '''236''', '''12345''' and '''123456789012''' and then validate them. Also attempt to validate the same integers if the check digits in all cases were '''9''' rather than what they actually are.\n\nDisplay digit by digit calculations for the first two integers but not for the third. \n\n;Related task:\n* [[Damm algorithm]]\n\n", "solution": "#include \n#include \n#include \n#include \n\ntypedef std::pair data;\n\nconst std::array, 10> multiplication_table = { {\n\t{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },\n\t{ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 },\n\t{ 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 },\n\t{ 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 },\n\t{ 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 },\n\t{ 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 },\n\t{ 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 },\n\t{ 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 },\n\t{ 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 },\n\t{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }\n} };\n\nconst std::array inverse = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 };\n\nconst std::array, 8> permutation_table = { {\n { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },\n { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 },\n { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 },\n { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 },\n { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 },\n { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 },\n\t{ 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 },\n { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }\n} };\n\nint32_t verhoeff_checksum(std::string number, bool doValidation, bool doDisplay) {\n\tif ( doDisplay ) {\n\t\tstd::string calculationType = doValidation ? \"Validation\" : \"Check digit\";\n\t\tstd::cout << calculationType << \" calculations for \" << number << \"\\n\" << std::endl;\n\t\tstd::cout << \" i ni p[i, ni] c\" << std::endl;\n\t\tstd::cout << \"-------------------\" << std::endl;\n\t}\n\n\tif ( ! doValidation ) {\n\t\tnumber += \"0\";\n\t}\n\n\tint32_t c = 0;\n\tconst int32_t le = number.length() - 1;\n\tfor ( int32_t i = le; i >= 0; i-- ) {\n\t\tconst int32_t ni = number[i] - '0';\n\t\tconst int32_t pi = permutation_table[(le - i) % 8][ni];\n\t\tc = multiplication_table[c][pi];\n\n\t\tif ( doDisplay ) {\n\t\t\tstd::cout << std::setw(2) << le - i << std::setw(3) << ni\n\t\t\t\t\t << std::setw(8) << pi << std::setw(6) << c << \"\\n\" << std::endl;\n\t\t}\n\t}\n\n\tif ( doDisplay && ! doValidation ) {\n\t\tstd::cout << \"inverse[\" << c << \"] = \" << inverse[c] << \"\\n\" << std::endl;;\n\t}\n\n\treturn doValidation ? c == 0 : inverse[c];\n}\n\nint main( ) {\n\tconst std::array tests = {\n\t\tstd::make_pair(\"123\", true), std::make_pair(\"12345\", true), std::make_pair(\"123456789012\", false) };\n\n\tfor ( data test : tests ) {\n\t\tint32_t digit = verhoeff_checksum(test.first, false, test.second);\n\t\tstd::cout << \"The check digit for \" << test.first << \" is \" << digit << \"\\n\" << std::endl;\n\n\t\tstd::string numbers[2] = { test.first + std::to_string(digit), test.first + \"9\" };\n\t\tfor ( std::string number : numbers ) {\n\t\t\tdigit = verhoeff_checksum(number, true, test.second);\n\t\t\tstd::string result = ( digit == 1 ) ? \"correct\" : \"incorrect\";\n\t\t\tstd::cout << \"The validation for \" << number << \" is \" << result << \".\\n\" << std::endl;\n\t\t}\n\t}\n}\n"} {"title": "Visualize a tree", "language": "C++", "task": "A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n\n", "solution": "#include \n#include \n#include \n\nclass BinarySearchTree {\nprivate:\n struct Node {\n int key;\n Node *left, *right;\n\n Node(int k) : key(k), left(nullptr), right(nullptr) {\n //empty\n }\n } *root;\n\npublic:\n BinarySearchTree() : root(nullptr) {\n // empty\n }\n\n bool insert(int key) {\n if (root == nullptr) {\n root = new Node(key);\n } else {\n auto n = root;\n Node *parent;\n while (true) {\n if (n->key == key) {\n return false;\n }\n\n parent = n;\n\n bool goLeft = key < n->key;\n n = goLeft ? n->left : n->right;\n\n if (n == nullptr) {\n if (goLeft) {\n parent->left = new Node(key);\n } else {\n parent->right = new Node(key);\n }\n break;\n }\n }\n }\n return true;\n }\n\n friend std::ostream &operator<<(std::ostream &, const BinarySearchTree &);\n};\n\ntemplate\nvoid display(std::ostream &os, const T *n) {\n if (n != nullptr) {\n os << \"Node(\";\n\n display(os, n->left);\n\n os << ',' << n->key << ',';\n\n display(os, n->right);\n\n os << \")\";\n } else {\n os << '-';\n }\n}\n\nstd::ostream &operator<<(std::ostream &os, const BinarySearchTree &bst) {\n display(os, bst.root);\n return os;\n}\n\nint main() {\n std::default_random_engine generator;\n std::uniform_int_distribution distribution(0, 200);\n auto rng = std::bind(distribution, generator);\n\n BinarySearchTree tree;\n\n tree.insert(100);\n for (size_t i = 0; i < 20; i++) {\n tree.insert(rng());\n }\n std::cout << tree << '\\n';\n\n return 0;\n}"} {"title": "Vogel's approximation method", "language": "C++ from Java", "task": "Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them \"A\", \"B\", \"C\", \"D\", and \"E\". They estimate that:\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called \"W\", \"X\", \"Y\", and \"Z\".\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.\n\nRepeat until all supply and demand is met:\n\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\nFinally calculate the cost of your solution. In the example given it is PS3100:\n\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n\nThe optimal solution determined by GLPK is PS3100:\n\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n\n;Cf.\n* Transportation problem\n\n", "solution": "#include \n#include \n#include \n\ntemplate \nstd::ostream &operator<<(std::ostream &os, const std::vector &v) {\n auto it = v.cbegin();\n auto end = v.cend();\n\n os << '[';\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n\n return os << ']';\n}\n\nstd::vector demand = { 30, 20, 70, 30, 60 };\nstd::vector supply = { 50, 60, 50, 50 };\nstd::vector> costs = {\n {16, 16, 13, 22, 17},\n {14, 14, 13, 19, 15},\n {19, 19, 20, 23, 50},\n {50, 12, 50, 15, 11}\n};\n\nint nRows = supply.size();\nint nCols = demand.size();\n\nstd::vector rowDone(nRows, false);\nstd::vector colDone(nCols, false);\nstd::vector> result(nRows, std::vector(nCols, 0));\n\nstd::vector diff(int j, int len, bool isRow) {\n int min1 = INT_MAX;\n int min2 = INT_MAX;\n int minP = -1;\n for (int i = 0; i < len; i++) {\n if (isRow ? colDone[i] : rowDone[i]) {\n continue;\n }\n int c = isRow\n ? costs[j][i]\n : costs[i][j];\n if (c < min1) {\n min2 = min1;\n min1 = c;\n minP = i;\n } else if (c < min2) {\n min2 = c;\n }\n }\n return { min2 - min1, min1, minP };\n}\n\nstd::vector maxPenalty(int len1, int len2, bool isRow) {\n int md = INT_MIN;\n int pc = -1;\n int pm = -1;\n int mc = -1;\n for (int i = 0; i < len1; i++) {\n if (isRow ? rowDone[i] : colDone[i]) {\n continue;\n }\n std::vector res = diff(i, len2, isRow);\n if (res[0] > md) {\n md = res[0]; // max diff\n pm = i; // pos of max diff\n mc = res[1]; // min cost\n pc = res[2]; // pos of min cost\n }\n }\n return isRow\n ? std::vector { pm, pc, mc, md }\n : std::vector{ pc, pm, mc, md };\n}\n\nstd::vector nextCell() {\n auto res1 = maxPenalty(nRows, nCols, true);\n auto res2 = maxPenalty(nCols, nRows, false);\n\n if (res1[3] == res2[3]) {\n return res1[2] < res2[2]\n ? res1\n : res2;\n }\n return res1[3] > res2[3]\n ? res2\n : res1;\n}\n\nint main() {\n int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });\n int totalCost = 0;\n\n while (supplyLeft > 0) {\n auto cell = nextCell();\n int r = cell[0];\n int c = cell[1];\n\n int quantity = std::min(demand[c], supply[r]);\n\n demand[c] -= quantity;\n if (demand[c] == 0) {\n colDone[c] = true;\n }\n\n supply[r] -= quantity;\n if (supply[r] == 0) {\n rowDone[r] = true;\n }\n\n result[r][c] = quantity;\n supplyLeft -= quantity;\n\n totalCost += quantity * costs[r][c];\n }\n\n for (auto &a : result) {\n std::cout << a << '\\n';\n }\n\n std::cout << \"Total cost: \" << totalCost;\n\n return 0;\n}"} {"title": "Voronoi diagram", "language": "C++", "task": "A Voronoi diagram is a diagram consisting of a number of sites. \n\nEach Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.\n\n\n;Task:\nDemonstrate how to generate and display a Voroni diagram. \n\n\nSee algo [[K-means++ clustering]].\n\n", "solution": "#include \n#include \n#include \n\nusing namespace std;\n\n//////////////////////////////////////////////////////\nstruct Point {\n int x, y;\n};\n\n//////////////////////////////////////////////////////\nclass MyBitmap {\n public:\n MyBitmap() : pen_(nullptr) {}\n ~MyBitmap() {\n DeleteObject(pen_);\n DeleteDC(hdc_);\n DeleteObject(bmp_);\n }\n\n bool Create(int w, int h) {\n BITMAPINFO\tbi;\n ZeroMemory(&bi, sizeof(bi));\n\n bi.bmiHeader.biSize = sizeof(bi.bmiHeader);\n bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n bi.bmiHeader.biCompression = BI_RGB;\n bi.bmiHeader.biPlanes = 1;\n bi.bmiHeader.biWidth = w;\n bi.bmiHeader.biHeight = -h;\n\n void *bits_ptr = nullptr;\n HDC dc = GetDC(GetConsoleWindow());\n bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);\n if (!bmp_) return false;\n\n hdc_ = CreateCompatibleDC(dc);\n SelectObject(hdc_, bmp_);\n ReleaseDC(GetConsoleWindow(), dc);\n\n width_ = w;\n height_ = h;\n\n return true;\n }\n\n void SetPenColor(DWORD clr) {\n if (pen_) DeleteObject(pen_);\n pen_ = CreatePen(PS_SOLID, 1, clr);\n SelectObject(hdc_, pen_);\n }\n\n bool SaveBitmap(const char* path) {\n HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (file == INVALID_HANDLE_VALUE) {\n return false;\n }\n\n BITMAPFILEHEADER fileheader;\n BITMAPINFO infoheader;\n BITMAP bitmap; \n GetObject(bmp_, sizeof(bitmap), &bitmap);\n\n DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));\n ZeroMemory(&infoheader, sizeof(BITMAPINFO));\n ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));\n\n infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;\n infoheader.bmiHeader.biCompression = BI_RGB;\n infoheader.bmiHeader.biPlanes = 1;\n infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);\n infoheader.bmiHeader.biHeight = bitmap.bmHeight;\n infoheader.bmiHeader.biWidth = bitmap.bmWidth;\n infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);\n\n fileheader.bfType = 0x4D42;\n fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);\n fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);\n\n DWORD wb;\n WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);\n WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);\n WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);\n CloseHandle(file);\n\n delete[] dwp_bits;\n return true;\n }\n\n HDC hdc() { return hdc_; }\n int width() { return width_; }\n int height() { return height_; }\n\n private:\n HBITMAP bmp_;\n HDC hdc_;\n HPEN pen_;\n int width_, height_;\n};\n\nstatic int DistanceSqrd(const Point& point, int x, int y) {\n int xd = x - point.x;\n int yd = y - point.y;\n return (xd * xd) + (yd * yd);\n}\n\n//////////////////////////////////////////////////////\nclass Voronoi {\n public:\n void Make(MyBitmap* bmp, int count) {\n bmp_ = bmp;\n CreatePoints(count);\n CreateColors();\n CreateSites();\n SetSitesPoints();\n }\n\n private:\n void CreateSites() {\n int w = bmp_->width(), h = bmp_->height(), d;\n for (int hh = 0; hh < h; hh++) {\n for (int ww = 0; ww < w; ww++) {\n int ind = -1, dist = INT_MAX;\n for (size_t it = 0; it < points_.size(); it++) {\n const Point& p = points_[it];\n d = DistanceSqrd(p, ww, hh);\n if (d < dist) {\n dist = d;\n ind = it;\n }\n }\n\n if (ind > -1)\n SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);\n else\n __asm nop // should never happen!\n }\n }\n }\n\n void SetSitesPoints() {\n for (const auto& point : points_) {\n int x = point.x, y = point.y;\n for (int i = -1; i < 2; i++)\n for (int j = -1; j < 2; j++)\n SetPixel(bmp_->hdc(), x + i, y + j, 0);\n }\n }\n\n void CreatePoints(int count) {\n const int w = bmp_->width() - 20, h = bmp_->height() - 20;\n for (int i = 0; i < count; i++) {\n points_.push_back({ rand() % w + 10, rand() % h + 10 });\n }\n }\n\n void CreateColors() {\n for (size_t i = 0; i < points_.size(); i++) {\n DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);\n colors_.push_back(c);\n }\n }\n\n vector points_;\n vector colors_;\n MyBitmap* bmp_;\n};\n\n//////////////////////////////////////////////////////\nint main(int argc, char* argv[]) {\n ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);\n srand(GetTickCount());\n\n MyBitmap bmp;\n bmp.Create(512, 512);\n bmp.SetPenColor(0);\n\n Voronoi v;\n v.Make(&bmp, 50);\n\n BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);\n bmp.SaveBitmap(\"v.bmp\");\n\n system(\"pause\");\n\n return 0;\n}\n"} {"title": "War card game", "language": "C++", "task": "War Card Game\n\nSimulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.\n\nReferences:\n\n:* Bicycle card company: War game site\n\n:* Wikipedia: War (card game)\n\nRelated tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards for FreeCell]]\n* [[Poker hand_analyser]]\n* [[Go Fish]]\n\n\n", "solution": "#include \n#include \n#include \n\nclass war_game {\npublic:\n\twar_game() {\n\t\tfor ( char suit : SUITS ) {\n\t\t\tfor ( char pip : PIPS ) {\n\t\t\t\tdeck.emplace_back(card(suit, pip));\n\t\t\t}\n\t\t}\n\t\tstd::random_shuffle(deck.begin(), deck.end());\n\n\t\thandA = { deck.begin(), deck.begin() + 26 };\n\t\thandB = { deck.begin() + 26, deck.end() };\n\t}\n\n\tvoid next_turn() {\n\t\tcard cardA = handA.front(); handA.erase(handA.begin());\n\t\tcard cardB = handB.front(); handB.erase(handB.begin());\n\t\ttabledCards.emplace_back(cardA);\n\t\ttabledCards.emplace_back(cardB);\n\t\tint32_t rankA = getRank(cardA.pip);\n\t\tint32_t rankB = getRank(cardB.pip);\n\t\tstd::cout << cardA.pip << cardA.suit << \" \" << cardB.pip << cardB.suit << std::endl;\n\n\t\tif ( rankA > rankB ) {\n\t\t\tstd::cout << \" Player A takes the cards\" << std::endl;\n\t\t\tstd::random_shuffle(tabledCards.begin(), tabledCards.end());\n\t\t\thandA.insert(handA.end(), tabledCards.begin(), tabledCards.end());\n\t\t\ttabledCards.clear();\n\t\t} else if ( rankA < rankB ) {\n\t\t\tstd::cout << \" Player B takes the cards\" << std::endl;\n\t\t\tstd::random_shuffle(tabledCards.begin(), tabledCards.end());\n\t\t\thandB.insert(handB.end(), tabledCards.begin(), tabledCards.end());;\n\t\t\ttabledCards.clear();\n\t\t} else {\n\t\t\tstd::cout << \" War!\" << std::endl;\n\t\t\tif ( game_over() ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcard cardAA = handA.front(); handA.erase(handA.begin());\n\t\t\tcard cardBB = handB.front(); handB.erase(handB.begin());\n\t\t\ttabledCards.emplace_back(cardAA);\n\t\t\ttabledCards.emplace_back(cardBB);\n\t\t\tstd::cout << \"? ? Cards are face down\" << std::endl;\n\t\t\tif ( game_over() ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tnext_turn();\n\t\t}\n\t}\n\n\tbool game_over() const {\n\t\treturn handA.size() == 0 || handB.size() == 0;\n\t}\n\n\tvoid declare_winner() const {\n\t\tif ( handA.size() == 0 && handB.size() == 0 ) {\n\t\t\tstd::cout << \"The game ended in a tie\" << std::endl;\n\t\t} else if ( handA.size() == 0 ) {\n\t\t\tstd::cout << \"Player B has won the game\" << std::endl;\n\t\t} else {\n\t\t\tstd::cout << \"Player A has won the game\" << std::endl;\n\t\t}\n\t}\nprivate:\n\tclass card {\n\tpublic:\n\t\tcard(const char suit, const char pip) : suit(suit), pip(pip) {};\n\t\tchar suit, pip;\n\t};\n\n\tint32_t getRank(const char ch)\tconst {\n\t auto it = find(PIPS.begin(), PIPS.end(), ch);\n\t if ( it != PIPS.end() ) {\n\t return it - PIPS.begin();\n\t }\n\t return -1;\n\t}\n\n\tstd::vector deck, handA, handB, tabledCards;\n\tinline static const std::vector PIPS = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };\n\tinline static const std::vector SUITS = { 'C', 'D', 'H', 'S' };\n};\n\nint main() {\n\twar_game wargame;\n\n\twhile ( ! wargame.game_over() ) {\n\t\twargame.next_turn();\n\t}\n\n\twargame.declare_winner();\n}\n"} {"title": "Water collected between towers", "language": "C++", "task": "In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, \ncompletely filling all convex enclosures in the chart with water. \n\n \n9 ## 9 ## \n8 ## 8 ## \n7 ## ## 7 #### \n6 ## ## ## 6 ###### \n5 ## ## ## #### 5 ########## \n4 ## ## ######## 4 ############ \n3 ###### ######## 3 ############## \n2 ################ ## 2 ##################\n1 #################### 1 ####################\n \n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n\nSee, also:\n\n* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.\n\n\n\n", "solution": "#include \n#include \n#include \n\nenum { EMPTY, WALL, WATER };\n\nauto fill(const std::vector b) {\n auto water = 0;\n const auto rows = *std::max_element(std::begin(b), std::end(b));\n const auto cols = std::size(b);\n std::vector> g(rows);\n for (auto& r : g) {\n for (auto i = 0; i < cols; ++i) {\n r.push_back(EMPTY);\n }\n }\n for (auto c = 0; c < cols; ++c) {\n for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {\n g[r][c] = WALL;\n }\n }\n for (auto c = 0; c < cols - 1; ++c) {\n auto start_row = rows - b[c];\n while (start_row < rows) {\n if (g[start_row][c] == EMPTY) break;\n auto c2 = c + 1;\n bool hitWall = false;\n while (c2 < cols) {\n if (g[start_row][c2] == WALL) {\n hitWall = true;\n break;\n }\n ++c2;\n }\n if (hitWall) {\n for (auto i = c + 1; i < c2; ++i) {\n g[start_row][i] = WATER;\n ++water;\n }\n }\n ++start_row;\n }\n }\n return water;\n}\n\nint main() {\n std::vector> b = {\n { 1, 5, 3, 7, 2 },\n { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },\n { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },\n { 5, 5, 5, 5 },\n { 5, 6, 7, 8 },\n { 8, 7, 7, 6 },\n { 6, 7, 10, 7, 6 }\n };\n for (const auto v : b) {\n auto water = fill(v);\n std::cout << water << \" water drops.\" << std::endl;\n }\n std::cin.ignore();\n std::cin.get();\n return 0;\n}"} {"title": "Weird numbers", "language": "C++ from D", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* MathWorld: weird number\n\n", "solution": "#include \n#include \n#include \n#include \n\nstd::vector divisors(int n) {\n std::vector divs = { 1 };\n std::vector divs2;\n\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n int j = n / i;\n divs.push_back(i);\n if (i != j) {\n divs2.push_back(j);\n }\n }\n }\n\n std::copy(divs.cbegin(), divs.cend(), std::back_inserter(divs2));\n return divs2;\n}\n\nbool abundant(int n, const std::vector &divs) {\n return std::accumulate(divs.cbegin(), divs.cend(), 0) > n;\n}\n\ntemplate\nbool semiperfect(int n, const IT &it, const IT &end) {\n if (it != end) {\n auto h = *it;\n auto t = std::next(it);\n if (n < h) {\n return semiperfect(n, t, end);\n } else {\n return n == h\n || semiperfect(n - h, t, end)\n || semiperfect(n, t, end);\n }\n } else {\n return false;\n }\n}\n\ntemplate\nbool semiperfect(int n, const C &c) {\n return semiperfect(n, std::cbegin(c), std::cend(c));\n}\n\nstd::vector sieve(int limit) {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n std::vector w(limit);\n for (int i = 2; i < limit; i += 2) {\n if (w[i]) continue;\n auto divs = divisors(i);\n if (!abundant(i, divs)) {\n w[i] = true;\n } else if (semiperfect(i, divs)) {\n for (int j = i; j < limit; j += i) {\n w[j] = true;\n }\n }\n }\n return w;\n}\n\nint main() {\n auto w = sieve(17000);\n int count = 0;\n int max = 25;\n std::cout << \"The first 25 weird numbers:\";\n for (int n = 2; count < max; n += 2) {\n if (!w[n]) {\n std::cout << n << ' ';\n count++;\n }\n }\n std::cout << '\\n';\n return 0;\n}"} {"title": "Word frequency", "language": "C++", "task": "Given a text file and an integer '''n''', print/display the '''n''' most\ncommon words in the file (and the number of their occurrences) in decreasing frequency.\n\n\nFor the purposes of this task:\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a ''letter'' is. \n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like '''well-dressed''' as either one word or two. \n* The word '''it's''' could also be one or two words as you see fit. \n* You may also choose not to support non US-ASCII characters. \n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences. \n* Treat '''color''' and '''colour''' as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*McIlroy's program\n\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint main(int ac, char** av) {\n std::ios::sync_with_stdio(false);\n int head = (ac > 1) ? std::atoi(av[1]) : 10;\n std::istreambuf_iterator it(std::cin), eof;\n std::filebuf file;\n if (ac > 2) {\n if (file.open(av[2], std::ios::in), file.is_open()) {\n it = std::istreambuf_iterator(&file);\n } else return std::cerr << \"file \" << av[2] << \" open failed\\n\", 1;\n }\n auto alpha = [](unsigned c) { return c-'A' < 26 || c-'a' < 26; };\n auto lower = [](unsigned c) { return c | '\\x20'; };\n std::unordered_map counts;\n std::string word;\n for (; it != eof; ++it) {\n if (alpha(*it)) {\n word.push_back(lower(*it));\n } else if (!word.empty()) {\n ++counts[word];\n word.clear();\n }\n }\n if (!word.empty()) ++counts[word]; // if file ends w/o ws\n std::vector const*> out;\n for (auto& count : counts) out.push_back(&count);\n std::partial_sort(out.begin(),\n out.size() < head ? out.end() : out.begin() + head,\n out.end(), [](auto const* a, auto const* b) {\n return a->second > b->second;\n });\n if (out.size() > head) out.resize(head);\n for (auto const& count : out) {\n std::cout << count->first << ' ' << count->second << '\\n';\n }\n return 0;\n}\n"} {"title": "Word frequency", "language": "C++ from C#", "task": "Given a text file and an integer '''n''', print/display the '''n''' most\ncommon words in the file (and the number of their occurrences) in decreasing frequency.\n\n\nFor the purposes of this task:\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a ''letter'' is. \n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like '''well-dressed''' as either one word or two. \n* The word '''it's''' could also be one or two words as you see fit. \n* You may also choose not to support non US-ASCII characters. \n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences. \n* Treat '''color''' and '''colour''' as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*McIlroy's program\n\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint main() {\n std::ifstream in(\"135-0.txt\");\n std::string text{\n std::istreambuf_iterator{in}, std::istreambuf_iterator{}\n };\n in.close();\n\n std::regex word_rx(\"\\\\w+\");\n std::map freq;\n for (const auto& a : std::ranges::subrange(\n std::sregex_iterator{ text.cbegin(),text.cend(), word_rx }, std::sregex_iterator{}\n ))\n {\n auto word = a.str();\n transform(word.begin(), word.end(), word.begin(), ::tolower);\n freq[word]++;\n }\n\n std::vector> pairs;\n for (const auto& elem : freq)\n {\n pairs.push_back(elem);\n }\n\n std::ranges::sort(pairs, std::ranges::greater{}, &std::pair::second);\n\n std::cout << \"Rank Word Frequency\\n\"\n \"==== ==== =========\\n\";\n for (int rank=1; const auto& [word, count] : pairs | std::views::take(10))\n {\n std::cout << std::format(\"{:2} {:>4} {:5}\\n\", rank++, word, count);\n }\n}"} {"title": "Word ladder", "language": "C++", "task": "Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.\n\nOnly one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.\n\nDemonstrate the following:\n\nA boy can be made into a man: boy -> bay -> ban -> man\n\nWith a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady\n\nA john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane \n\nA child can not be turned into an adult.\n\nOptional transpositions of your choice.\n\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing word_map = std::map>;\n\n// Returns true if strings s1 and s2 differ by one character.\nbool one_away(const std::string& s1, const std::string& s2) {\n if (s1.size() != s2.size())\n return false;\n bool result = false;\n for (size_t i = 0, n = s1.size(); i != n; ++i) {\n if (s1[i] != s2[i]) {\n if (result)\n return false;\n result = true;\n }\n }\n return result;\n}\n\n// Join a sequence of strings into a single string using the given separator.\ntemplate \nstd::string join(iterator_type begin, iterator_type end,\n separator_type separator) {\n std::string result;\n if (begin != end) {\n result += *begin++;\n for (; begin != end; ++begin) {\n result += separator;\n result += *begin;\n }\n }\n return result;\n}\n\n// If possible, print the shortest chain of single-character modifications that\n// leads from \"from\" to \"to\", with each intermediate step being a valid word.\n// This is an application of breadth-first search.\nbool word_ladder(const word_map& words, const std::string& from,\n const std::string& to) {\n auto w = words.find(from.size());\n if (w != words.end()) {\n auto poss = w->second;\n std::vector> queue{{from}};\n while (!queue.empty()) {\n auto curr = queue.front();\n queue.erase(queue.begin());\n for (auto i = poss.begin(); i != poss.end();) {\n if (!one_away(*i, curr.back())) {\n ++i;\n continue;\n }\n if (to == *i) {\n curr.push_back(to);\n std::cout << join(curr.begin(), curr.end(), \" -> \") << '\\n';\n return true;\n }\n std::vector temp(curr);\n temp.push_back(*i);\n queue.push_back(std::move(temp));\n i = poss.erase(i);\n }\n }\n }\n std::cout << from << \" into \" << to << \" cannot be done.\\n\";\n return false;\n}\n\nint main() {\n word_map words;\n std::ifstream in(\"unixdict.txt\");\n if (!in) {\n std::cerr << \"Cannot open file unixdict.txt.\\n\";\n return EXIT_FAILURE;\n }\n std::string word;\n while (getline(in, word))\n words[word.size()].push_back(word);\n word_ladder(words, \"boy\", \"man\");\n word_ladder(words, \"girl\", \"lady\");\n word_ladder(words, \"john\", \"jane\");\n word_ladder(words, \"child\", \"adult\");\n word_ladder(words, \"cat\", \"dog\");\n word_ladder(words, \"lead\", \"gold\");\n word_ladder(words, \"white\", \"black\");\n word_ladder(words, \"bubble\", \"tickle\");\n return EXIT_SUCCESS;\n}"} {"title": "Word search", "language": "C++", "task": "A word search puzzle typically consists of a grid of letters in which words are hidden.\n\nThere are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.\n\nThe words may overlap but are not allowed to zigzag, or wrap around.\n\n;Task \nCreate a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.\n\nThe cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. \n\nPack a minimum of 25 words into the grid.\n\nPrint the resulting grid and the solutions.\n\n;Example\n\n\n 0 1 2 3 4 5 6 7 8 9\n\n0 n a y r y R e l m f \n1 y O r e t s g n a g \n2 t n e d i S k y h E \n3 n o t n c p c w t T \n4 a l s u u n T m a x \n5 r o k p a r i s h h \n6 a A c f p a e a c C \n7 u b u t t t O l u n \n8 g y h w a D h p m u \n9 m i r p E h o g a n \n\nparish (3,5)(8,5) gangster (9,1)(2,1)\npaucity (4,6)(4,0) guaranty (0,8)(0,1)\nprim (3,9)(0,9) huckster (2,8)(2,1)\nplasm (7,8)(7,4) fancy (3,6)(7,2)\nhogan (5,9)(9,9) nolo (1,2)(1,5)\nunder (3,4)(3,0) chatham (8,6)(8,0)\nate (4,8)(6,6) nun (9,7)(9,9)\nbutt (1,7)(4,7) hawk (9,5)(6,2)\nwhy (3,8)(1,8) ryan (3,0)(0,0)\nfay (9,0)(7,2) much (8,8)(8,5)\ntar (5,7)(5,5) elm (6,0)(8,0)\nmax (7,4)(9,4) pup (5,3)(3,5)\nmph (8,8)(6,8)\n\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;\n\nclass Cell {\npublic:\n Cell() : val( 0 ), cntOverlap( 0 ) {}\n char val; int cntOverlap;\n};\nclass Word {\npublic:\n Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : \n word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}\n bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }\n std::string word;\n int cols, rows, cole, rowe, dx, dy;\n};\nclass words {\npublic:\n void create( std::string& file ) {\n std::ifstream f( file.c_str(), std::ios_base::in );\n std::string word;\n while( f >> word ) {\n if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;\n if( word.find_first_not_of( \"abcdefghijklmnopqrstuvwxyz\" ) != word.npos ) continue;\n dictionary.push_back( word );\n }\n f.close();\n std::random_shuffle( dictionary.begin(), dictionary.end() );\n buildPuzzle();\n }\n\n void printOut() {\n std::cout << \"\\t\";\n for( int x = 0; x < WID; x++ ) std::cout << x << \" \";\n std::cout << \"\\n\\n\";\n for( int y = 0; y < HEI; y++ ) {\n std::cout << y << \"\\t\";\n for( int x = 0; x < WID; x++ )\n std::cout << puzzle[x][y].val << \" \";\n std::cout << \"\\n\";\n }\n size_t wid1 = 0, wid2 = 0;\n for( size_t x = 0; x < used.size(); x++ ) {\n if( x & 1 ) {\n if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();\n } else {\n if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();\n }\n }\n std::cout << \"\\n\";\n std::vector::iterator w = used.begin();\n while( w != used.end() ) {\n std::cout << std::right << std::setw( wid1 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n << ( *w ).cole << \", \" << ( *w ).rowe << \")\\t\";\n w++;\n if( w == used.end() ) break;\n std::cout << std::setw( wid2 ) << ( *w ).word << \" (\" << ( *w ).cols << \", \" << ( *w ).rows << \") (\" \n << ( *w ).cole << \", \" << ( *w ).rowe << \")\\n\";\n w++;\n }\n std::cout << \"\\n\\n\";\n }\nprivate:\n void addMsg() {\n std::string msg = \"ROSETTACODE\";\n int stp = 9, p = rand() % stp;\n for( size_t x = 0; x < msg.length(); x++ ) {\n puzzle[p % WID][p / HEI].val = msg.at( x );\n p += rand() % stp + 4;\n }\n }\n int getEmptySpaces() {\n int es = 0;\n for( int y = 0; y < HEI; y++ ) {\n for( int x = 0; x < WID; x++ ) {\n if( !puzzle[x][y].val ) es++;\n }\n }\n return es;\n }\n bool check( std::string word, int c, int r, int dc, int dr ) {\n for( size_t a = 0; a < word.length(); a++ ) {\n if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;\n if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;\n c += dc; r += dr;\n }\n return true;\n }\n bool setWord( std::string word, int c, int r, int dc, int dr ) {\n if( !check( word, c, r, dc, dr ) ) return false;\n int sx = c, sy = r;\n for( size_t a = 0; a < word.length(); a++ ) {\n if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );\n else puzzle[c][r].cntOverlap++;\n c += dc; r += dr;\n }\n used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );\n return true;\n }\n bool add2Puzzle( std::string word ) {\n int x = rand() % WID, y = rand() % HEI,\n z = rand() % 8;\n for( int d = z; d < z + 8; d++ ) {\n switch( d % 8 ) {\n case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break;\n case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;\n case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break;\n case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break;\n case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break;\n case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break;\n case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break;\n case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break;\n }\n }\n return false;\n }\n void clearWord() {\n if( used.size() ) {\n Word lastW = used.back();\n used.pop_back();\n\n for( size_t a = 0; a < lastW.word.length(); a++ ) {\n if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {\n puzzle[lastW.cols][lastW.rows].val = 0;\n }\n if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {\n puzzle[lastW.cols][lastW.rows].cntOverlap--;\n }\n lastW.cols += lastW.dx; lastW.rows += lastW.dy;\n }\n }\n }\n void buildPuzzle() {\n addMsg();\n int es = 0, cnt = 0;\n size_t idx = 0;\n do {\n for( std::vector::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {\n if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;\n \n if( add2Puzzle( *w ) ) {\n es = getEmptySpaces();\n if( !es && used.size() >= MIN_WORD_CNT ) \n return;\n }\n }\n clearWord();\n std::random_shuffle( dictionary.begin(), dictionary.end() );\n\n } while( ++cnt < 100 );\n }\n std::vector used;\n std::vector dictionary;\n Cell puzzle[WID][HEI];\n};\nint main( int argc, char* argv[] ) {\n unsigned s = unsigned( time( 0 ) );\n srand( s );\n words w; w.create( std::string( \"unixdict.txt\" ) );\n w.printOut();\n return 0;\n}\n"} {"title": "Word wrap", "language": "C++ from Go", "task": "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "#include \n#include \n#include \n\nconst char *text =\n{\n \"In olden times when wishing still helped one, there lived a king \"\n \"whose daughters were all beautiful, but the youngest was so beautiful \"\n \"that the sun itself, which has seen so much, was astonished whenever \"\n \"it shone in her face. Close by the king's castle lay a great dark \"\n \"forest, and under an old lime tree in the forest was a well, and when \"\n \"the day was very warm, the king's child went out into the forest and \"\n \"sat down by the side of the cool fountain, and when she was bored she \"\n \"took a golden ball, and threw it up on high and caught it, and this \"\n \"ball was her favorite plaything.\"\n};\n\nstd::string wrap(const char *text, size_t line_length = 72)\n{\n std::istringstream words(text);\n std::ostringstream wrapped;\n std::string word;\n\n if (words >> word) {\n wrapped << word;\n size_t space_left = line_length - word.length();\n while (words >> word) {\n if (space_left < word.length() + 1) {\n wrapped << '\\n' << word;\n space_left = line_length - word.length();\n } else {\n wrapped << ' ' << word;\n space_left -= word.length() + 1;\n }\n }\n }\n return wrapped.str();\n}\n\nint main()\n{\n std::cout << \"Wrapped at 72:\\n\" << wrap(text) << \"\\n\\n\";\n std::cout << \"Wrapped at 80:\\n\" << wrap(text, 80) << \"\\n\";\n}"} {"title": "World Cup group stage", "language": "C++ from Go", "task": "It's World Cup season (or at least it was when this page was created)! \n\nThe World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams. \n\nFor the first part of the World Cup tournament the teams play in \"group stage\" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage. \n\nEach game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. \n:::* A win is worth three points.\n:::* A draw/tie is worth one point. \n:::* A loss is worth zero points.\n\n\n;Task:\n:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. \n:* Calculate the standings points for each team with each combination of outcomes. \n:* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.\n\n\nDon't worry about tiebreakers as they can get complicated. We are basically looking to answer the question \"if a team gets x standings points, where can they expect to end up in the group standings?\".\n\n''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''\n\n", "solution": "#include \n#include \n#include \n#include \n#include \n\nstd::array games{ \"12\", \"13\", \"14\", \"23\", \"24\", \"34\" };\nstd::string results = \"000000\";\n\nint fromBase3(std::string num) {\n int out = 0;\n for (auto c : num) {\n int d = c - '0';\n out = 3 * out + d;\n }\n return out;\n}\n\nstd::string toBase3(int num) {\n std::stringstream ss;\n\n while (num > 0) {\n int rem = num % 3;\n num /= 3;\n ss << rem;\n }\n\n auto str = ss.str();\n std::reverse(str.begin(), str.end());\n return str;\n}\n\nbool nextResult() {\n if (results == \"222222\") {\n return false;\n }\n\n auto res = fromBase3(results);\n\n std::stringstream ss;\n ss << std::setw(6) << std::setfill('0') << toBase3(res + 1);\n results = ss.str();\n\n return true;\n}\n\nint main() {\n std::array, 4> points;\n for (auto &row : points) {\n std::fill(row.begin(), row.end(), 0);\n }\n\n do {\n std::array records {0, 0, 0, 0 };\n\n for (size_t i = 0; i < games.size(); i++) {\n switch (results[i]) {\n case '2':\n records[games[i][0] - '1'] += 3;\n break;\n case '1':\n records[games[i][0] - '1']++;\n records[games[i][1] - '1']++;\n break;\n case '0':\n records[games[i][1] - '1'] += 3;\n break;\n default:\n break;\n }\n }\n\n std::sort(records.begin(), records.end());\n for (size_t i = 0; i < records.size(); i++) {\n points[i][records[i]]++;\n }\n } while (nextResult());\n\n std::cout << \"POINTS 0 1 2 3 4 5 6 7 8 9\\n\";\n std::cout << \"-------------------------------------------------------------\\n\";\n std::array places{ \"1st\", \"2nd\", \"3rd\", \"4th\" };\n for (size_t i = 0; i < places.size(); i++) {\n std::cout << places[i] << \" place\";\n for (size_t j = 0; j < points[i].size(); j++) {\n std::cout << std::setw(5) << points[3 - i][j];\n }\n std::cout << '\\n';\n }\n return 0;\n}"} {"title": "Write float arrays to a text file", "language": "C++", "task": "Write two equal-sized numerical arrays 'x' and 'y' to \na two-column text file named 'filename'.\n\nThe first column of the file contains values from an 'x'-array with a \ngiven 'xprecision', the second -- values from 'y'-array with 'yprecision'.\n\nFor example, considering:\n x = {1, 2, 3, 1e11};\n y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; \n /* sqrt(x) */\n xprecision = 3;\n yprecision = 5;\n\nThe file should look like:\n 1 1\n 2 1.4142\n 3 1.7321\n 1e+011 3.1623e+005\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "#include \n#include // ::sqrt()\n#include \n#include // setprecision()\n#include \n#include \n#include \n\nint main()\n{\n try {\n // prepare test data\n double x[] = {1, 2, 3, 1e11};\n const size_t xsize = sizeof(x) / sizeof(*x);\n std::vector y(xsize);\n std::transform(&x[0], &x[xsize], y.begin(), ::sqrt);\n\n // write file using default precisions\n writedat(\"sqrt.dat\", &x[0], &x[xsize], y.begin(), y.end());\n\n // print the result file\n std::ifstream f(\"sqrt.dat\");\n for (std::string line; std::getline(f, line); )\n std::cout << line << std::endl;\n }\n catch(std::exception& e) {\n std::cerr << \"writedat: exception: '\" << e.what() << \"'\\n\";\n return 1;\n }\n return 0;\n}"} {"title": "Write language name in 3D ASCII", "language": "C++", "task": "Write/display a language's name in '''3D''' ASCII. \n\n\n(We can leave the definition of \"3D ASCII\" fuzzy, \nso long as the result is interesting or amusing, \nnot a cheap hack to satisfy the task.)\n\n\n;Related tasks:\n* draw a sphere\n* draw a cuboid\n* draw a rotating cube\n* draw a Deathstar\n\n", "solution": "#include \n#include \n\n//--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n//--------------------------------------------------------------------------------------------------\nint main(int argc, char* argv[])\n{\n\tcout << \n\t\t\" ______ ______ \" << endl <<\n\t\t\" _____ _____|\\\\ \\\\ _____|\\\\ \\\\ \" << endl <<\n\t\t\" _____\\\\ \\\\_ / / | | / / | |\" << endl <<\n\t\t\" / /| || |/ /|| |/ /|\" << endl <<\n\t\t\" / / /____/|| |\\\\____/ || |\\\\____/ |\" << endl <<\n\t\t\"| | |____|/ |\\\\ \\\\ | / |\\\\ \\\\ | / \" << endl <<\n\t\t\"| | _____ | \\\\ \\\\___|/ | \\\\ \\\\___|/ \" << endl <<\n\t\t\"|\\\\ \\\\|\\\\ \\\\ | \\\\ \\\\ | \\\\ \\\\ \" << endl <<\n\t\t\"| \\\\_____\\\\| | \\\\ \\\\_____\\\\ \\\\ \\\\_____\\\\ \" << endl <<\n\t\t\"| | /____/| \\\\ | | \\\\ | | \" << endl <<\n\t\t\" \\\\|_____| || \\\\|_____| \\\\|_____| \" << endl <<\n\t\t\" |____|/ \";\n\n\tcout << endl << endl << endl;\n\n\tsystem( \"pause\" );\n\treturn 0;\n}\n//--------------------------------------------------------------------------------------------------\n"} {"title": "Write to Windows event log", "language": "C++ from C", "task": "Write script status to the Windows Event Log\n\n", "solution": "#include \n#include \n\nint main(int argc, char *argv[]) {\n using namespace std;\n\n#if _WIN32\n if (argc != 5) {\n cout << \"Usage : \" << argv[0] << \" (type) (id) (source string) (description>)\\n\";\n cout << \" Valid types: SUCCESS, ERROR, WARNING, INFORMATION\\n\";\n } else {\n stringstream ss;\n ss << \"EventCreate /t \" << argv[1] << \" /id \" << argv[2] << \" /l APPLICATION /so \" << argv[3] << \" /d \\\"\" << argv[4] << \"\\\"\";\n system(ss.str().c_str());\n }\n#else\n cout << \"Not implemented for *nix, only windows.\\n\";\n#endif\n\n return 0;\n}"} {"title": "Yellowstone sequence", "language": "C++", "task": "The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:\n\nFor n <= 3,\n\n a(n) = n\n\nFor n >= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first '''30''' Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* Greatest common divisor.\n:* Plot coordinate pairs.\n\n\n;See also:\n:* The OEIS entry: A098550 The Yellowstone permutation.\n:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "#include \n#include \n#include \n\ntemplate \nclass yellowstone_generator {\npublic:\n integer next() {\n n2_ = n1_;\n n1_ = n_;\n if (n_ < 3) {\n ++n_;\n } else {\n for (n_ = min_; !(sequence_.count(n_) == 0\n && std::gcd(n1_, n_) == 1\n && std::gcd(n2_, n_) > 1); ++n_) {}\n }\n sequence_.insert(n_);\n for (;;) {\n auto it = sequence_.find(min_);\n if (it == sequence_.end())\n break;\n sequence_.erase(it);\n ++min_;\n }\n return n_;\n }\nprivate:\n std::set sequence_;\n integer min_ = 1;\n integer n_ = 0;\n integer n1_ = 0;\n integer n2_ = 0;\n};\n\nint main() {\n std::cout << \"First 30 Yellowstone numbers:\\n\";\n yellowstone_generator ygen;\n std::cout << ygen.next();\n for (int i = 1; i < 30; ++i)\n std::cout << ' ' << ygen.next();\n std::cout << '\\n';\n return 0;\n}"} {"title": "Zeckendorf number representation", "language": "C++11", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "// For a class N which implements Zeckendorf numbers:\n// I define an increment operation ++()\n// I define a comparison operation <=(other N)\n// Nigel Galloway October 22nd., 2012\n#include \nclass N {\nprivate:\n int dVal = 0, dLen;\npublic:\n N(char const* x = \"0\"){\n int i = 0, q = 1;\n for (; x[i] > 0; i++);\n for (dLen = --i/2; i >= 0; i--) {\n dVal+=(x[i]-48)*q;\n q*=2;\n }}\n const N& operator++() {\n for (int i = 0;;i++) {\n if (dLen < i) dLen = i;\n switch ((dVal >> (i*2)) & 3) {\n case 0: dVal += (1 << (i*2)); return *this;\n case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this;\n case 2: dVal &= ~(3 << (i*2));\n }}}\n const bool operator<=(const N& other) const {return dVal <= other.dVal;}\n friend std::ostream& operator<<(std::ostream&, const N&);\n};\nN operator \"\" N(char const* x) {return N(x);}\nstd::ostream &operator<<(std::ostream &os, const N &G) {\n const static std::string dig[] {\"00\",\"01\",\"10\"}, dig1[] {\"\",\"1\",\"10\"};\n if (G.dVal == 0) return os << \"0\";\n os << dig1[(G.dVal >> (G.dLen*2)) & 3];\n for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3];\n return os;\n}\n"} {"title": "Zero to the zero power", "language": "C++", "task": "Some computer programming languages are not exactly consistent (with other computer programming languages) \nwhen ''raising zero to the zeroth power'': 00\n\n\n;Task:\nShow the results of raising zero to the zeroth power.\n\n\nIf your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like:\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n\n'''Show the result here.'''\nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation. \n\n\n;See also:\n* The Wiki entry: Zero to the power of zero. \n* The Wiki entry: Zero to the power of zero: History.\n* The MathWorld(tm) entry: exponent laws.\n** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1.\n* The OEIS entry: The special case of zero to the zeroth power\n\n", "solution": "#include \n#include \n#include \n\nint main()\n{\n std::cout << \"0 ^ 0 = \" << std::pow(0,0) << std::endl;\n std::cout << \"0+0i ^ 0+0i = \" <<\n std::pow(std::complex(0),std::complex(0)) << std::endl;\n return 0;\n}"} {"title": "Zhang-Suen thinning algorithm", "language": "C++", "task": "This is an algorithm used to thin a black and white i.e. one bit per pixel images. \n\nFor example, with an input image of:\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \nIt produces the thinned output:\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n\n;Algorithm:\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours. \n\nThe neighbours are, in order, arranged as:\n\n\n P9 P2 P3 \n P8 P1 P4 \n P7 P6 P5 \n\n\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\n\n;Step 1:\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\n\n;Step 2:\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and '''P8''' is white\n* (4) At least one of '''P2''' and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\n\n;Iteration:\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\n\n;Task:\n# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. \n\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n\n;Reference:\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen\n\n", "solution": "#include \n#include \n#include \n#include \nconst std::string input {\n\"................................\"\n\".#########.......########.......\"\n\".###...####.....####..####......\"\n\".###....###.....###....###......\"\n\".###...####.....###.............\"\n\".#########......###.............\"\n\".###.####.......###....###......\"\n\".###..####..###.####..####.###..\"\n\".###...####.###..########..###..\"\n\"................................\"\n};\nconst std::string input2 {\n\"..........................................................\"\n\".#################...................#############........\"\n\".##################...............################........\"\n\".###################............##################........\"\n\".########.....#######..........###################........\"\n\"...######.....#######.........#######.......######........\"\n\"...######.....#######........#######......................\"\n\"...#################.........#######......................\"\n\"...################..........#######......................\"\n\"...#################.........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######........#######......................\"\n\"...######.....#######.........#######.......######........\"\n\".########.....#######..........###################........\"\n\".########.....#######.######....##################.######.\"\n\".########.....#######.######......################.######.\"\n\".########.....#######.######.........#############.######.\"\n\"..........................................................\"\n};\n\nclass ZhangSuen;\n\nclass Image {\npublic:\n friend class ZhangSuen;\n using pixel_t = char;\n static const pixel_t BLACK_PIX;\n static const pixel_t WHITE_PIX;\n\n Image(unsigned width = 1, unsigned height = 1) \n : width_{width}, height_{height}, data_( '\\0', width_ * height_)\n {}\n Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}\n {}\n Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}\n {}\n ~Image() = default;\n Image& operator=(const Image& i) {\n if (this != &i) {\n width_ = i.width_;\n height_ = i.height_;\n data_ = i.data_;\n }\n return *this;\n }\n Image& operator=(Image&& i) {\n if (this != &i) {\n width_ = i.width_;\n height_ = i.height_;\n data_ = std::move(i.data_);\n }\n return *this;\n }\n size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }\n bool operator()(unsigned x, unsigned y) {\n return data_[idx(x, y)];\n }\n friend std::ostream& operator<<(std::ostream& o, const Image& i) {\n o << i.width_ << \" x \" << i.height_ << std::endl;\n size_t px = 0;\n for(const auto& e : i.data_) {\n o << (e?Image::BLACK_PIX:Image::WHITE_PIX);\n if (++px % i.width_ == 0)\n o << std::endl;\n }\n return o << std::endl;\n }\n friend std::istream& operator>>(std::istream& in, Image& img) {\n auto it = std::begin(img.data_);\n const auto end = std::end(img.data_);\n Image::pixel_t tmp;\n while(in && it != end) {\n in >> tmp;\n if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)\n throw \"Bad character found in image\";\n *it = (tmp == Image::BLACK_PIX)?1:0;\n ++it;\n }\n return in;\n }\n unsigned width() const noexcept { return width_; }\n unsigned height() const noexcept { return height_; }\n struct Neighbours {\n // 9 2 3\n // 8 1 4\n // 7 6 5\n Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)\n : img_{img}\n , p1_{img.idx(p1_x, p1_y)}\n , p2_{p1_ - img.width()}\n , p3_{p2_ + 1}\n , p4_{p1_ + 1}\n , p5_{p4_ + img.width()}\n , p6_{p5_ - 1}\n , p7_{p6_ - 1}\n , p8_{p1_ - 1}\n , p9_{p2_ - 1} \n {}\n const Image& img_;\n const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }\n const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }\n const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }\n const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }\n const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }\n const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }\n const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }\n const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }\n const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }\n const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;\n };\n Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }\nprivate:\n unsigned height_ { 0 };\n unsigned width_ { 0 };\n std::valarray data_;\n};\n\nconstexpr const Image::pixel_t Image::BLACK_PIX = '#';\nconstexpr const Image::pixel_t Image::WHITE_PIX = '.';\n\nclass ZhangSuen {\npublic:\n\n // the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2\n unsigned transitions_white_black(const Image::Neighbours& a) const {\n unsigned sum = 0;\n sum += (a.p9() == 0) && a.p2();\n sum += (a.p2() == 0) && a.p3();\n sum += (a.p3() == 0) && a.p4();\n sum += (a.p8() == 0) && a.p9();\n sum += (a.p4() == 0) && a.p5();\n sum += (a.p7() == 0) && a.p8();\n sum += (a.p6() == 0) && a.p7();\n sum += (a.p5() == 0) && a.p6();\n return sum;\n }\n\n // The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n unsigned black_pixels(const Image::Neighbours& a) const {\n unsigned sum = 0;\n sum += a.p9();\n sum += a.p2();\n sum += a.p3();\n sum += a.p8();\n sum += a.p4();\n sum += a.p7();\n sum += a.p6();\n sum += a.p5();\n return sum;\n }\n const Image& operator()(const Image& img) {\n tmp_a_ = img;\n size_t changed_pixels = 0;\n do {\n changed_pixels = 0;\n // Step 1\n tmp_b_ = tmp_a_;\n for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {\n for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {\n if (tmp_a_.data_[tmp_a_.idx(x, y)]) {\n auto n = tmp_a_.neighbours(x, y);\n auto bp = black_pixels(n);\n if (bp >= 2 && bp <= 6) {\n auto tr = transitions_white_black(n);\n if ( tr == 1 \n && (n.p2() * n.p4() * n.p6() == 0)\n && (n.p4() * n.p6() * n.p8() == 0)\n ) {\n tmp_b_.data_[n.p1_] = 0;\n ++changed_pixels;\n }\n }\n } \n }\n }\n // Step 2\n tmp_a_ = tmp_b_;\n for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {\n for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {\n if (tmp_b_.data_[tmp_b_.idx(x, y)]) {\n auto n = tmp_b_.neighbours(x, y);\n auto bp = black_pixels(n);\n if (bp >= 2 && bp <= 6) {\n auto tr = transitions_white_black(n);\n if ( tr == 1 \n && (n.p2() * n.p4() * n.p8() == 0)\n && (n.p2() * n.p6() * n.p8() == 0)\n ) {\n tmp_a_.data_[n.p1_] = 0;\n ++changed_pixels;\n }\n }\n } \n }\n }\n } while(changed_pixels > 0);\n return tmp_a_;\n }\nprivate:\n Image tmp_a_;\n Image tmp_b_;\n};\n\nint main(int argc, char const *argv[])\n{\n using namespace std;\n Image img(32, 10);\n istringstream iss{input};\n iss >> img;\n cout << img;\n cout << \"ZhangSuen\" << endl;\n ZhangSuen zs;\n Image res = std::move(zs(img));\n cout << res << endl;\n\n Image img2(58,18);\n istringstream iss2{input2};\n iss2 >> img2;\n cout << img2;\n cout << \"ZhangSuen with big image\" << endl;\n Image res2 = std::move(zs(img2));\n cout << res2 << endl;\n return 0;\n}\n"}