title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
100 prisoners
C++
The Problem: * 100 prisoners are individually numbered 1 to 100 * A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. * Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. * Prisoners start outside the room :* They can decide some strategy before any enter the room. :* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. :* A prisoner can open no more than 50 drawers. :* A prisoner tries to find his own number. :* A prisoner finding his own number is then held apart from the others. * If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. ;The task: # Simulate several thousand instances of the game where the prisoners randomly open drawers # Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: :* First opening the drawer whose outside number is his prisoner number. :* 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). Show and compare the computed probabilities of success for the two strategies, here, on this page. ;References: # The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). # [[wp:100 prisoners problem]] # 100 Prisoners Escape Puzzle DataGenetics. # Random permutation statistics#One hundred prisoners on Wikipedia.
#include <cstdlib> // for rand #include <algorithm> // for random_shuffle #include <iostream> // for output using namespace std; class cupboard { public: cupboard() { for (int i = 0; i < 100; i++) drawers[i] = i; random_shuffle(drawers, drawers + 100); } bool playRandom(); bool playOptimal(); private: int drawers[100]; }; bool cupboard::playRandom() { bool openedDrawers[100] = { 0 }; for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { // loops through prisoners numbered 0 through 99 bool prisonerSuccess = false; for (int i = 0; i < 100 / 2; i++) { // loops through 50 draws for each prisoner int drawerNum = rand() % 100; if (!openedDrawers[drawerNum]) { openedDrawers[drawerNum] = true; break; } if (drawers[drawerNum] == prisonerNum) { prisonerSuccess = true; break; } } if (!prisonerSuccess) return false; } return true; } bool cupboard::playOptimal() { for (int prisonerNum = 0; prisonerNum < 100; prisonerNum++) { bool prisonerSuccess = false; int checkDrawerNum = prisonerNum; for (int i = 0; i < 100 / 2; i++) { if (drawers[checkDrawerNum] == prisonerNum) { prisonerSuccess = true; break; } else checkDrawerNum = drawers[checkDrawerNum]; } if (!prisonerSuccess) return false; } return true; } double simulate(char strategy) { int numberOfSuccesses = 0; for (int i = 0; i < 10000; i++) { cupboard d; if ((strategy == 'R' && d.playRandom()) || (strategy == 'O' && d.playOptimal())) // will run playRandom or playOptimal but not both because of short-circuit evaluation numberOfSuccesses++; } return numberOfSuccesses * 100.0 / 10000; } int main() { cout << "Random strategy: " << simulate('R') << " %" << endl; cout << "Optimal strategy: " << simulate('O') << " %" << endl; system("PAUSE"); // for Windows return 0; }
15 puzzle game
C++
Implement the Fifteen Puzzle Game. The '''15-puzzle''' is also known as: :::* '''Fifteen Puzzle''' :::* '''Gem Puzzle''' :::* '''Boss Puzzle''' :::* '''Game of Fifteen''' :::* '''Mystic Square''' :::* '''14-15 Puzzle''' :::* and some others. ;Related Tasks: :* 15 Puzzle Solver :* [[16 Puzzle Game]]
#include <time.h> #include <stdlib.h> #include <vector> #include <string> #include <iostream> class p15 { public : void play() { bool p = true; std::string a; while( p ) { createBrd(); while( !isDone() ) { drawBrd();getMove(); } drawBrd(); std::cout << "\n\nCongratulations!\nPlay again (Y/N)?"; std::cin >> a; if( a != "Y" && a != "y" ) break; } } private: void createBrd() { int i = 1; std::vector<int> v; for( ; i < 16; i++ ) { brd[i - 1] = i; } brd[15] = 0; x = y = 3; for( i = 0; i < 1000; i++ ) { getCandidates( v ); move( v[rand() % v.size()] ); v.clear(); } } void move( int d ) { int t = x + y * 4; switch( d ) { case 1: y--; break; case 2: x++; break; case 4: y++; break; case 8: x--; } brd[t] = brd[x + y * 4]; brd[x + y * 4] = 0; } void getCandidates( std::vector<int>& v ) { if( x < 3 ) v.push_back( 2 ); if( x > 0 ) v.push_back( 8 ); if( y < 3 ) v.push_back( 4 ); if( y > 0 ) v.push_back( 1 ); } void drawBrd() { int r; std::cout << "\n\n"; for( int y = 0; y < 4; y++ ) { std::cout << "+----+----+----+----+\n"; for( int x = 0; x < 4; x++ ) { r = brd[x + y * 4]; std::cout << "| "; if( r < 10 ) std::cout << " "; if( !r ) std::cout << " "; else std::cout << r << " "; } std::cout << "|\n"; } std::cout << "+----+----+----+----+\n"; } void getMove() { std::vector<int> v; getCandidates( v ); std::vector<int> p; getTiles( p, v ); unsigned int i; while( true ) { std::cout << "\nPossible moves: "; for( i = 0; i < p.size(); i++ ) std::cout << p[i] << " "; int z; std::cin >> z; for( i = 0; i < p.size(); i++ ) if( z == p[i] ) { move( v[i] ); return; } } } void getTiles( std::vector<int>& p, std::vector<int>& v ) { for( unsigned int t = 0; t < v.size(); t++ ) { int xx = x, yy = y; switch( v[t] ) { case 1: yy--; break; case 2: xx++; break; case 4: yy++; break; case 8: xx--; } p.push_back( brd[xx + yy * 4] ); } } bool isDone() { for( int i = 0; i < 15; i++ ) { if( brd[i] != i + 1 ) return false; } return true; } int brd[16], x, y; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); p15 p; p.play(); return 0; }
21 game
C++
'''21''' is a two player game, the game is played by choosing a number ('''1''', '''2''', or '''3''') to be added to the ''running total''. The game is won by the player whose chosen number causes the ''running total'' to reach ''exactly'' '''21'''. The ''running total'' starts at zero. One player will be the computer. Players alternate supplying a number to be added to the ''running total''. ;Task: Write a computer program that will: ::* do the prompting (or provide a button menu), ::* check for errors and display appropriate error messages, ::* do the additions (add a chosen number to the ''running total''), ::* display the ''running total'', ::* provide a mechanism for the player to quit/exit/halt/stop/close the program, ::* issue a notification when there is a winner, and ::* determine who goes first (maybe a random or user choice, or can be specified when the game begins).
/** * Game 21 - an example in C++ language for Rosseta Code. * * This version is an example of MVP architecture. The user input, as well as * the AI opponent, is handled by separate passive subclasses of abstract class * named Controller. It can be noticed that the architecture support OCP, * for an example the AI module can be "easily" replaced by another AI etc. * * BTW, it would be better to place each class in its own file. But it would * be less convinient for Rosseta Code, where "one solution" mean "one file". */ #include <cstdlib> #include <ctime> #include <iostream> #include <iomanip> #include <limits> using namespace std; #define _(STR) STR class Model { protected: int oldTotal; int newTotal; int lastMove; public: static const int GOAL = 21; static const int NUMBER_OF_PLAYERS = 2; Model() { newTotal = 0; oldTotal = 0; lastMove = 0; } void update(int move) { oldTotal = newTotal; newTotal = oldTotal + move; lastMove = move; } int getOldTotal() { return oldTotal; } int getNewTotal() { return newTotal; } int getLastMove() { return lastMove; } bool isEndGame() { return newTotal == GOAL; } }; class View { public: void update(string comment, Model* model) { cout << setw(8) << comment << ": " << model->getNewTotal() << " = " << model->getOldTotal() << " + " << model->getLastMove() << endl << endl; } void newGame(string player) { cout << _("----NEW GAME----") << endl << endl << _("The running total is currently zero.") << endl << endl << _("The first move is ") << player << _(" move.") << endl << endl; } void endGame(string name) { cout << endl << _("The winner is ") << name << _(".") << endl << endl << endl; } }; class Controller { public: virtual string getName() = 0; virtual int getMove(Model* model) = 0; }; class AI : public Controller { public: string getName() { return _("AI"); } int getMove(Model* model) { int n = model->getNewTotal(); for (int i = 1; i <= 3; i++) if (n + i == Model::GOAL) return i; for (int i = 1; i <= 3; i++) if ((n + i - 1) % 4 == 0) return i; return 1 + rand() % 3; } }; class Human : public Controller { public: string getName() { return _("human"); } int getMove(Model* model) { int n = model->getNewTotal(); int value; while (true) { if (n == Model::GOAL - 1) cout << _("enter 1 to play (or enter 0 to exit game): "); else if (n == Model::GOAL - 2) cout << _("enter 1 or 2 to play (or enter 0 to exit game): "); else cout << _("enter 1 or 2 or 3 to play (or enter 0 to exit game): "); cin >> value; if (!cin.fail()) { if (value == 0) exit(0); else if (value >= 1 && value <= 3 && n + value <= Model::GOAL) { cout << endl; return value; } } cout << _("Your answer is not a valid choice.") << endl; cin.clear(); cin.ignore((streamsize)numeric_limits<int>::max, '\n'); } } }; class Presenter { protected: Model* model; View* view; Controller** controllers; public: Presenter(Model* model, View* view, Controller** controllers) { this->model = model; this->view = view; this->controllers = controllers; } void run() { int player = rand() % Model::NUMBER_OF_PLAYERS; view->newGame(controllers[player]->getName()); while (true) { Controller* controller = controllers[player]; model->update(controller->getMove(model)); view->update(controller->getName(), model); if (model->isEndGame()) { view->endGame(controllers[player]->getName()); break; } player = (player + 1) % Model::NUMBER_OF_PLAYERS; } } }; int main(int argc, char* argv) { srand(time(NULL)); while (true) { Model* model = new Model(); View* view = new View(); Controller* controllers[Model::NUMBER_OF_PLAYERS]; controllers[0] = new Human(); for (int i = 1; i < Model::NUMBER_OF_PLAYERS; i++) controllers[i] = new AI(); Presenter* presenter = new Presenter(model, view, controllers); presenter->run(); delete model; delete view; delete controllers[0]; delete controllers[1]; delete presenter; } return EXIT_SUCCESS; // dead code }
24 game
C++11
The 24 Game tests one's mental arithmetic. ;Task Write a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed. The 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. The goal is for the player to enter an expression that (numerically) evaluates to '''24'''. * Only the following operators/functions are allowed: multiplication, division, addition, subtraction * Division should use floating point or rational arithmetic, etc, to preserve remainders. * Brackets are allowed, if using an infix expression evaluator. * 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). * The order of the digits when given does not have to be preserved. ;Notes * The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. * The task is not for the program to generate the expression, or test whether an expression is even possible. ;Related tasks * [[24 game/Solve]] ;Reference * The 24 Game on h2g2.
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
4-rings or 4-squares puzzle
C++
Replace '''a, b, c, d, e, f,''' and '''g ''' with the decimal digits LOW ---> HIGH such that the sum of the letters inside of each of the four large squares add up to the same sum. +--------------+ +--------------+ | | | | | a | | e | | | | | | +---+------+---+ +---+---------+ | | | | | | | | | | b | | d | | f | | | | | | | | | | | | | | | | | | +----------+---+ +---+------+---+ | | c | | g | | | | | | | | | +--------------+ +-------------+ Show all output here. :* Show all solutions for each letter being unique with LOW=1 HIGH=7 :* Show all solutions for each letter being unique with LOW=3 HIGH=9 :* Show only the ''number'' of solutions when each letter can be non-unique LOW=0 HIGH=9 ;Related task: * [[Solve the no connection puzzle]]
//C++14/17 #include <algorithm>//std::for_each #include <iostream> //std::cout #include <numeric> //std::iota #include <vector> //std::vector, save solutions #include <list> //std::list, for fast erase using std::begin, std::end, std::for_each; //Generates all the valid solutions for the problem in the specified range [from, to) std::list<std::vector<int>> combinations(int from, int to) { if (from > to) return {}; //Return nothing if limits are invalid auto pool = std::vector<int>(to - from);//Here we'll save our values std::iota(begin(pool), end(pool), from);//Populates pool auto solutions = std::list<std::vector<int>>{}; //List for the solutions //Brute-force calculation of valid values... for (auto a : pool) for (auto b : pool) for (auto c : pool) for (auto d : pool) for (auto e : pool) for (auto f : pool) for (auto g : pool) if ( a == c + d && b + c == e + f && d + e == g ) solutions.push_back({a, b, c, d, e, f, g}); return solutions; } //Filter the list generated from "combinations" and return only lists with no repetitions std::list<std::vector<int>> filter_unique(int from, int to) { //Helper lambda to check repetitions: //If the count is > 1 for an element, there must be a repetition inside the range auto has_non_unique_values = [](const auto & range, auto target) { return std::count( begin(range), end(range), target) > 1; }; //Generates all the solutions... auto results = combinations(from, to); //For each solution, find duplicates inside for (auto subrange = cbegin(results); subrange != cend(results); ++subrange) { bool repetition = false; //If some element is repeated, repetition becomes true for (auto x : *subrange) repetition |= has_non_unique_values(*subrange, x); if (repetition) //If repetition is true, remove the current subrange from the list { results.erase(subrange); //Deletes subrange from solutions --subrange; //Rewind to the last subrange analysed } } return results; //Finally return remaining results } template <class Container> //Template for the sake of simplicity inline void print_range(const Container & c) { for (const auto & subrange : c) { std::cout << "["; for (auto elem : subrange) std::cout << elem << ' '; std::cout << "\b]\n"; } } int main() { std::cout << "Unique-numbers combinations in range 1-7:\n"; auto solution1 = filter_unique(1, 8); print_range(solution1); std::cout << "\nUnique-numbers combinations in range 3-9:\n"; auto solution2 = filter_unique(3,10); print_range(solution2); std::cout << "\nNumber of combinations in range 0-9: " << combinations(0, 10).size() << "." << std::endl; return 0; }
9 billion names of God the integer
C++
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a "name": :The integer 1 has 1 name "1". :The integer 2 has 2 names "1+1", and "2". :The integer 3 has 3 names "1+1+1", "2+1", and "3". :The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4". :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". ;Task Display the first 25 rows of a number triangle which begins: 1 1 1 1 1 1 1 2 1 1 1 2 2 1 1 1 3 3 2 1 1 Where 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. A function G(n) should return the sum of the n-th row. Demonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). Optionally note that the sum of the n-th row P(n) is the integer partition function. Demonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345). ;Extra credit If your environment is able, plot P(n) against n for n=1\ldots 999. ;Related tasks * [[Partition function P]]
// Calculate hypotenuse n of OTT assuming only nothingness, unity, and hyp[n-1] if n>1 // Nigel Galloway, May 6th., 2013 #include <gmpxx.h> int N{123456}; mpz_class hyp[N-3]; const mpz_class G(const int n,const int g){return g>n?0:(g==1 or n-g<2)?1:hyp[n-g-2];}; void G_hyp(const int n){for(int i=0;i<N-2*n-1;i++) n==1?hyp[n-1+i]=1+G(i+n+1,n+1):hyp[n-1+i]+=G(i+n+1,n+1);} }
A+B
C++
'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used. ;Task: Given two integers, '''A''' and '''B'''. Their sum needs to be calculated. ;Input data: Two integers are written in the input stream, separated by space(s): : (-1000 \le A,B \le +1000) ;Output data: The required output is one integer: the sum of '''A''' and '''B'''. ;Example: ::{|class="standard" ! input ! output |- | 2 2 | 4 |- | 3 2 | 5 |}
// Input file: input.txt // Output file: output.txt #include <fstream> using namespace std; int main() { ifstream in("input.txt"); ofstream out("output.txt"); int a, b; in >> a >> b; out << a + b << endl; return 0; }
ABC problem
C++11
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks: (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) ;Task: Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple: ::# Once a letter on a block is used that block cannot be used again ::# The function should be case-insensitive ::# Show the output on this page for the following 7 words in the following example ;Example: >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True
#include <iostream> #include <vector> #include <string> #include <set> #include <cctype> typedef std::pair<char,char> item_t; typedef std::vector<item_t> list_t; bool can_make_word(const std::string& w, const list_t& vals) { std::set<uint32_t> used; while (used.size() < w.size()) { const char c = toupper(w[used.size()]); uint32_t x = used.size(); for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) { if (used.find(i) == used.end()) { if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) { used.insert(i); break; } } } if (x == used.size()) break; } return used.size() == w.size(); } int main() { 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'} }; std::vector<std::string> words{"A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"}; for (const std::string& w : words) { std::cout << w << ": " << std::boolalpha << can_make_word(w,vals) << ".\n"; } }
ASCII art diagram converter
C++
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ Where (every column of the table is 1 bit): ID is 16 bits QR = Query (0) or Response (1) Opcode = Four bits defining kind of query: 0: a standard query (QUERY) 1: an inverse query (IQUERY) 2: a server status request (STATUS) 3-15: reserved for future use AA = Authoritative Answer bit TC = Truncation bit RD = Recursion Desired bit RA = Recursion Available bit Z = Reserved RCODE = Response code QC = Question Count ANC = Answer Count AUC = Authority Count ADC = Additional Count Write 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. If 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. Such "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. Bonus: perform a thoroughly validation of the input string.
#include <array> #include <bitset> #include <iostream> using namespace std; struct FieldDetails {string_view Name; int NumBits;}; // parses the ASCII diagram and returns the field name, bit sizes, and the // total byte size template <const char *T> consteval auto ParseDiagram() { // trim the ASCII diagram text constexpr string_view rawArt(T); constexpr auto firstBar = rawArt.find("|"); constexpr auto lastBar = rawArt.find_last_of("|"); constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar); static_assert(firstBar < lastBar, "ASCII Table has no fields"); // make an array for all of the fields constexpr auto numFields = count(rawArt.begin(), rawArt.end(), '|') - count(rawArt.begin(), rawArt.end(), '\n') / 2; array<FieldDetails, numFields> fields; // parse the diagram bool isValidDiagram = true; int startDiagramIndex = 0; int totalBits = 0; for(int i = 0; i < numFields; ) { auto beginningBar = art.find("|", startDiagramIndex); auto endingBar = art.find("|", beginningBar + 1); auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1); if(field.find("-") == field.npos) { int numBits = (field.size() + 1) / 3; auto nameStart = field.find_first_not_of(" "); auto nameEnd = field.find_last_not_of(" "); if (nameStart > nameEnd || nameStart == string_view::npos) { // the table cannot be parsed isValidDiagram = false; field = ""sv; } else { field = field.substr(nameStart, 1 + nameEnd - nameStart); } fields[i++] = FieldDetails {field, numBits}; totalBits += numBits; } startDiagramIndex = endingBar; } int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0; return make_pair(fields, numRawBytes); } // encode the values of the fields into a raw data array template <const char *T> auto Encode(auto inputValues) { constexpr auto parsedDiagram = ParseDiagram<T>(); static_assert(parsedDiagram.second > 0, "Invalid ASCII talble"); array<unsigned char, parsedDiagram.second> data; int startBit = 0; int i = 0; for(auto value : inputValues) { const auto &field = parsedDiagram.first[i++]; int remainingValueBits = field.NumBits; while(remainingValueBits > 0) { // pack the bits from an input field into the data array auto [fieldStartByte, fieldStartBit] = div(startBit, 8); int unusedBits = 8 - fieldStartBit; int numBitsToEncode = min({unusedBits, 8, field.NumBits}); int divisor = 1 << (remainingValueBits - numBitsToEncode); unsigned char bitsToEncode = value / divisor; data[fieldStartByte] <<= numBitsToEncode; data[fieldStartByte] |= bitsToEncode; value %= divisor; startBit += numBitsToEncode; remainingValueBits -= numBitsToEncode; } } return data; } // decode the raw data into the format of the ASCII diagram template <const char *T> void Decode(auto data) { cout << "Name Bit Pattern\n"; cout << "======= ================\n"; constexpr auto parsedDiagram = ParseDiagram<T>(); static_assert(parsedDiagram.second > 0, "Invalid ASCII talble"); int startBit = 0; for(const auto& field : parsedDiagram.first) { // unpack the bits from the data into a single field auto [fieldStartByte, fieldStartBit] = div(startBit, 8); unsigned char firstByte = data[fieldStartByte]; firstByte <<= fieldStartBit; firstByte >>= fieldStartBit; int64_t value = firstByte; auto endBit = startBit + field.NumBits; auto [fieldEndByte, fieldEndBit] = div(endBit, 8); fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1)); for(int index = fieldStartByte + 1; index <= fieldEndByte; index++) { value <<= 8; value += data[index]; } value >>= fieldEndBit; startBit = endBit; cout << field.Name << string_view(" ", (7 - field.Name.size())) << " " << string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) << "\n"; } } int main(void) { static constexpr char art[] = R"( +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)"; // using the table above, encode the data below auto rawData = Encode<art> (initializer_list<int64_t> { 30791, 0, 15, 0, 1, 1, 1, 3, 15, 21654, 57646, 7153, 27044 }); cout << "Raw encoded data in hex:\n"; for (auto v : rawData) printf("%.2X", v); cout << "\n\n"; cout << "Decoded raw data:\n"; Decode<art>(rawData); }
AVL tree
C++ from D
{{wikipedia|AVL tree}} In 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. AVL 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. ;Task: Implement an AVL tree in the language of choice, and provide at least basic operations. ;Related task [[Red_black_tree_sort]]
#include <algorithm> #include <iostream> /* AVL node */ template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; delete right; } }; /* AVL tree */ template <class T> class AVLtree { public: AVLtree(void); ~AVLtree(void); bool insert(T key); void deleteKey(const T key); void printBalance(); private: AVLnode<T> *root; AVLnode<T>* rotateLeft ( AVLnode<T> *a ); AVLnode<T>* rotateRight ( AVLnode<T> *a ); AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n ); AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n ); void rebalance ( AVLnode<T> *n ); int height ( AVLnode<T> *n ); void setBalance ( AVLnode<T> *n ); void printBalance ( AVLnode<T> *n ); }; /* AVL class definition */ template <class T> void AVLtree<T>::rebalance(AVLnode<T> *n) { setBalance(n); if (n->balance == -2) { if (height(n->left->left) >= height(n->left->right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n->balance == 2) { if (height(n->right->right) >= height(n->right->left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); } if (n->parent != NULL) { rebalance(n->parent); } else { root = n; } } template <class T> AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) { AVLnode<T> *b = a->right; b->parent = a->parent; a->right = b->left; if (a->right != NULL) a->right->parent = a; b->left = a; a->parent = b; if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } } setBalance(a); setBalance(b); return b; } template <class T> AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) { AVLnode<T> *b = a->left; b->parent = a->parent; a->left = b->right; if (a->left != NULL) a->left->parent = a; b->right = a; a->parent = b; if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } } setBalance(a); setBalance(b); return b; } template <class T> AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) { n->left = rotateLeft(n->left); return rotateRight(n); } template <class T> AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) { n->right = rotateRight(n->right); return rotateLeft(n); } template <class T> int AVLtree<T>::height(AVLnode<T> *n) { if (n == NULL) return -1; return 1 + std::max(height(n->left), height(n->right)); } template <class T> void AVLtree<T>::setBalance(AVLnode<T> *n) { n->balance = height(n->right) - height(n->left); } template <class T> void AVLtree<T>::printBalance(AVLnode<T> *n) { if (n != NULL) { printBalance(n->left); std::cout << n->balance << " "; printBalance(n->right); } } template <class T> AVLtree<T>::AVLtree(void) : root(NULL) {} template <class T> AVLtree<T>::~AVLtree(void) { delete root; } template <class T> bool AVLtree<T>::insert(T key) { if (root == NULL) { root = new AVLnode<T>(key, NULL); } else { AVLnode<T> *n = root, *parent; while (true) { if (n->key == key) return false; parent = n; bool goLeft = n->key > key; n = goLeft ? n->left : n->right; if (n == NULL) { if (goLeft) { parent->left = new AVLnode<T>(key, parent); } else { parent->right = new AVLnode<T>(key, parent); } rebalance(parent); break; } } } return true; } template <class T> void AVLtree<T>::deleteKey(const T delKey) { if (root == NULL) return; AVLnode<T> *n = root, *parent = root, *delNode = NULL, *child = root; while (child != NULL) { parent = n; n = child; child = delKey >= n->key ? n->right : n->left; if (delKey == n->key) delNode = n; } if (delNode != NULL) { delNode->key = n->key; child = n->left != NULL ? n->left : n->right; if (root->key == delKey) { root = child; } else { if (parent->left == n) { parent->left = child; } else { parent->right = child; } rebalance(parent); } } } template <class T> void AVLtree<T>::printBalance() { printBalance(root); std::cout << std::endl; } int main(void) { AVLtree<int> t; std::cout << "Inserting integer values 1 to 10" << std::endl; for (int i = 1; i <= 10; ++i) t.insert(i); std::cout << "Printing balance: "; t.printBalance(); }
Abbreviations, automatic
C++ from C#
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an easy way to add flexibility when specifying or using commands, sub-commands, options, etc. It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if the minimum abbreviation length of that list could be automatically (programmatically) determined. For 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). Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag E_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune Ehud Segno Maksegno Erob Hamus Arbe Kedame Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat domingu llunes martes miercoles xueves vienres sabadu Bazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn nedelia ponedelnik vtornik sriada chetvartak petak sabota sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte Dzeenkk-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 dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn Dimanch Lendi Madi Mekredi Jedi Vandredi Samdi nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota nede^le ponde^li utery str^eda c^tvrtek patek sobota Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee s0ndag mandag tirsdag onsdag torsdag fredag l0rdag zondag maandag dinsdag woensdag donderdag vrijdag zaterdag Diman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato pUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata sunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai dimanche lundi mardi mercredi jeudi vendredi samedi Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon Domingo Segunda_feira Martes Mercores Joves Venres Sabado k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar popule po`akahi po`alua po`akolu po`aha po`alima po`aono Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar vasarnap hetfo kedd szerda csutortok pentek szombat Sunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur sundio lundio mardio merkurdio jovdio venerdio saturdio Minggu Senin Selasa Rabu Kamis Jumat Sabtu Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato De_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn domenica lunedi martedi mercoledi giovedi venerdi sabato Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi xing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam Jabot Manre Juje Wonje Taije Balaire Jarere geminrongo minomishi martes mierkoles misheushi bernashi mishabaro Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu sphndag mandag tirsdag onsdag torsdag fredag lphrdag lo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte djadomingo djaluna djamars djarason djaweps djabierna djasabra Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota Domingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado Domingo Lunes martes Miercoles Jueves Viernes Sabado Duminica Luni Mart'i Miercuri Joi Vineri Sambata voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota Sunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne nedjelja ponedjeljak utorak sreda cxetvrtak petak subota Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha- nedel^a pondelok utorok streda s^tvrtok piatok sobota Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota domingo lunes martes miercoles jueves viernes sabado sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi sondag mandag tisdag onsdag torsdag fredag lordag Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado Le-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso Pazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi nedilya ponedilok vivtorok sereda chetver pyatnytsya subota Chu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo zuntik montik dinstik mitvokh donershtik fraytik shabes iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni Bazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae Sun Moon Mars Mercury Jove Venus Saturn zondag maandag dinsdag woensdag donderdag vrijdag zaterdag KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend Domingo Luns Terza_feira Corta_feira Xoves Venres Sabado Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum xing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu djadomingu djaluna djamars djarason djaweps djabierne djasabra Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau ''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.'' To 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). Notes concerning the above list of words ::* each line has a list of days-of-the-week for a language, separated by at least one blank ::* the words on each line happen to be in order, from Sunday --> Saturday ::* most lines have words in mixed case and some have all manner of accented words and other characters ::* some words were translated to the nearest character that was available to ''code page'' '''437''' ::* the characters in the words are not restricted except that they may not have imbedded blanks ::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word ;Task: ::* The list of words (days of the week) needn't be verified/validated. ::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique. ::* A blank line (or a null line) should return a null string. ::* Process and show the output for at least the first '''five''' lines of the file. ::* Show all output here.
#include <iomanip> #include <iostream> #include <fstream> #include <map> #include <sstream> #include <string> #include <vector> std::vector<std::string> split(const std::string& str, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(str); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } int main() { using namespace std; string line; int i = 0; ifstream in("days_of_week.txt"); if (in.is_open()) { while (getline(in, line)) { i++; if (line.empty()) { continue; } auto days = split(line, ' '); if (days.size() != 7) { throw std::runtime_error("There aren't 7 days in line " + i); } map<string, int> temp; for (auto& day : days) { if (temp.find(day) != temp.end()) { cerr << " ∞ " << line << '\n'; continue; } temp[day] = 1; } int len = 1; while (true) { temp.clear(); for (auto& day : days) { string key = day.substr(0, len); if (temp.find(key) != temp.end()) { break; } temp[key] = 1; } if (temp.size() == 7) { cout << setw(2) << len << " " << line << '\n'; break; } len++; } } } return 0; }
Abbreviations, easy
C++
This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]]. For this task, the following ''command table'' will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up Notes concerning the above ''command table'': ::* it can be thought of as one long literal string (with blanks at end-of-lines) ::* it may have superfluous blanks ::* it may be in any case (lower/upper/mixed) ::* the order of the words in the ''command table'' must be preserved as shown ::* the user input(s) may be in any case (upper/lower/mixed) ::* commands will be restricted to the Latin alphabet (A --> Z, a --> z) ::* A valid abbreviation is a word that has: :::* at least the minimum length of the number of capital letters of the word in the ''command table'' :::* compares equal (regardless of case) to the leading characters of the word in the ''command table'' :::* a length not longer than the word in the ''command table'' ::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer''' ::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer''' ::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters ::::* Any word longer than five characters can't be an abbreviation for '''ALTer''' ::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay''' ::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted ;Task: ::* The command table needn't be verified/validated. ::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table''). ::* If the word is valid, then return the full uppercase version of that "word". ::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters). ::* A blank input (or a null input) should return a null string. ::* Show all output here. ;An example test case to be used for this task: For a user string of: riG rePEAT copies put mo rest types fup. 6 poweRin the computer program should return the string: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; // cmd is assumed to be all uppercase command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} // str is assumed to be all uppercase bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } // convert string to uppercase void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { // count leading uppercase characters size_t len = get_min_length(word); // then convert to uppercase uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Abbreviations, simple
C++
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an easy way to add flexibility when specifying or using commands, sub-commands, options, etc. For this task, the following ''command table'' will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 Notes concerning the above ''command table'': ::* it can be thought of as one long literal string (with blanks at end-of-lines) ::* it may have superfluous blanks ::* it may be in any case (lower/upper/mixed) ::* the order of the words in the ''command table'' must be preserved as shown ::* the user input(s) may be in any case (upper/lower/mixed) ::* commands will be restricted to the Latin alphabet (A --> Z, a --> z) ::* a command is followed by an optional number, which indicates the minimum abbreviation ::* A valid abbreviation is a word that has: :::* at least the minimum length of the word's minimum number in the ''command table'' :::* compares equal (regardless of case) to the leading characters of the word in the ''command table'' :::* a length not longer than the word in the ''command table'' ::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3''' ::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3''' ::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters ::::* Any word longer than five characters can't be an abbreviation for '''ALTER''' ::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1''' ::* if there isn't a number after the command, then there isn't an abbreviation permitted ;Task: ::* The command table needn't be verified/validated. ::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table''). ::* If the word is valid, then return the full uppercase version of that "word". ::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters). ::* A blank input (or a null input) should return a null string. ::* Show all output here. ;An example test case to be used for this task: For a user string of: riG rePEAT copies put mo rest types fup. 6 poweRin the computer program should return the string: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; // cmd is assumed to be all uppercase command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} // str is assumed to be all uppercase bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } // convert string to uppercase void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; // if there's an integer following this word, it specifies the minimum // length for the command, otherwise the minimum length is the length // of the command string int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Abelian sandpile model/Identity
C++
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addition on sandpiles is done by adding numbers in corresponding grid areas, so for the above: 1 2 0 2 1 3 3 3 3 s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2 0 1 3 0 1 0 0 2 3 If the addition would result in more than 3 "grains of sand" in any area then those areas cause the whole sandpile to become "unstable" and the sandpile areas are "toppled" in an "avalanche" until the "stable" result is obtained. Any unstable area (with a number >= 4), is "toppled" by loosing one grain of sand to each of its four horizontal or vertical neighbours. Grains are lost at the edge of the grid, but otherwise increase the number in neighbouring cells by one, whilst decreasing the count in the toppled cell by four in each toppling. A toppling may give an adjacent area more than four grains of sand leading to a chain of topplings called an "avalanche". E.g. 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3 The final result is the stable sandpile on the right. '''Note:''' The order in which cells are toppled does not affect the final result. ;Task: * Create a class or datastructure and functions to represent and operate on sandpiles. * Confirm the result of the avalanche of topplings shown above * Confirm that s1 + s2 == s2 + s1 # Show the stable results * If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile: 2 1 2 1 0 1 2 1 2 * Show that s3 + s3_id == s3 * Show that s3_id + s3_id == s3_id Show confirming output here, with your examples. ;References: * https://www.youtube.com/watch?v=1MtEUErz7Gg * https://en.wikipedia.org/wiki/Abelian_sandpile_model
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&); public: abelian_sandpile(); explicit abelian_sandpile(std::initializer_list<int> init); void stabilize(); bool is_stable() const; void topple(); abelian_sandpile& operator+=(const abelian_sandpile&); bool operator==(const abelian_sandpile&); private: int& cell_value(size_t row, size_t column) { return cells_[cell_index(row, column)]; } static size_t cell_index(size_t row, size_t column) { return row * sp_columns + column; } static size_t row_index(size_t cell_index) { return cell_index/sp_columns; } static size_t column_index(size_t cell_index) { return cell_index % sp_columns; } std::array<int, sp_cells> cells_; }; abelian_sandpile::abelian_sandpile() { cells_.fill(0); } abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) { assert(init.size() == sp_cells); std::copy(init.begin(), init.end(), cells_.begin()); } abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) { for (size_t i = 0; i < sp_cells; ++i) cells_[i] += other.cells_[i]; stabilize(); return *this; } bool abelian_sandpile::operator==(const abelian_sandpile& other) { return cells_ == other.cells_; } bool abelian_sandpile::is_stable() const { return std::none_of(cells_.begin(), cells_.end(), [](int a) { return a >= sp_limit; }); } void abelian_sandpile::topple() { for (size_t i = 0; i < sp_cells; ++i) { if (cells_[i] >= sp_limit) { cells_[i] -= sp_limit; size_t row = row_index(i); size_t column = column_index(i); if (row > 0) ++cell_value(row - 1, column); if (row + 1 < sp_rows) ++cell_value(row + 1, column); if (column > 0) ++cell_value(row, column - 1); if (column + 1 < sp_columns) ++cell_value(row, column + 1); break; } } } void abelian_sandpile::stabilize() { while (!is_stable()) topple(); } abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) { abelian_sandpile c(a); c += b; return c; } std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) { for (size_t i = 0; i < sp_cells; ++i) { if (i > 0) out << (as.column_index(i) == 0 ? '\n' : ' '); out << as.cells_[i]; } return out << '\n'; } int main() { std::cout << std::boolalpha; std::cout << "Avalanche:\n"; abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3}; while (!sp.is_stable()) { std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; sp.topple(); } std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; std::cout << "Commutativity:\n"; abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3}; abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0}; abelian_sandpile sum1(s1 + s2); abelian_sandpile sum2(s2 + s1); std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n"; std::cout << "s1 + s2 = \n" << sum1; std::cout << "\ns2 + s1 = \n" << sum2; std::cout << '\n'; std::cout << "Identity:\n"; abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3}; abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2}; abelian_sandpile sum3(s3 + s3_id); abelian_sandpile sum4(s3_id + s3_id); std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n'; std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n"; std::cout << "s3 + s3_id = \n" << sum3; std::cout << "\ns3_id + s3_id = \n" << sum4; return 0; }
Abundant odd numbers
C++ from Go
An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''', or, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''. ;E.G.: '''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n'''). Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. To make things more interesting, this task is specifically about finding ''odd abundant numbers''. ;Task *Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum. *Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum. *Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum. ;References: :* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n) :* 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)
#include <algorithm> #include <iostream> #include <numeric> #include <sstream> #include <vector> std::vector<int> divisors(int n) { std::vector<int> divs{ 1 }; std::vector<int> divs2; for (int i = 2; i*i <= n; i++) { if (n%i == 0) { int j = n / i; divs.push_back(i); if (i != j) { divs2.push_back(j); } } } std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs)); return divs; } int sum(const std::vector<int>& divs) { return std::accumulate(divs.cbegin(), divs.cend(), 0); } std::string sumStr(const std::vector<int>& divs) { auto it = divs.cbegin(); auto end = divs.cend(); std::stringstream ss; if (it != end) { ss << *it; it = std::next(it); } while (it != end) { ss << " + " << *it; it = std::next(it); } return ss.str(); } int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) { int count = countFrom; int n = searchFrom; for (; count < countTo; n += 2) { auto divs = divisors(n); int tot = sum(divs); if (tot > n) { count++; if (printOne && count < countTo) { continue; } auto s = sumStr(divs); if (printOne) { printf("%d < %s = %d\n", n, s.c_str(), tot); } else { printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot); } } } return n; } int main() { using namespace std; const int max = 25; cout << "The first " << max << " abundant odd numbers are:\n"; int n = abundantOdd(1, 0, 25, false); cout << "\nThe one thousandth abundant odd number is:\n"; abundantOdd(n, 25, 1000, true); cout << "\nThe first abundant odd number above one billion is:\n"; abundantOdd(1e9 + 1, 0, 1, true); return 0; }
Accumulator factory
C++
{{requires|Mutable State}} A 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). ;Rules: The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text''). :Before you submit an example, make sure the function :# 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 :# 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)'' :# 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.)'' :# 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.)'' :# 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.)'' : E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'': :: x = foo(1); x(5); foo(3); print x(2.3); : 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.)'' ;Task: Create a function that implements the described rules. It 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. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#include <iostream> class Acc { public: Acc(int init) : _type(intType) , _intVal(init) {} Acc(float init) : _type(floatType) , _floatVal(init) {} int operator()(int x) { if( _type == intType ) { _intVal += x; return _intVal; } else { _floatVal += x; return static_cast<int>(_floatVal); } } float operator()(float x) { if( _type == intType ) { _floatVal = _intVal + x; _type = floatType; return _floatVal; } else { _floatVal += x; return _floatVal; } } private: enum {floatType, intType} _type; float _floatVal; int _intVal; }; int main() { Acc a(1); a(5); Acc(3); std::cout << a(2.3f); return 0; }
Accumulator factory
C++11
{{requires|Mutable State}} A 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). ;Rules: The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text''). :Before you submit an example, make sure the function :# 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 :# 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)'' :# 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.)'' :# 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.)'' :# 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.)'' : E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'': :: x = foo(1); x(5); foo(3); print x(2.3); : 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.)'' ;Task: Create a function that implements the described rules. It 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. Where it is not possible to hold exactly to the constraints above, describe the deviations.
// still inside struct Accumulator_ // various operator() implementations provide a de facto multimethod Accumulator_& operator()(int more) { if (auto i = CoerceInt(*val_)) Set(+i + more); else if (auto d = CoerceDouble(*val_)) Set(+d + more); else THROW("Accumulate(int) failed"); return *this; } Accumulator_& operator()(double more) { if (auto d = CoerceDouble(*val_)) Set(+d + more); else THROW("Accumulate(double) failed"); return *this; } Accumulator_& operator()(const String_& more) { if (auto s = CoerceString(*val_)) Set(+s + more); else THROW("Accumulate(string) failed"); return *this; } };
Aliquot sequence classifications
C++
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the [[Proper divisors]] of the previous term. :* If the terms eventually reach 0 then the series for K is said to '''terminate'''. :There are several classifications for non termination: :* 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'''. :* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''. :* 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'''. :Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... :* 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'''. :* 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'''. :And finally: :* 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. ;Task: # Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. # Use it to display the classification and sequences of the numbers one to ten inclusive. # Use it to show the classification and sequences of the following integers, in order: :: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. ;Related tasks: * [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence). * [[Proper divisors]] * [[Amicable pairs]]
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; // See https://en.wikipedia.org/wiki/Divisor_function integer divisor_sum(integer n) { integer total = 1, power = 2; // Deal with powers of 2 first for (; n % 2 == 0; power *= 2, n /= 2) total += power; // Odd prime factors up to the square root for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } // If n > 1 then it's prime if (n > 1) total *= n + 1; return total; } // See https://en.wikipedia.org/wiki/Aliquot_sequence void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
Amb
C++
Define and give an example of the Amb operator. The 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"). The 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. Problems 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. Essentially 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. For 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. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The 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. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The 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: #"the" "that" "a" #"frog" "elephant" "thing" #"walked" "treaded" "grows" #"slowly" "quickly" The 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. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The 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.
#include <iostream> #include <string_view> #include <boost/hana.hpp> #include <boost/hana/experimental/printable.hpp> using namespace std; namespace hana = boost::hana; // Define the Amb function. The first parameter is the constraint to be // enforced followed by the potential values. constexpr auto Amb(auto constraint, auto&& ...params) { // create the set of all possible solutions auto possibleSolutions = hana::cartesian_product(hana::tuple(params...)); // find one that matches the constraint auto foldOperation = [constraint](auto a, auto b) { bool meetsConstraint = constraint(a); return meetsConstraint ? a : b; }; return hana::fold_right(possibleSolutions, foldOperation); } void AlgebraExample() { // use a tuple to hold the possible values of each variable constexpr hana::tuple x{1, 2, 3}; constexpr hana::tuple y{7, 6, 4, 5}; // the constraint enforcing x * y == 8 constexpr auto constraint = [](auto t) { return t[hana::size_c<0>] * t[hana::size_c<1>] == 8; }; // find the solution using the Amb function auto result = Amb(constraint, x, y); cout << "\nx = " << hana::experimental::print(x); cout << "\ny = " << hana::experimental::print(y); cout << "\nx * y == 8: " << hana::experimental::print(result); } void StringExample() { // the word lists to choose from constexpr hana::tuple words1 {"the"sv, "that"sv, "a"sv}; constexpr hana::tuple words2 {"frog"sv, "elephant"sv, "thing"sv}; constexpr hana::tuple words3 {"walked"sv, "treaded"sv, "grows"sv}; constexpr hana::tuple words4 {"slowly"sv, "quickly"sv}; // the constraint that the first letter of a word is the same as the last // letter of the previous word constexpr auto constraint = [](const auto t) { auto adjacent = hana::zip(hana::drop_back(t), hana::drop_front(t)); return hana::all_of(adjacent, [](auto t) { return t[hana::size_c<0>].back() == t[hana::size_c<1>].front(); }); }; // find the solution using the Amb function auto wordResult = Amb(constraint, words1, words2, words3, words4); cout << "\n\nWords 1: " << hana::experimental::print(words1); cout << "\nWords 2: " << hana::experimental::print(words2); cout << "\nWords 3: " << hana::experimental::print(words3); cout << "\nWords 4: " << hana::experimental::print(words4); cout << "\nSolution: " << hana::experimental::print(wordResult) << "\n"; } int main() { AlgebraExample(); StringExample(); }
Anagrams/Deranged anagrams
C++
Two or more words are said to be anagrams if they have the same characters, but in a different order. By 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. ;Task Use the word list at unixdict to find and display the longest deranged anagram. ;Related * [[Permutations/Derangements]] * Best shuffle {{Related tasks/Word plays}}
#include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <map> #include <numeric> #include <set> #include <string> bool is_deranged(const std::string& left, const std::string& right) { return (left.size() == right.size()) && (std::inner_product(left.begin(), left.end(), right.begin(), 0, std::plus<int>(), std::equal_to<char>()) == 0); } int main() { std::ifstream input("unixdict.txt"); if (!input) { std::cerr << "can't open input file\n"; return EXIT_FAILURE; } typedef std::set<std::string> WordList; typedef std::map<std::string, WordList> AnagraMap; AnagraMap anagrams; std::pair<std::string, std::string> result; size_t longest = 0; for (std::string value; input >> value; /**/) { std::string key(value); std::sort(key.begin(), key.end()); if (longest < value.length()) { // is it a long candidate? if (0 < anagrams.count(key)) { // is it an anagram? for (const auto& prior : anagrams[key]) { if (is_deranged(prior, value)) { // are they deranged? result = std::make_pair(prior, value); longest = value.length(); } } } } anagrams[key].insert(value); } std::cout << result.first << ' ' << result.second << '\n'; return EXIT_SUCCESS; }
Angle difference between two bearings
C++
Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings] ;Task: Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. Input bearings are expressed in the range '''-180''' to '''+180''' degrees. The result is also expressed in the range '''-180''' to '''+180''' degrees. Compute the angle for the following pairs: * 20 degrees ('''b1''') and 45 degrees ('''b2''') * -45 and 45 * -85 and 90 * -95 and 90 * -45 and 125 * -45 and 145 * 29.4803 and -88.6381 * -78.3251 and -159.036 ;Optional extra: Allow the input bearings to be any (finite) value. ;Test cases: * -70099.74233810938 and 29840.67437876723 * -165313.6666297357 and 33693.9894517456 * 1174.8380510598456 and -154146.66490124757 * 60175.77306795546 and 42213.07192354373
#include <cmath> #include <iostream> using namespace std; double getDifference(double b1, double b2) { double r = fmod(b2 - b1, 360.0); if (r < -180.0) r += 360.0; if (r >= 180.0) r -= 360.0; return r; } int main() { cout << "Input in -180 to +180 range" << endl; cout << getDifference(20.0, 45.0) << endl; cout << getDifference(-45.0, 45.0) << endl; cout << getDifference(-85.0, 90.0) << endl; cout << getDifference(-95.0, 90.0) << endl; cout << getDifference(-45.0, 125.0) << endl; cout << getDifference(-45.0, 145.0) << endl; cout << getDifference(-45.0, 125.0) << endl; cout << getDifference(-45.0, 145.0) << endl; cout << getDifference(29.4803, -88.6381) << endl; cout << getDifference(-78.3251, -159.036) << endl; cout << "Input in wider range" << endl; cout << getDifference(-70099.74233810938, 29840.67437876723) << endl; cout << getDifference(-165313.6666297357, 33693.9894517456) << endl; cout << getDifference(1174.8380510598456, -154146.66490124757) << endl; cout << getDifference(60175.77306795546, 42213.07192354373) << endl; return 0; }
Anti-primes
C++ from C
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. ;Task: Generate and show here, the first twenty anti-primes. ;Related tasks: :* [[Factors of an integer]] :* [[Sieve of Eratosthenes]]
#include <iostream> int countDivisors(int n) { if (n < 2) return 1; int count = 2; // 1 and n for (int i = 2; i <= n/2; ++i) { if (n%i == 0) ++count; } return count; } int main() { int maxDiv = 0, count = 0; std::cout << "The first 20 anti-primes are:" << std::endl; for (int n = 1; count < 20; ++n) { int d = countDivisors(n); if (d > maxDiv) { std::cout << n << " "; maxDiv = d; count++; } } std::cout << std::endl; return 0; }
Apply a digital filter (direct form II transposed)
C++
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] ;Task: Filter 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] The 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] ;See also: [Wikipedia on Butterworth filters]
#include <vector> #include <iostream> using namespace std; void Filter(const vector<float> &b, const vector<float> &a, const vector<float> &in, vector<float> &out) { out.resize(0); out.resize(in.size()); for(int i=0; i < in.size(); i++) { float tmp = 0.; int j=0; out[i] = 0.f; for(j=0; j < b.size(); j++) { if(i - j < 0) continue; tmp += b[j] * in[i-j]; } for(j=1; j < a.size(); j++) { if(i - j < 0) continue; tmp -= a[j]*out[i-j]; } tmp /= a[0]; out[i] = tmp; } } int main() { vector<float> sig = {-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}; //Constants for a Butterworth filter (order 3, low pass) vector<float> a = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}; vector<float> b = {0.16666667, 0.5, 0.5, 0.16666667}; vector<float> result; Filter(b, a, sig, result); for(size_t i=0;i<result.size();i++) cout << result[i] << ","; cout << endl; return 0; }
Approximate equality
C++ from C
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. ;Task: Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, '''100000000000000.01''' may be approximately equal to '''100000000000000.011''', even though '''100.01''' is not approximately equal to '''100.011'''. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values: :# 100000000000000.01, 100000000000000.011 (note: should return ''true'') :# 100.01, 100.011 (note: should return ''false'') :# 10000000000000.001 / 10000.0, 1000000000.0000001000 :# 0.001, 0.0010000001 :# 0.000000000000000000000101, 0.0 :# sqrt(2) * sqrt(2), 2.0 :# -sqrt(2) * sqrt(2), -2.0 :# 3.14159265358979323846, 3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution. __TOC__
#include <iomanip> #include <iostream> #include <cmath> bool approxEquals(double a, double b, double e) { return fabs(a - b) < e; } void test(double a, double b) { constexpr double epsilon = 1e-18; std::cout << std::setprecision(21) << a; std::cout << ", "; std::cout << std::setprecision(21) << b; std::cout << " => "; std::cout << approxEquals(a, b, epsilon) << '\n'; } int main() { test(100000000000000.01, 100000000000000.011); test(100.01, 100.011); test(10000000000000.001 / 10000.0, 1000000000.0000001000); test(0.001, 0.0010000001); test(0.000000000000000000000101, 0.0); test(sqrt(2.0) * sqrt(2.0), 2.0); test(-sqrt(2.0) * sqrt(2.0), -2.0); test(3.14159265358979323846, 3.14159265358979324); return 0; }
Archimedean spiral
C++
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: :\, r=a+b\theta with real numbers ''a'' and ''b''. ;Task Draw an Archimedean spiral.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class spiral { public: spiral() { bmp.create( BMP_SIZE, BMP_SIZE ); } void draw( int c, int s ) { double a = .2, b = .3, r, x, y; int w = BMP_SIZE >> 1; HDC dc = bmp.getDC(); for( double d = 0; d < c * 6.28318530718; d += .002 ) { r = a + b * d; x = r * cos( d ); y = r * sin( d ); SetPixel( dc, ( int )( s * x + w ), ( int )( s * y + w ), 255 ); } // saves the bitmap bmp.saveBitmap( "./spiral.bmp" ); } private: myBitmap bmp; }; int main(int argc, char* argv[]) { spiral s; s.draw( 16, 8 ); return 0; }
Arena storage pool
C++
Dynamically allocated objects take their memory from a [[heap]]. The memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]]. Often a call to allocator is denoted as P := new T where '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object. The storage pool chosen by the allocator can be determined by either: * the object type '''T''' * the type of pointer '''P''' In the former case objects can be allocated only in one storage pool. In the latter case objects of the type can be allocated in any storage pool or on the [[stack]]. ;Task: The task is to show how allocators and user-defined storage pools are supported by the language. In particular: # define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups. # allocate some objects (e.g., integers) in the pool. Explain what controls the storage pool choice in the language.
#include <cstdlib> #include <cassert> #include <new> // This class basically provides a global stack of pools; it is not thread-safe, and pools must be destructed in reverse order of construction // (you definitely want something better in production use :-)) class Pool { public: Pool(std::size_type sz); ~Pool(); static Pool& current() { return *cur; } void* allocate(std::size_type sz, std::size_t alignment); private: char* memory; // char* instead of void* enables pointer arithmetic char* free; char* end; Pool* prev; static Pool* cur; // prohibit copying Pool(Pool const&); // not implemented Pool& operator=(Pool const&); // not implemented }; Pool* pool::cur = 0; Pool::Pool(std::size_type size): memory(static_cast<char*>(::operator new(size))), free(memory), end(memory + size)) { prev = cur; cur = this; } Pool::~Pool() { ::operator delete(memory); cur = prev; } void* Pool::allocate(std::size_t size, std::size_t alignment) { char* start = free; // align the pointer std::size_t extra = (start - memory) % aligment; if (extra != 0) { extra = alignment - extra; } // test if we can still allocate that much memory if (end - free < size + extra) throw std::bad_alloc(); // the free memory now starts after the newly allocated object free = start + size + extra; return start; } // this is just a simple C-like struct, except that it uses a specific allocation/deallocation function. struct X { int member; void* operator new(std::size_t); void operator delete(void*) {} // don't deallocate memory for single objects }; void* X::operator new(std::size_t size) { // unfortunately C++ doesn't offer a portable way to find out alignment // however, using the size as alignment is always safe (although usually wasteful) return Pool::current().allocate(size, size); } // Example program int main() { Pool my_pool(3*sizeof(X)); X* p1 = new X; // uses the allocator function defined above X* p2 = new X; X* p3 = new X; delete p3; // doesn't really deallocate the memory because operator delete has an empty body try { X* p4 = new X; // should fail assert(false); } catch(...) { } X* p5 = new X[10]; // uses global array allocation routine because we didn't provide operator new[] and operator delete[] delete[] p5; // global array deallocation Pool* my_second_pool(1000); // a large pool X* p6 = new X; // allocate a new object from that pool X* p7 = new X; delete my_second_pool // also deallocates the memory for p6 and p7 } // Here my_pool goes out of scope, deallocating the memory for p1, p2 and p3
Arithmetic-geometric mean
C++
{{wikipedia|Arithmetic-geometric mean}} ;Task: Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence: : a_0 = a; \qquad g_0 = g : a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}. Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: :\mathrm{agm}(1,1/\sqrt{2}) ;Also see: * mathworld.wolfram.com/Arithmetic-Geometric Mean
#include<bits/stdc++.h> using namespace std; #define _cin ios_base::sync_with_stdio(0); cin.tie(0); #define rep(a, b) for(ll i =a;i<=b;++i) double agm(double a, double g) //ARITHMETIC GEOMETRIC MEAN { double epsilon = 1.0E-16,a1,g1; if(a*g<0.0) { cout<<"Couldn't find arithmetic-geometric mean of these numbers\n"; exit(1); } while(fabs(a-g)>epsilon) { a1 = (a+g)/2.0; g1 = sqrt(a*g); a = a1; g = g1; } return a; } int main() { _cin; //fast input-output double x, y; cout<<"Enter X and Y: "; //Enter two numbers cin>>x>>y; cout<<"\nThe Arithmetic-Geometric Mean of "<<x<<" and "<<y<<" is "<<agm(x, y); return 0; }
Arithmetic numbers
C++
Definition A positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer. Clearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5. ;Example 30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. ;Task Calculate and show here: 1. The first 100 arithmetic numbers. 2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000. 3. How many of the first '''x''' arithmetic numbers are composite. Note that, technically, the arithmetic number '''1''' is neither prime nor composite. ;Stretch Carry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000. ;References * Wikipedia: Arithmetic number * OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += i; divisor_count += 1; if (i != j) { divisor_sum += j; divisor_count += 1; } } } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; n++) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, divisor_count, divisor_sum); unsigned int mean = divisor_sum / divisor_count; if (mean * divisor_count != divisor_sum) continue; arithmetic_count++; if (divisor_count > 2) composite_count++; if (arithmetic_count <= 100) { // would prefer to use <stream> and <format> in C++20 std::printf("%3u ", n); if (arithmetic_count % 10 == 0) std::printf("\n"); } if ((arithmetic_count == 1000) || (arithmetic_count == 10000) || (arithmetic_count == 100000) || (arithmetic_count == 1000000)) { std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
Array length
C++
Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'.
std::vector<std::string> fruitV({ "apples", "oranges" }); std::list<std::string> fruitL({ "apples", "oranges" }); std::deque<std::string> fruitD({ "apples", "oranges" }); std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;
Ascending primes
C++ from C
Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly is at least mildly interesting. Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is at least one significantly better and much faster way, needing a mere 511 odd/prime tests. ;See also ;* OEIS:A052015 - Primes with distinct digits in ascending order ;Related: *[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't) *[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)
/* * Ascending primes * * Generate and show all primes with strictly ascending decimal digits. * * * Solution * * We only consider positive numbers in the range 1 to 123456789. We would * get 7027260 primes, because there are so many primes smaller than 123456789 * (see also Wolfram Alpha).On the other hand, there are only 511 distinct * nonzero positive integers having their digits arranged in ascending order. * Therefore, it is better to start with numbers that have properly arranged * digitsand then check if they are prime numbers.The method of generating * a sequence of such numbers is not indifferent.We want this sequence to be * monotonically increasing, because then additional sorting of results will * be unnecessary. It turns out that by using a queue we can easily get the * desired effect. Additionally, the algorithm then does not use recursion * (although the program probably does not have to comply with the MISRA * standard). The problem to be solved is the queue size, the a priori * assumption that 1000 is good enough, but a bit magical. */ #include <cmath> #include <iostream> #include <queue> #include <vector> using namespace std; queue<unsigned> suspected; vector<unsigned> primes; bool isPrime(unsigned n) { if (n == 2) { return true; } if (n == 1 || n % 2 == 0) { return false; } unsigned root = sqrt(n); for (unsigned k = 3; k <= root; k += 2) { if (n % k == 0) { return false; } } return true; } int main(int argc, char argv[]) { for (unsigned k = 1; k <= 9; k++) { suspected.push(k); } while (!suspected.empty()) { int n = suspected.front(); suspected.pop(); if (isPrime(n)) { primes.push_back(n); } // The value of n % 10 gives the least significient digit of n // for (unsigned k = n % 10 + 1; k <= 9; k++) { suspected.push(n * 10 + k); } } copy(primes.begin(), primes.end(), ostream_iterator<unsigned>(cout, " ")); return EXIT_SUCCESS; }
Associative array/Merging
C++
Define two associative arrays, where one represents the following "base" data: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "name" || "Rocket Skates" |- | "price" || 12.75 |- | "color" || "yellow" |} And the other represents "update" data: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "price" || 15.25 |- | "color" || "red" |- | "year" || 1974 |} Merge 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: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "name" || "Rocket Skates" |- | "price" || 15.25 |- | "color" || "red" |- | "year" || 1974 |}
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; map original{ {"name", "Rocket Skates"}, {"price", "12.75"}, {"color", "yellow"} }; map update{ {"price", "15.25"}, {"color", "red"}, {"year", "1974"} }; map merged(merge(original, update)); for (auto&& i : merged) std::cout << "key: " << i.first << ", value: " << i.second << '\n'; return 0; }
Attractive numbers
C++ from C
A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime. ;Example: The 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. ;Task: Show sequence items up to '''120'''. ;Reference: :* The OEIS entry: A063989: Numbers with a prime number of prime divisors.
#include <iostream> #include <iomanip> #define MAX 120 using namespace std; bool is_prime(int n) { if (n < 2) return false; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; int d = 5; while (d *d <= n) { if (!(n % d)) return false; d += 2; if (!(n % d)) return false; d += 4; } return true; } int count_prime_factors(int n) { if (n == 1) return 0; if (is_prime(n)) return 1; int count = 0, f = 2; while (true) { if (!(n % f)) { count++; n /= f; if (n == 1) return count; if (is_prime(n)) f = n; } else if (f >= 3) f += 2; else f = 3; } } int main() { cout << "The attractive numbers up to and including " << MAX << " are:" << endl; for (int i = 1, count = 0; i <= MAX; ++i) { int n = count_prime_factors(i); if (is_prime(n)) { cout << setw(4) << i; if (!(++count % 20)) cout << endl; } } cout << endl; return 0; }
Average loop length
C++
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. ;Task: Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 /** * Used to generate a uniform random distribution */ static std::random_device rd; //Will be used to obtain a seed for the random number engine static std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { //Factorial using dynamic programming to memoize the values. static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
Averages/Mean angle
C++ from C#
{{Related tasks/Statistical measures}}
#include <iomanip> #include <iostream> #include <vector> #define _USE_MATH_DEFINES #include <math.h> template<typename C> double meanAngle(const C& c) { auto it = std::cbegin(c); auto end = std::cend(c); double x = 0.0; double y = 0.0; double len = 0.0; while (it != end) { x += cos(*it * M_PI / 180); y += sin(*it * M_PI / 180); len++; it = std::next(it); } return atan2(y, x) * 180 / M_PI; } void printMean(std::initializer_list<double> init) { std::cout << std::fixed << std::setprecision(3) << meanAngle(init) << '\n'; } int main() { printMean({ 350, 10 }); printMean({ 90, 180, 270, 360 }); printMean({ 10, 20, 30 }); return 0; }
Averages/Pythagorean means
C++
{{Related tasks/Statistical measures}}
#include <vector> #include <iostream> #include <numeric> #include <cmath> #include <algorithm> double toInverse ( int i ) { return 1.0 / i ; } int main( ) { std::vector<int> numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ; double geometric_mean = pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ; std::vector<double> inverses ; inverses.resize( numbers.size( ) ) ; std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ; double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double! std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean " << geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ; return 0 ; }
Averages/Root mean square
C++
Task Compute the Root mean square of the numbers 1..10. The ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''. The RMS is calculated as the mean of the squares of the numbers, square-rooted: ::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}. ;See also {{Related tasks/Statistical measures}}
#include <iostream> #include <vector> #include <cmath> #include <numeric> int main( ) { std::vector<int> numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast<double>( numbers.size() ) ); std::cout << "The quadratic mean of the numbers 1 .. " << numbers.size() << " is " << meansquare << " !\n" ; return 0 ; }
Babbage problem
C++
Charles Babbage Charles Babbage's analytical engine. Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: {{quote | What is the smallest positive integer whose square ends in the digits 269,696? | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. }} He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. ;Task The 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. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For 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]. ;Motivation The 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.
#include <iostream> int main( ) { int current = 0 ; while ( ( current * current ) % 1000000 != 269696 ) current++ ; std::cout << "The square of " << current << " is " << (current * current) << " !\n" ; return 0 ; }
Balanced brackets
C++
'''Task''': * Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. * 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. ;Examples: (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
#include <algorithm> #include <iostream> #include <string> std::string generate(int n, char left = '[', char right = ']') { std::string str(std::string(n, left) + std::string(n, right)); std::random_shuffle(str.begin(), str.end()); return str; } bool balanced(const std::string &str, char left = '[', char right = ']') { int count = 0; for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == left) count++; else if (*it == right) if (--count < 0) return false; } return count == 0; } int main() { srand(time(NULL)); // seed rng for (int i = 0; i < 9; ++i) { std::string s(generate(i)); std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n"; } }
Balanced ternary
C++
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. ;Examples: Decimal 11 = 32 + 31 - 30, thus it can be written as "++-" Decimal 6 = 32 - 31 + 0 x 30, thus it can be written as "+-0" ;Task: Implement balanced ternary representation of integers with the following: # Support arbitrarily large integers, both positive and negative; # 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). # 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. # Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first. # Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable"). '''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-": * write out ''a'', ''b'' and ''c'' in decimal notation; * calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations. '''Note:''' The pages floating point balanced ternary.
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: // Store the value as a reversed string of +, 0 and - characters string value; // Helper function to change a balanced ternary character to an integer int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } // Helper function to negate a string of ternary characters string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: // Default constructor BalancedTernary() { value = "0"; } // Construct from a string BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } // Construct from an integer BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } // Copy constructor BalancedTernary(const BalancedTernary &n) { value = n.value; } // Addition operators BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); // Chop off leading zeroes return *this; } // Negation operator BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } // Subtraction operators BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } // Multiplication operators BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } // Stream output operator friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } // Convert to string string toString() const { return string(value.rbegin(), value.rend()); } // Convert to integer long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } // Convert to integer if possible bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Barnsley fern
C++
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). ;Task: Create this fractal fern, using the following transformations: * f1 (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn * f2 (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = -0.04 xn + 0.85 yn + 1.6 * f3 (chosen 7% of the time) xn + 1 = 0.2 xn - 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 * f4 (chosen 7% of the time) xn + 1 = -0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
#include <windows.h> #include <ctime> #include <string> const int BMP_SIZE = 600, ITERATIONS = static_cast<int>( 15e5 ); class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class fern { public: void draw() { bmp.create( BMP_SIZE, BMP_SIZE ); float x = 0, y = 0; HDC dc = bmp.getDC(); int hs = BMP_SIZE >> 1; for( int f = 0; f < ITERATIONS; f++ ) { SetPixel( dc, hs + static_cast<int>( x * 55.f ), BMP_SIZE - 15 - static_cast<int>( y * 55.f ), RGB( static_cast<int>( rnd() * 80.f ) + 20, static_cast<int>( rnd() * 128.f ) + 128, static_cast<int>( rnd() * 80.f ) + 30 ) ); getXY( x, y ); } bmp.saveBitmap( "./bf.bmp" ); } private: void getXY( float& x, float& y ) { float g, xl, yl; g = rnd(); if( g < .01f ) { xl = 0; yl = .16f * y; } else if( g < .07f ) { xl = .2f * x - .26f * y; yl = .23f * x + .22f * y + 1.6f; } else if( g < .14f ) { xl = -.15f * x + .28f * y; yl = .26f * x + .24f * y + .44f; } else { xl = .85f * x + .04f * y; yl = -.04f * x + .85f * y + 1.6f; } x = xl; y = yl; } float rnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } myBitmap bmp; }; int main( int argc, char* argv[]) { srand( static_cast<unsigned>( time( 0 ) ) ); fern f; f.draw(); return 0; }
Base64 decode data
C++14
See [[Base64 encode data]]. Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. When 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.
#include <algorithm> #include <iostream> #include <string> #include <vector> typedef unsigned char ubyte; const auto BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::vector<ubyte> encode(const std::vector<ubyte>& source) { auto it = source.cbegin(); auto end = source.cend(); std::vector<ubyte> sink; while (it != end) { auto b1 = *it++; int acc; sink.push_back(BASE64[b1 >> 2]); // first output (first six bits from b1) acc = (b1 & 0x3) << 4; // last two bits from b1 if (it != end) { auto b2 = *it++; acc |= (b2 >> 4); // first four bits from b2 sink.push_back(BASE64[acc]); // second output acc = (b2 & 0xF) << 2; // last four bits from b2 if (it != end) { auto b3 = *it++; acc |= (b3 >> 6); // first two bits from b3 sink.push_back(BASE64[acc]); // third output sink.push_back(BASE64[b3 & 0x3F]); // fouth output (final six bits from b3) } else { sink.push_back(BASE64[acc]); // third output sink.push_back('='); // fourth output (1 byte padding) } } else { sink.push_back(BASE64[acc]); // second output sink.push_back('='); // third output (first padding byte) sink.push_back('='); // fourth output (second padding byte) } } return sink; } int findIndex(ubyte val) { if ('A' <= val && val <= 'Z') { return val - 'A'; } if ('a' <= val && val <= 'z') { return val - 'a' + 26; } if ('0' <= val && val <= '9') { return val - '0' + 52; } if ('+' == val) { return 62; } if ('/' == val) { return 63; } return -1; } std::vector<ubyte> decode(const std::vector<ubyte>& source) { if (source.size() % 4 != 0) { throw new std::runtime_error("Error in size to the decode method"); } auto it = source.cbegin(); auto end = source.cend(); std::vector<ubyte> sink; while (it != end) { auto b1 = *it++; auto b2 = *it++; auto b3 = *it++; // might be first padding byte auto b4 = *it++; // might be first or second padding byte auto i1 = findIndex(b1); auto i2 = findIndex(b2); auto acc = i1 << 2; // six bits came from the first byte acc |= i2 >> 4; // two bits came from the first byte sink.push_back(acc); // output the first byte if (b3 != '=') { auto i3 = findIndex(b3); acc = (i2 & 0xF) << 4; // four bits came from the second byte acc |= i3 >> 2; // four bits came from the second byte sink.push_back(acc); // output the second byte if (b4 != '=') { auto i4 = findIndex(b4); acc = (i3 & 0x3) << 6; // two bits came from the third byte acc |= i4; // six bits came from the third byte sink.push_back(acc); // output the third byte } } } return sink; } int main() { using namespace std; string data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"; vector<ubyte> datav{ begin(data), end(data) }; cout << data << "\n\n" << decode(datav).data() << endl; return 0; }
Benford's law
C++
{{Wikipedia|Benford's_law}} '''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. In 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. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This 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. A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability :::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right) For 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). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. ''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. ;See also: * numberphile.com. * A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.
//to cope with the big numbers , I used the Class Library for Numbers( CLN ) //if used prepackaged you can compile writing "g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram" #include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cmath> #include <map> using namespace cln ; class NextNum { public : NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { } cl_I operator( )( ) { cl_I result = first + second ; first = second ; second = result ; return result ; } private : cl_I first ; cl_I second ; } ; void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) { for ( cl_I bignumber : fibos ) { std::ostringstream os ; fprintdecimal ( os , bignumber ) ;//from header file cln/integer_io.h int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ; auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ; if ( ! result.second ) numberfrequencies[ firstdigit ]++ ; } } int main( ) { std::vector<cl_I> fibonaccis( 1000 ) ; fibonaccis[ 0 ] = 0 ; fibonaccis[ 1 ] = 1 ; cl_I a = 0 ; cl_I b = 1 ; //since a and b are passed as references to the generator's constructor //they are constantly changed ! std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ; std::cout << std::endl ; std::map<int , int> frequencies ; findFrequencies( fibonaccis , frequencies ) ; std::cout << " found expected\n" ; for ( int i = 1 ; i < 10 ; i++ ) { double found = static_cast<double>( frequencies[ i ] ) / 1000 ; double expected = std::log10( 1 + 1 / static_cast<double>( i )) ; std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ; std::cout.precision( 3 ) ; std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ; } return 0 ; }
Best shuffle
C++ from Java
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A 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. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did ''not'' change. ;Example: tree, eetr, (0) ;Test cases: abracadabra seesaw elk grrrrrr up a ;Related tasks * [[Anagrams/Deranged anagrams]] * [[Permutations/Derangements]]
#include <iostream> #include <sstream> #include <algorithm> using namespace std; template <class S> class BestShuffle { public: BestShuffle() : rd(), g(rd()) {} S operator()(const S& s1) { S s2 = s1; shuffle(s2.begin(), s2.end(), g); for (unsigned i = 0; i < s2.length(); i++) if (s2[i] == s1[i]) for (unsigned j = 0; j < s2.length(); j++) if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) { swap(s2[i], s2[j]); break; } ostringstream os; os << s1 << endl << s2 << " [" << count(s2, s1) << ']'; return os.str(); } private: static int count(const S& s1, const S& s2) { auto count = 0; for (unsigned i = 0; i < s1.length(); i++) if (s1[i] == s2[i]) count++; return count; } random_device rd; mt19937 g; }; int main(int argc, char* arguments[]) { BestShuffle<basic_string<char>> bs; for (auto i = 1; i < argc; i++) cout << bs(basic_string<char>(arguments[i])) << endl; return 0; }
Bin given limits
C++
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ..'' bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] ;Task: The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will ''print the limit of each bin together with the count of items that fell in the range''. Assume the numbers to bin are too large to practically sort. ;Task examples: Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] 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, 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] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> std::vector<int> bins(const std::vector<int>& limits, const std::vector<int>& data) { std::vector<int> result(limits.size() + 1, 0); for (int n : data) { auto i = std::upper_bound(limits.begin(), limits.end(), n); ++result[i - limits.begin()]; } return result; } void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) { size_t n = limits.size(); if (n == 0) return; assert(n + 1 == bins.size()); std::cout << " < " << std::setw(3) << limits[0] << ": " << std::setw(2) << bins[0] << '\n'; for (size_t i = 1; i < n; ++i) std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < " << std::setw(3) << limits[i] << ": " << std::setw(2) << bins[i] << '\n'; std::cout << ">= " << std::setw(3) << limits[n - 1] << " : " << std::setw(2) << bins[n] << '\n'; } int main() { const std::vector<int> limits1{23, 37, 43, 53, 67, 83}; const std::vector<int> data1{ 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, 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}; std::cout << "Example 1:\n"; print_bins(limits1, bins(limits1, data1)); const std::vector<int> limits2{14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const std::vector<int> data2{ 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; std::cout << "\nExample 2:\n"; print_bins(limits2, bins(limits2, data2)); }
Bioinformatics/Sequence mutation
C++
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: # Choosing a random base position in the sequence. # Mutate the sequence by doing one of either: ## '''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) ## '''D'''elete the chosen base at the position. ## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position. # Randomly generate a test DNA sequence of at least 200 bases # "Pretty print" the sequence and a count of its size, and the count of each base in the sequence # Mutate the sequence ten times. # "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. ;Extra credit: * Give more information on the individual mutations applied. * Allow mutations to be weighted and/or chosen.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
Bioinformatics/base count
C++
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT ;Task: :* "Pretty print" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence :* print the total count of each base in the string.
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { // Map each character to a counter for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << " :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Brazilian numbers
C++ from D
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil. Brazilian numbers are defined as: The 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. ;E.G.: :* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''. :* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same. :* '''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. :* '''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. :* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same. :* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same. :* ''and so on...'' All 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'''. More 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''' The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All 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 ;Task: Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; :* the first '''20''' Brazilian numbers; :* the first '''20 odd''' Brazilian numbers; :* the first '''20 prime''' Brazilian numbers; ;See also: :* '''OEIS:A125134 - Brazilian numbers''' :* '''OEIS:A257521 - Odd Brazilian numbers''' :* '''OEIS:A085104 - Prime Brazilian numbers'''
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { if (sameDigits(n, b)) { return true; } } return false; } bool isPrime(int n) { if (n < 2)return false; if (n % 2 == 0)return n == 2; if (n % 3 == 0)return n == 3; int d = 5; while (d * d <= n) { if (n % d == 0)return false; d += 2; if (n % d == 0)return false; d += 4; } return true; } int main() { for (auto kind : { "", "odd ", "prime " }) { bool quiet = false; int BigLim = 99999; int limit = 20; std::cout << "First " << limit << ' ' << kind << "Brazillian numbers:\n"; int c = 0; int n = 7; while (c < BigLim) { if (isBrazilian(n)) { if (!quiet)std::cout << n << ' '; if (++c == limit) { std::cout << "\n\n"; quiet = true; } } if (quiet && kind != "") continue; if (kind == "") { n++; } else if (kind == "odd ") { n += 2; } else if (kind == "prime ") { while (true) { n += 2; if (isPrime(n)) break; } } else { throw new std::runtime_error("Unexpected"); } } if (kind == "") { std::cout << "The " << BigLim + 1 << "th Brazillian number is: " << n << "\n\n"; } } return 0; }
Break OO privacy
C++
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. The 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. The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory. Note that cheating on your type system is almost universally regarded as unidiomatic at best, and poor programming practice at worst. Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
#include <iostream> class CWidget; // Forward-declare that we have a class named CWidget. class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); // Disallow the default constructor. CWidget(const CWidget&); // Disallow the copy constructor CWidget& operator=(const CWidget&); // Disallow the assignment operator. public: CWidget(CFactory& parent); ~CWidget(); }; // CFactory constructors and destructors. Very simple things. CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} // CFactory method which creates CWidgets. CWidget* CFactory::GetWidget() { // Create a new CWidget, tell it we're its parent. return new CWidget(*this); } // CWidget constructor CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
Burrows–Wheeler transform
C++ from C#
{{Wikipedia|Burrows-Wheeler_transform}} The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This 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. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows-Wheeler transform
#include <algorithm> #include <iostream> #include <vector> const int STX = 0x02; const int ETX = 0x03; void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; } std::string bwt(const std::string &s) { for (char c : s) { if (c == STX || c == ETX) { throw std::runtime_error("Input can't contain STX or ETX"); } } std::string ss; ss += STX; ss += s; ss += ETX; std::vector<std::string> table; for (size_t i = 0; i < ss.length(); i++) { table.push_back(ss); rotate(ss); } //table.sort(); std::sort(table.begin(), table.end()); std::string out; for (auto &s : table) { out += s[s.length() - 1]; } return out; } std::string ibwt(const std::string &r) { int len = r.length(); std::vector<std::string> table(len); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { table[j] = r[j] + table[j]; } std::sort(table.begin(), table.end()); } for (auto &row : table) { if (row[row.length() - 1] == ETX) { return row.substr(1, row.length() - 2); } } return {}; } std::string makePrintable(const std::string &s) { auto ls = s; for (auto &c : ls) { if (c == STX) { c = '^'; } else if (c == ETX) { c = '|'; } } return ls; } int main() { auto tests = { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" }; for (auto &test : tests) { std::cout << makePrintable(test) << "\n"; std::cout << " --> "; std::string t; try { t = bwt(test); std::cout << makePrintable(t) << "\n"; } catch (std::runtime_error &e) { std::cout << "Error " << e.what() << "\n"; } std::string r = ibwt(t); std::cout << " --> " << r << "\n\n"; } return 0; }
CSV data manipulation
C++
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. ;Task: Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 Suggestions Show how to add a column, headed 'SUM', of the sums of the rows. If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: // trim string for empty spaces in begining and at the end inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
CSV to HTML translation
C++
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be ''escaped'' when converted to HTML ;Task: Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. : Character,Speech : The multitude,The messiah! Show us the messiah! : Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! : The multitude,Who are you? : Brians mother,I'm his mother; that's who! : The multitude,Behold his mother! Behold his mother! ;Extra credit: ''Optionally'' allow special formatting for the first row of the table as if it is the tables header row (via preferably; CSS if you must).
#include <string> #include <boost/regex.hpp> #include <iostream> std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\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" ; std::cout << csvToHTML( text ) ; return 0 ; } std::string csvToHTML( const std::string & csvtext ) { //the order of the regexes and the replacements is decisive! std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ; const char* replacements [ 5 ] = { "&lt;" , "&gt;" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ; boost::regex e1( regexes[ 0 ] ) ; std::string tabletext = boost::regex_replace( csvtext , e1 , replacements[ 0 ] , boost::match_default | boost::format_all ) ; for ( int i = 1 ; i < 5 ; i++ ) { e1.assign( regexes[ i ] ) ; tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ; } tabletext = std::string( "<TABLE>\n" ) + tabletext ; tabletext.append( "</TABLE>\n" ) ; return tabletext ; }
Calculating the value of e
C++ from C
Calculate the value of ''e''. (''e'' is also known as ''Euler's number'' and ''Napier's constant''.) See details: Calculating the value of e
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { const double EPSILON = 1.0e-15; unsigned long long fact = 1; double e = 2.0, e0; int n = 2; do { e0 = e; fact *= n++; e += 1.0 / fact; } while (fabs(e - e0) >= EPSILON); cout << "e = " << setprecision(16) << e << endl; return 0; }
Call a function
C++
Demonstrate the different syntax and semantics provided for calling a function. This may include: :* Calling a function that requires no arguments :* Calling a function with a fixed number of arguments :* Calling a function with optional arguments :* Calling a function with a variable number of arguments :* Calling a function with named arguments :* Using a function in statement context :* Using a function in first-class context within an expression :* Obtaining the return value of a function :* Distinguishing built-in functions and user-defined functions :* Distinguishing subroutines and functions ;* Stating whether arguments are passed by value or by reference ;* Is partial application possible and how This task is ''not'' about defining functions.
#include <iostream> using namespace std; /* passing arguments by reference */ void f(int &y) /* variable is now passed by reference */ { y++; } int main() { int x = 0; cout<<"x = "<<x<<endl; /* should produce result "x = 0" */ f(x); /* call function f */ cout<<"x = "<<x<<endl; /* should produce result "x = 1" */ }
Canonicalize CIDR
C++
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. ;Example: Given '''87.70.141.1/22''', your code should output '''87.70.140.0/22''' ;Explanation: An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry. The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0. ;More examples for testing 36.18.154.103/12 - 36.16.0.0/12 62.62.197.11/29 - 62.62.197.8/29 67.137.119.181/4 - 64.0.0.0/4 161.214.74.21/24 - 161.214.74.0/24 184.232.176.184/18 - 184.232.128.0/18
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> // Class representing an IPv4 address + netmask length class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsigned int mask_length() const { return mask_length_; } friend std::istream& operator>>(std::istream&, ipv4_cidr&); private: std::uint32_t address_ = 0; unsigned int mask_length_ = 0; }; // Stream extraction operator, also performs canonicalization std::istream& operator>>(std::istream& in, ipv4_cidr& cidr) { int a, b, c, d, m; char ch; if (!(in >> a >> ch) || a < 0 || a > UINT8_MAX || ch != '.' || !(in >> b >> ch) || b < 0 || b > UINT8_MAX || ch != '.' || !(in >> c >> ch) || c < 0 || c > UINT8_MAX || ch != '.' || !(in >> d >> ch) || d < 0 || d > UINT8_MAX || ch != '/' || !(in >> m) || m < 1 || m > 32) { in.setstate(std::ios_base::failbit); return in; } uint32_t mask = ~((1 << (32 - m)) - 1); uint32_t address = (a << 24) + (b << 16) + (c << 8) + d; address &= mask; cidr.address_ = address; cidr.mask_length_ = m; return in; } // Stream insertion operator std::ostream& operator<<(std::ostream& out, const ipv4_cidr& cidr) { uint32_t address = cidr.address(); unsigned int d = address & UINT8_MAX; address >>= 8; unsigned int c = address & UINT8_MAX; address >>= 8; unsigned int b = address & UINT8_MAX; address >>= 8; unsigned int a = address & UINT8_MAX; out << a << '.' << b << '.' << c << '.' << d << '/' << cidr.mask_length(); return out; } int main(int argc, char** argv) { const char* tests[] = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18" }; for (auto test : tests) { std::istringstream in(test); ipv4_cidr cidr; if (in >> cidr) std::cout << std::setw(18) << std::left << test << " -> " << cidr << '\n'; else std::cerr << test << ": invalid CIDR\n"; } return 0; }
Cantor set
C++ from D
Draw a Cantor set. See details at this Wikipedia webpage: Cantor set
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { // init for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } // calculate cantor(0, WIDTH, 1); // print for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
Cartesian product of two or more lists
C++
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: ::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: ::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. :: {1, 2} x {} = {} :: {} x {1, 2} = {} For 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. Use your n-ary Cartesian product function to show the following products: :: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1} :: {1, 2, 3} x {30} x {500, 100} :: {1, 2, 3} x {} x {500, 100}
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }
Casting out nines
C++
Task (in three parts): ;Part 1 Write 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. Note 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. With 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. ;Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: : Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]). : note that 318682 has the same checksum as (101558 + 217124); : 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); : note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2. Demonstrate 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. ;Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: : \mathit{co9}(x) is the residual of x mod 9; : the procedure can be extended to bases other than 9. Demonstrate 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. ;related tasks * [[First perfect square in base N with N unique digits]] * [[Kaprekar numbers]]
// Casting Out Nines // // Nigel Galloway. June 24th., 2012 // #include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 - ((double)c2/c1)*100 << "%" <<std::endl; return 0; }
Catalan numbers/Pascal's triangle
C++
Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle. ;See: * Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction. * Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition. * Sequence A000108 on OEIS has a lot of information on Catalan Numbers. ;Related Tasks: [[Pascal's triangle]]
// Generate Catalan Numbers // // Nigel Galloway: June 9th., 2012 // #include <iostream> int main() { const int N = 15; int t[N+2] = {0,1}; for(int i = 1; i<=N; i++){ for(int j = i; j>1; j--) t[j] = t[j] + t[j-1]; t[i+1] = t[i]; for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1]; std::cout << t[i+1] - t[i] << " "; } return 0; }
Catamorphism
C++
''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. ;Task: Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language. ;See also: * Wikipedia article: Fold * Wikipedia article: Catamorphism
#include <iostream> #include <numeric> #include <functional> #include <vector> int main() { std::vector<int> nums = { 1, 2, 3, 4, 5 }; auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>()); auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) { return a + 2 * b; }); std::cout << "nums_added: " << nums_added << std::endl; std::cout << "nums_other: " << nums_other << std::endl; }
Chaocipher
C++ from C#
Description: The 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. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ;Task: Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
#include <iostream> enum class Mode { ENCRYPT, DECRYPT, }; const std::string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; const std::string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; std::string exec(std::string text, Mode mode, bool showSteps = false) { auto left = L_ALPHABET; auto right = R_ALPHABET; auto eText = new char[text.size() + 1]; auto temp = new char[27]; memset(eText, 0, text.size() + 1); memset(temp, 0, 27); for (size_t i = 0; i < text.size(); i++) { if (showSteps) std::cout << left << ' ' << right << '\n'; size_t index; if (mode == Mode::ENCRYPT) { index = right.find(text[i]); eText[i] = left[index]; } else { index = left.find(text[i]); eText[i] = right[index]; } if (i == text.size() - 1) break; // permute left for (int j = index; j < 26; ++j) temp[j - index] = left[j]; for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j]; auto store = temp[1]; for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; left = temp; // permurte right for (int j = index; j < 26; ++j) temp[j - index] = right[j]; for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j]; store = temp[0]; for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j]; temp[25] = store; store = temp[2]; for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; right = temp; } return eText; } int main() { auto plainText = "WELLDONEISBETTERTHANWELLSAID"; std::cout << "The original plaintext is : " << plainText << "\n\n"; std::cout << "The left and right alphabets after each permutation during encryption are :\n"; auto cipherText = exec(plainText, Mode::ENCRYPT, true); std::cout << "\nThe ciphertext is : " << cipherText << '\n'; auto plainText2 = exec(cipherText, Mode::DECRYPT); std::cout << "\nThe recovered plaintext is : " << plainText2 << '\n'; return 0; }
Chaos game
C++
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. ;Task Play 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. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. ;See also * The Game of Chaos
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class chaos { public: void start() { POINT org; fillPts(); initialPoint( org ); initColors(); int cnt = 0, i; bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear( 255 ); while( cnt++ < 1000000 ) { switch( rand() % 6 ) { case 0: case 3: i = 0; break; case 1: case 5: i = 1; break; case 2: case 4: i = 2; } setPoint( org, myPoints[i], i ); } // --- edit this path --- // bmp.saveBitmap( "F:/st.bmp" ); } private: void setPoint( POINT &o, POINT v, int i ) { POINT z; o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1; SetPixel( bmp.getDC(), o.x, o.y, colors[i] ); } void fillPts() { int a = BMP_SIZE - 1; myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0; myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a; } void initialPoint( POINT& p ) { p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 ); p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 ); } void initColors() { colors[0] = RGB( 255, 0, 0 ); colors[1] = RGB( 0, 255, 0 ); colors[2] = RGB( 0, 0, 255 ); } myBitmap bmp; POINT myPoints[3]; COLORREF colors[3]; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); chaos c; c.start(); return 0; }
Check output device is a terminal
C++ from C
Demonstrate how to check whether the output device is a terminal or not. ;Related task: * [[Check input device is a terminal]]
#if _WIN32 #include <io.h> #define ISATTY _isatty #define FILENO _fileno #else #include <unistd.h> #define ISATTY isatty #define FILENO fileno #endif #include <iostream> int main() { if (ISATTY(FILENO(stdout))) { std::cout << "stdout is a tty\n"; } else { std::cout << "stdout is not a tty\n"; } return 0; }
Cheryl's birthday
C++ from Go
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. ;Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. ;Related task: * [[Sum and Product Puzzle]] ;References * Wikipedia article of the same name. * Tuple Relational Calculus
#include <algorithm> #include <iostream> #include <vector> using namespace std; const vector<string> MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; struct Birthday { int month, day; friend ostream &operator<<(ostream &, const Birthday &); }; ostream &operator<<(ostream &out, const Birthday &birthday) { return out << MONTHS[birthday.month - 1] << ' ' << birthday.day; } template <typename C> bool monthUniqueIn(const Birthday &b, const C &container) { auto it = cbegin(container); auto end = cend(container); int count = 0; while (it != end) { if (it->month == b.month) { count++; } it = next(it); } return count == 1; } template <typename C> bool dayUniqueIn(const Birthday &b, const C &container) { auto it = cbegin(container); auto end = cend(container); int count = 0; while (it != end) { if (it->day == b.day) { count++; } it = next(it); } return count == 1; } template <typename C> bool monthWithUniqueDayIn(const Birthday &b, const C &container) { auto it = cbegin(container); auto end = cend(container); while (it != end) { if (it->month == b.month && dayUniqueIn(*it, container)) { return true; } it = next(it); } return false; } int main() { vector<Birthday> choices = { {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}, }; // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. vector<Birthday> filtered; for (auto bd : choices) { if (!monthUniqueIn(bd, choices)) { filtered.push_back(bd); } } // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. vector<Birthday> filtered2; for (auto bd : filtered) { if (!monthWithUniqueDayIn(bd, filtered)) { filtered2.push_back(bd); } } // Bernard now knows the answer. // So the day must be unique within the remaining choices. vector<Birthday> filtered3; for (auto bd : filtered2) { if (dayUniqueIn(bd, filtered2)) { filtered3.push_back(bd); } } // Albert now knows the answer too. // So the month must be unique within the remaining choices. vector<Birthday> filtered4; for (auto bd : filtered3) { if (monthUniqueIn(bd, filtered3)) { filtered4.push_back(bd); } } if (filtered4.size() == 1) { cout << "Cheryl's birthday is " << filtered4[0] << '\n'; } else { cout << "Something went wrong!\n"; } return 0; }
Chinese remainder theorem
C++
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, 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: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv a_2 \pmod{n_2} \\ &{}\ \ \vdots \\ x &\equiv a_k \pmod{n_k} \end{align} Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. ;Task: Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. ''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]. '''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: ::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows: For each i, the integers n_i and N/n_i are co-prime. Using 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. Then, one solution to the system of simultaneous congruences is: ::: x = \sum_{i=1}^k a_i s_i N/n_i and the minimal solution, ::: x \pmod{N}.
// Requires C++17 #include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Chinese zodiac
C++
Determine the Chinese zodiac sign and related associations for a given year. Traditionally, 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. Years 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. Mapping 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. The 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. Thus, 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. ;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. You 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). ;Requisite information: * The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. * The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. * Each element gets two consecutive years; a yang followed by a yin. * The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from. Thus, 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. ;Information for optional task: * 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". * 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". Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
#include <iostream> #include <cmath> using namespace std; const string animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}; const string elements[]={"Wood","Fire","Earth","Metal","Water"}; string getElement(int year) { int element = floor((year-4)%10/2); return elements[element]; } string getAnimal(int year) { return animals[(year-4)%12]; } string getYY(int year) { if(year%2==0) { return "yang"; } else { return "yin"; } } int main() { int years[]={1935,1938,1968,1972,1976,2017}; //the zodiac cycle didnt start until 4 CE, so years <4 shouldnt be valid for(int i=0;i<6;i++) { cout << years[i] << " is the year of the " << getElement(years[i]) << " " << getAnimal(years[i]) << " (" << getYY(years[i]) << ")." << endl; } return 0; }
Church numerals
C++
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. * '''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. * '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)''' * '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))''' * 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. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: * Church Zero, * a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), * functions for Addition, Multiplication and Exponentiation over Church numerals, * a function to convert integers to corresponding Church numerals, * and a function to convert Church numerals to corresponding integers. You should: * Derive Church numerals three and four in terms of Church zero and a Church successor function. * use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, * similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, * convert each result back to an integer, and return it or print it to the console.
#include <iostream> // apply the function zero times (return an identity function) auto Zero = [](auto){ return [](auto x){ return x; }; }; // define Church True and False auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; // apply the function f one more time auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; }; } // apply the function a times after b times auto Add(auto a, auto b) { return [=](auto f) { return [=](auto x) { return a(f)(b(f)(x)); }; }; } // apply the function a times b times auto Multiply(auto a, auto b) { return [=](auto f) { return a(b(f)); }; } // apply the function a^b times auto Exp(auto a, auto b) { return b(a); } // check if a number is zero auto IsZero(auto a){ return a([](auto){ return False; })(True); } // apply the function f one less time auto Predecessor(auto a) { return [=](auto f) { return [=](auto x) { return a( [=](auto g) { return [=](auto h){ return h(g(f)); }; } )([=](auto){ return x; })([](auto y){ return y; }); }; }; } // apply the Predecessor function b times to a auto Subtract(auto a, auto b) { { return b([](auto c){ return Predecessor(c); })(a); }; } namespace { // helper functions for division. // end the recusrion auto Divr(decltype(Zero), auto) { return Zero; } // count how many times b can be subtracted from a auto Divr(auto a, auto b) { auto a_minus_b = Subtract(a, b); auto isZero = IsZero(a_minus_b); // normalize all Church zeros to be the same (intensional equality). // In this implemetation, Church numerals have extensional equality // but not intensional equality. '6 - 3' and '4 - 1' have extensional // equality because they will both cause a function to be called // three times but due to the static type system they do not have // intensional equality. Internally the two numerals are represented // by different lambdas. Normalize all Church zeros (1 - 1, 2 - 2, etc.) // to the same zero (Zero) so it will match the function that end the // recursion. return isZero (Zero) (Successor(Divr(isZero(Zero)(a_minus_b), b))); } } // apply the function a / b times auto Divide(auto a, auto b) { return Divr(Successor(a), b); } // create a Church numeral from an integer at compile time template <int N> constexpr auto ToChurch() { if constexpr(N<=0) return Zero; else return Successor(ToChurch<N-1>()); } // use an increment function to convert the Church number to an integer int ToInt(auto church) { return church([](int n){ return n + 1; })(0); } int main() { // show some examples auto three = Successor(Successor(Successor(Zero))); auto four = Successor(three); auto six = ToChurch<6>(); auto ten = ToChurch<10>(); auto thousand = Exp(ten, three); std::cout << "\n 3 + 4 = " << ToInt(Add(three, four)); std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four)); std::cout << "\n 3^4 = " << ToInt(Exp(three, four)); std::cout << "\n 4^3 = " << ToInt(Exp(four, three)); std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero)); std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three)); std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four)); std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three)); std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six)); auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand)); auto looloolool = Successor(looloolooo); std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool); // calculate the golden ratio by using a Church numeral to // apply the funtion 'f(x) = 1 + 1/x' a thousand times std::cout << "\n golden ratio = " << thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n"; }
Circles of given radius through two points
C++11
2 circles with a given radius through 2 points in 2D space. Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. ;Exceptions: # r==0.0 should be treated as never describing circles (except in the case where the points are coincident). # 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. # 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. # If the points are too far apart then no circles can be drawn. ;Task detail: * 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''. * Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 ;Related task: * [[Total circles area]]. ;See also: * Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_category, point, point>; double distance(point l, point r) { return std::hypot(l.x - r.x, l.y - r.y); } result_t find_circles(point p1, point p2, double r) { point ans1 { 1/0., 1/0.}, ans2 { 1/0., 1/0.}; if (p1 == p2) { if(r == 0.) return std::make_tuple(ONE_COINCEDENT, p1, p2 ); else return std::make_tuple(INFINITE, ans1, ans2); } point center { p1.x/2 + p2.x/2, p1.y/2 + p2.y/2}; double half_distance = distance(center, p1); if(half_distance > r) return std::make_tuple(NONE, ans1, ans2); if(half_distance - r == 0) return std::make_tuple(ONE_DIAMETER, center, ans2); double root = sqrt(pow(r, 2.l) - pow(half_distance, 2.l)) / distance(p1, p2); ans1.x = center.x + root * (p1.y - p2.y); ans1.y = center.y + root * (p2.x - p1.x); ans2.x = center.x - root * (p1.y - p2.y); ans2.y = center.y - root * (p2.x - p1.x); return std::make_tuple(TWO, ans1, ans2); } void print(result_t result, std::ostream& out = std::cout) { point r1, r2; result_category res; std::tie(res, r1, r2) = result; switch(res) { case NONE: out << "There are no solutions, points are too far away\n"; break; case ONE_COINCEDENT: case ONE_DIAMETER: out << "Only one solution: " << r1.x << ' ' << r1.y << '\n'; break; case INFINITE: out << "Infinitely many circles can be drawn\n"; break; case TWO: out << "Two solutions: " << r1.x << ' ' << r1.y << " and " << r2.x << ' ' << r2.y << '\n'; break; } } int main() { constexpr int size = 5; const point points[size*2] = { {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345}, {0.1234, 0.9876}, {0.1234, 0.9876} }; const double radius[size] = {2., 1., 2., .5, 0.}; for(int i = 0; i < size; ++i) print(find_circles(points[i*2], points[i*2 + 1], radius[i])); }
Cistercian numerals
C++ from Go
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'''. ;How they work All 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: :* The '''upper-right''' quadrant represents the '''ones''' place. :* The '''upper-left''' quadrant represents the '''tens''' place. :* The '''lower-right''' quadrant represents the '''hundreds''' place. :* The '''lower-left''' quadrant represents the '''thousands''' place. Please 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] ;Task :* 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). :* Use the routine to show the following Cistercian numerals: ::* 0 ::* 1 ::* 20 ::* 300 ::* 4000 ::* 5555 ::* 6789 ::* And a number of your choice! ;Notes Due 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. ;See also :* '''Numberphile - The Forgotten Number System''' :* '''dcode.fr - Online Cistercian numeral converter'''
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
Closures/Value capture
C++11
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. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. ;Goal: Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For 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. See also: [[Multiple distinct objects]]
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Colour bars/Display
C++
Display a series of vertical color bars across the width of the display. The color bars should either use: :::* the system palette, or :::* the sequence of colors: ::::::* black ::::::* red ::::::* green ::::::* blue ::::::* magenta ::::::* cyan ::::::* yellow ::::::* white
#include <QtGui> #include "colorbars.h" MyWidget::MyWidget( ) : width( 640 ) , height( 240 ) , colornumber( 8 ) { setGeometry( 0, 0 , width , height ) ; } void MyWidget::paintEvent ( QPaintEvent * ) { int rgbtriplets[ ] = { 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 255 , 0 , 255 , 0 , 255 , 255 , 255 , 255 , 0 , 255 , 255 , 255 } ; QPainter myPaint( this ) ; int rectwidth = width / colornumber ; //width of one rectangle int xstart = 1 ; //x coordinate of the first rectangle int offset = -1 ; //to allow for ++offset to define the red value even in the first run of the loop below for ( int i = 0 ; i < colornumber ; i++ ) { QColor rectColor ; rectColor.setRed( rgbtriplets[ ++offset ] ) ; rectColor.setGreen( rgbtriplets[ ++offset ] ) ; rectColor.setBlue( rgbtriplets[ ++offset ] ) ; myPaint.fillRect( xstart , 0 , rectwidth , height - 1 , rectColor ) ; xstart += rectwidth + 1 ; } }
Comma quibbling
C++
Comma quibbling is a task originally set by Eric Lippert in his blog. ;Task: Write a function to generate a string output which is the concatenation of input words from a list/sequence where: # An input of no words produces the output string of just the two brace characters "{}". # An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". # 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}". # 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}". Test your function with the following series of inputs showing your output here on this page: * [] # (No input words). * ["ABC"] * ["ABC", "DEF"] * ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#include <iostream> template<class T> void quibble(std::ostream& o, T i, T e) { o << "{"; if (e != i) { T n = i++; const char* more = ""; while (e != i) { o << more << *n; more = ", "; n = i++; } o << (*more?" and ":"") << *n; } o << "}"; } int main(int argc, char** argv) { char const* a[] = {"ABC","DEF","G","H"}; for (int i=0; i<5; i++) { quibble(std::cout, a, a+i); std::cout << std::endl; } return 0; }
Command-line arguments
C++
{{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]]. See also [[Program name]]. For parsing command line arguments intelligently, see [[Parsing command-line arguments]]. Example command line: myprogram -c "alpha beta" -h "gamma"
#include <iostream> int main(int argc, const char* argv[]) { std::cout << "This program is named " << argv[0] << '\n' << "There are " << argc - 1 << " arguments given.\n"; for (int i = 1; i < argc; ++i) std::cout << "The argument #" << i << " is " << argv[i] << '\n'; }
Compare a list of strings
C++
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each 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. If the input list has less than two elements, the tests should always return true. There is ''no'' need to provide a complete program and output. Assume 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. Try 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. If 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.
Assuming that the <code>strings</code> variable is of type <code>T&lt;std::string&gt;</code> where <code>T</code> is an ordered STL container such as <code>std::vector</code>:
Compare a list of strings
C++ 11
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each 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. If the input list has less than two elements, the tests should always return true. There is ''no'' need to provide a complete program and output. Assume 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. Try 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. If 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.
#include <algorithm> #include <string> // Bug: calling operator++ on an empty collection invokes undefined behavior. std::all_of( ++(strings.begin()), strings.end(), [&](std::string a){ return a == strings.front(); } ) // All equal std::is_sorted( strings.begin(), strings.end(), [](std::string a, std::string b){ return !(b < a); }) ) // Strictly ascending
Compile-time calculation
C++
Some programming languages allow calculation of values at compile time. ;Task: Calculate 10! (ten factorial) at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#include <iostream> template<int i> struct Fac { static const int result = i * Fac<i-1>::result; }; template<> struct Fac<1> { static const int result = 1; }; int main() { std::cout << "10! = " << Fac<10>::result << "\n"; return 0; }
Compile-time calculation
C++11
Some programming languages allow calculation of values at compile time. ;Task: Calculate 10! (ten factorial) at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#include <stdio.h> constexpr int factorial(int n) { return n ? (n * factorial(n - 1)) : 1; } constexpr int f10 = factorial(10); int main() { printf("%d\n", f10); return 0; }
Compiler/lexical analyzer
C++
The C and Python versions can be considered reference implementations. ;Related Tasks * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task
#include <charconv> // std::from_chars #include <fstream> // file_to_string, string_to_file #include <functional> // std::invoke #include <iomanip> // std::setw #include <ios> // std::left #include <iostream> #include <map> // keywords #include <sstream> #include <string> #include <utility> // std::forward #include <variant> // TokenVal using namespace std; // ===================================================================================================================== // Machinery // ===================================================================================================================== string file_to_string (const string& path) { // Open file ifstream file {path, ios::in | ios::binary | ios::ate}; if (!file) throw (errno); // Allocate string memory string contents; contents.resize(file.tellg()); // Read file contents into string file.seekg(0); file.read(contents.data(), contents.size()); return contents; } void string_to_file (const string& path, string contents) { ofstream file {path, ios::out | ios::binary}; if (!file) throw (errno); file.write(contents.data(), contents.size()); } template <class F> void with_IO (string source, string destination, F&& f) { string input; if (source == "stdin") getline(cin, input); else input = file_to_string(source); string output = invoke(forward<F>(f), input); if (destination == "stdout") cout << output; else string_to_file(destination, output); } // Add escaped newlines and backslashes back in for printing string sanitize (string s) { for (auto i = 0u; i < s.size(); ++i) { if (s[i] == '\n') s.replace(i++, 1, "\\n"); else if (s[i] == '\\') s.replace(i++, 1, "\\\\"); } return s; } class Scanner { public: const char* pos; int line = 1; int column = 1; Scanner (const char* source) : pos {source} {} inline char peek () { return *pos; } void advance () { if (*pos == '\n') { ++line; column = 1; } else ++column; ++pos; } char next () { advance(); return peek(); } void skip_whitespace () { while (isspace(static_cast<unsigned char>(peek()))) advance(); } }; // class Scanner // ===================================================================================================================== // Tokens // ===================================================================================================================== enum class TokenName { OP_MULTIPLY, OP_DIVIDE, OP_MOD, OP_ADD, OP_SUBTRACT, OP_NEGATE, OP_LESS, OP_LESSEQUAL, OP_GREATER, OP_GREATEREQUAL, OP_EQUAL, OP_NOTEQUAL, OP_NOT, OP_ASSIGN, OP_AND, OP_OR, LEFTPAREN, RIGHTPAREN, LEFTBRACE, RIGHTBRACE, SEMICOLON, COMMA, KEYWORD_IF, KEYWORD_ELSE, KEYWORD_WHILE, KEYWORD_PRINT, KEYWORD_PUTC, IDENTIFIER, INTEGER, STRING, END_OF_INPUT, ERROR }; using TokenVal = variant<int, string>; struct Token { TokenName name; TokenVal value; int line; int column; }; const char* to_cstring (TokenName name) { static const char* s[] = { "Op_multiply", "Op_divide", "Op_mod", "Op_add", "Op_subtract", "Op_negate", "Op_less", "Op_lessequal", "Op_greater", "Op_greaterequal", "Op_equal", "Op_notequal", "Op_not", "Op_assign", "Op_and", "Op_or", "LeftParen", "RightParen", "LeftBrace", "RightBrace", "Semicolon", "Comma", "Keyword_if", "Keyword_else", "Keyword_while", "Keyword_print", "Keyword_putc", "Identifier", "Integer", "String", "End_of_input", "Error" }; return s[static_cast<int>(name)]; } string to_string (Token t) { ostringstream out; out << setw(2) << t.line << " " << setw(2) << t.column << " "; switch (t.name) { case (TokenName::IDENTIFIER) : out << "Identifier " << get<string>(t.value); break; case (TokenName::INTEGER) : out << "Integer " << left << get<int>(t.value); break; case (TokenName::STRING) : out << "String \"" << sanitize(get<string>(t.value)) << '"'; break; case (TokenName::END_OF_INPUT) : out << "End_of_input"; break; case (TokenName::ERROR) : out << "Error " << get<string>(t.value); break; default : out << to_cstring(t.name); } out << '\n'; return out.str(); } // ===================================================================================================================== // Lexer // ===================================================================================================================== class Lexer { public: Lexer (const char* source) : s {source}, pre_state {s} {} bool has_more () { return s.peek() != '\0'; } Token next_token () { s.skip_whitespace(); pre_state = s; switch (s.peek()) { case '*' : return simply(TokenName::OP_MULTIPLY); case '%' : return simply(TokenName::OP_MOD); case '+' : return simply(TokenName::OP_ADD); case '-' : return simply(TokenName::OP_SUBTRACT); case '{' : return simply(TokenName::LEFTBRACE); case '}' : return simply(TokenName::RIGHTBRACE); case '(' : return simply(TokenName::LEFTPAREN); case ')' : return simply(TokenName::RIGHTPAREN); case ';' : return simply(TokenName::SEMICOLON); case ',' : return simply(TokenName::COMMA); case '&' : return expect('&', TokenName::OP_AND); case '|' : return expect('|', TokenName::OP_OR); case '<' : return follow('=', TokenName::OP_LESSEQUAL, TokenName::OP_LESS); case '>' : return follow('=', TokenName::OP_GREATEREQUAL, TokenName::OP_GREATER); case '=' : return follow('=', TokenName::OP_EQUAL, TokenName::OP_ASSIGN); case '!' : return follow('=', TokenName::OP_NOTEQUAL, TokenName::OP_NOT); case '/' : return divide_or_comment(); case '\'' : return char_lit(); case '"' : return string_lit(); default : if (is_id_start(s.peek())) return identifier(); if (is_digit(s.peek())) return integer_lit(); return error("Unrecognized character '", s.peek(), "'"); case '\0' : return make_token(TokenName::END_OF_INPUT); } } private: Scanner s; Scanner pre_state; static const map<string, TokenName> keywords; template <class... Args> Token error (Args&&... ostream_args) { string code {pre_state.pos, (string::size_type) s.column - pre_state.column}; ostringstream msg; (msg << ... << forward<Args>(ostream_args)) << '\n' << string(28, ' ') << "(" << s.line << ", " << s.column << "): " << code; if (s.peek() != '\0') s.advance(); return make_token(TokenName::ERROR, msg.str()); } inline Token make_token (TokenName name, TokenVal value = 0) { return {name, value, pre_state.line, pre_state.column}; } Token simply (TokenName name) { s.advance(); return make_token(name); } Token expect (char expected, TokenName name) { if (s.next() == expected) return simply(name); else return error("Unrecognized character '", s.peek(), "'"); } Token follow (char expected, TokenName ifyes, TokenName ifno) { if (s.next() == expected) return simply(ifyes); else return make_token(ifno); } Token divide_or_comment () { if (s.next() != '*') return make_token(TokenName::OP_DIVIDE); while (s.next() != '\0') { if (s.peek() == '*' && s.next() == '/') { s.advance(); return next_token(); } } return error("End-of-file in comment. Closing comment characters not found."); } Token char_lit () { int n = s.next(); if (n == '\'') return error("Empty character constant"); if (n == '\\') switch (s.next()) { case 'n' : n = '\n'; break; case '\\' : n = '\\'; break; default : return error("Unknown escape sequence \\", s.peek()); } if (s.next() != '\'') return error("Multi-character constant"); s.advance(); return make_token(TokenName::INTEGER, n); } Token string_lit () { string text = ""; while (s.next() != '"') switch (s.peek()) { case '\\' : switch (s.next()) { case 'n' : text += '\n'; continue; case '\\' : text += '\\'; continue; default : return error("Unknown escape sequence \\", s.peek()); } case '\n' : return error("End-of-line while scanning string literal." " Closing string character not found before end-of-line."); case '\0' : return error("End-of-file while scanning string literal." " Closing string character not found."); default : text += s.peek(); } s.advance(); return make_token(TokenName::STRING, text); } static inline bool is_id_start (char c) { return isalpha(static_cast<unsigned char>(c)) || c == '_'; } static inline bool is_id_end (char c) { return isalnum(static_cast<unsigned char>(c)) || c == '_'; } static inline bool is_digit (char c) { return isdigit(static_cast<unsigned char>(c)); } Token identifier () { string text (1, s.peek()); while (is_id_end(s.next())) text += s.peek(); auto i = keywords.find(text); if (i != keywords.end()) return make_token(i->second); return make_token(TokenName::IDENTIFIER, text); } Token integer_lit () { while (is_digit(s.next())); if (is_id_start(s.peek())) return error("Invalid number. Starts like a number, but ends in non-numeric characters."); int n; auto r = from_chars(pre_state.pos, s.pos, n); if (r.ec == errc::result_out_of_range) return error("Number exceeds maximum value"); return make_token(TokenName::INTEGER, n); } }; // class Lexer const map<string, TokenName> Lexer::keywords = { {"else", TokenName::KEYWORD_ELSE}, {"if", TokenName::KEYWORD_IF}, {"print", TokenName::KEYWORD_PRINT}, {"putc", TokenName::KEYWORD_PUTC}, {"while", TokenName::KEYWORD_WHILE} }; int main (int argc, char* argv[]) { string in = (argc > 1) ? argv[1] : "stdin"; string out = (argc > 2) ? argv[2] : "stdout"; with_IO(in, out, [](string input) { Lexer lexer {input.data()}; string s = "Location Token name Value\n" "--------------------------------------\n"; while (lexer.has_more()) s += to_string(lexer.next_token()); return s; }); }
Conjugate transpose
C++
Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M. ::: (M^H)_{ji} = \overline{M_{ij}} This means that row j, column i of the conjugate transpose equals the complex conjugate of row i, column j of the original matrix. In the next list, M must also be a square matrix. * A Hermitian matrix equals its own conjugate transpose: M^H = M. * A multiplication with its conjugate transpose: M^HM = MM^H. * A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix. ;Task: Given some matrix of complex numbers, find its conjugate transpose. Also determine if the matrix is a: ::* Hermitian matrix, ::* normal matrix, or ::* unitary matrix. ;See also: * MathWorld entry: conjugate transpose * MathWorld entry: Hermitian matrix * MathWorld entry: normal matrix * MathWorld entry: unitary matrix
#include <cassert> #include <cmath> #include <complex> #include <iomanip> #include <iostream> #include <sstream> #include <vector> template <typename scalar_type> class complex_matrix { public: using element_type = std::complex<scalar_type>; complex_matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} complex_matrix(size_t rows, size_t columns, element_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} complex_matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<element_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const element_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } element_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } friend bool operator==(const complex_matrix& a, const complex_matrix& b) { return a.rows_ == b.rows_ && a.columns_ == b.columns_ && a.elements_ == b.elements_; } private: size_t rows_; size_t columns_; std::vector<element_type> elements_; }; template <typename scalar_type> complex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a, const complex_matrix<scalar_type>& b) { assert(a.columns() == b.rows()); size_t arows = a.rows(); size_t bcolumns = b.columns(); size_t n = a.columns(); complex_matrix<scalar_type> c(arows, bcolumns); for (size_t i = 0; i < arows; ++i) { for (size_t j = 0; j < n; ++j) { for (size_t k = 0; k < bcolumns; ++k) c(i, k) += a(i, j) * b(j, k); } } return c; } template <typename scalar_type> complex_matrix<scalar_type> conjugate_transpose(const complex_matrix<scalar_type>& a) { size_t rows = a.rows(), columns = a.columns(); complex_matrix<scalar_type> b(columns, rows); for (size_t i = 0; i < columns; i++) { for (size_t j = 0; j < rows; j++) { b(i, j) = std::conj(a(j, i)); } } return b; } template <typename scalar_type> std::string to_string(const std::complex<scalar_type>& c) { std::ostringstream out; const int precision = 6; out << std::fixed << std::setprecision(precision); out << std::setw(precision + 3) << c.real(); if (c.imag() > 0) out << " + " << std::setw(precision + 2) << c.imag() << 'i'; else if (c.imag() == 0) out << " + " << std::setw(precision + 2) << 0.0 << 'i'; else out << " - " << std::setw(precision + 2) << -c.imag() << 'i'; return out.str(); } template <typename scalar_type> void print(std::ostream& out, const complex_matrix<scalar_type>& a) { size_t rows = a.rows(), columns = a.columns(); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < columns; ++column) { if (column > 0) out << ' '; out << to_string(a(row, column)); } out << '\n'; } } template <typename scalar_type> bool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; return matrix == conjugate_transpose(matrix); } template <typename scalar_type> bool is_normal_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; auto c = conjugate_transpose(matrix); return product(c, matrix) == product(matrix, c); } bool is_equal(const std::complex<double>& a, double b) { constexpr double e = 1e-15; return std::abs(a.imag()) < e && std::abs(a.real() - b) < e; } template <typename scalar_type> bool is_identity_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; size_t rows = matrix.rows(); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < rows; ++j) { if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0))) return false; } } return true; } template <typename scalar_type> bool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; auto c = conjugate_transpose(matrix); auto p = product(c, matrix); return is_identity_matrix(p) && p == product(matrix, c); } template <typename scalar_type> void test(const complex_matrix<scalar_type>& matrix) { std::cout << "Matrix:\n"; print(std::cout, matrix); std::cout << "Conjugate transpose:\n"; print(std::cout, conjugate_transpose(matrix)); std::cout << std::boolalpha; std::cout << "Hermitian: " << is_hermitian_matrix(matrix) << '\n'; std::cout << "Normal: " << is_normal_matrix(matrix) << '\n'; std::cout << "Unitary: " << is_unitary_matrix(matrix) << '\n'; } int main() { using matrix = complex_matrix<double>; matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}}, {{2, -1}, {3, 0}, {0, 1}}, {{4, 0}, {0, -1}, {1, 0}}}); double n = std::sqrt(0.5); matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}}, {{0, -n}, {0, n}, {0, 0}}, {{0, 0}, {0, 0}, {0, 1}}}); matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}}, {{2, -1}, {4, 1}, {0, 0}}, {{7, -5}, {1, -4}, {1, 0}}}); test(matrix1); std::cout << '\n'; test(matrix2); std::cout << '\n'; test(matrix3); return 0; }
Continued fraction
C++
A number may be represented as a continued fraction (see Mathworld for more information) as follows: :a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}} The 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: For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1. :\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}} For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1. :e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}} For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2. :\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}} ;See also: :* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
#include <iomanip> #include <iostream> #include <tuple> typedef std::tuple<double,double> coeff_t; // coefficients type typedef coeff_t (*func_t)(int); // callback function type double calc(func_t func, int n) { double a, b, temp = 0; for (; n > 0; --n) { std::tie(a, b) = func(n); temp = b / (a + temp); } std::tie(a, b) = func(0); return a + temp; } coeff_t sqrt2(int n) { return coeff_t(n > 0 ? 2 : 1, 1); } coeff_t napier(int n) { return coeff_t(n > 0 ? n : 2, n > 1 ? n - 1 : 1); } coeff_t pi(int n) { return coeff_t(n > 0 ? 6 : 3, (2 * n - 1) * (2 * n - 1)); } int main() { std::streamsize old_prec = std::cout.precision(15); // set output digits std::cout << calc(sqrt2, 20) << '\n' << calc(napier, 15) << '\n' << calc(pi, 10000) << '\n' << std::setprecision(old_prec); // reset precision }
Continued fraction/Arithmetic/Construct from rational number
C++
To understand this task in context please see [[Continued fraction arithmetic]] The 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_1 is the numerator :N_2 is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To 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. Demonstrate the function by outputing the continued fraction for: : 1/2 : 3 : 23/8 : 13/11 : 22/7 : -151/77 \sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you: : 14142,10000 : 141421,100000 : 1414214,1000000 : 14142136,10000000 Try : : 31,10 : 314,100 : 3142,1000 : 31428,10000 : 314285,100000 : 3142857,1000000 : 31428571,10000000 : 314285714,100000000 Observe 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.
#include <iostream> /* Interface for all Continued Fractions Nigel Galloway, February 9th., 2013. */ class ContinuedFraction { public: virtual const int nextTerm(){}; virtual const bool moreTerms(){}; }; /* Create a continued fraction from a rational number Nigel Galloway, February 9th., 2013. */ class r2cf : public ContinuedFraction { private: int n1, n2; public: r2cf(const int numerator, const int denominator): n1(numerator), n2(denominator){} const int nextTerm() { const int thisTerm = n1/n2; const int t2 = n2; n2 = n1 - thisTerm * n2; n1 = t2; return thisTerm; } const bool moreTerms() {return fabs(n2) > 0;} }; /* Generate a continued fraction for sqrt of 2 Nigel Galloway, February 9th., 2013. */ class SQRT2 : public ContinuedFraction { private: bool first=true; public: const int nextTerm() {if (first) {first = false; return 1;} else return 2;} const bool moreTerms() {return true;} };
Continued fraction/Arithmetic/G(matrix ng, continued fraction n)
C++
This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG: : \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} I may perform perform the following operations: :Input the next term of N1 :Output a term of the continued fraction resulting from the operation. I 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. When I input a term t my internal state: \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} is transposed thus \begin{bmatrix} a + a_1 * t & a_1 \\ b + b_1 * t & b_1 \end{bmatrix} When I output a term t my internal state: \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} is transposed thus \begin{bmatrix} b_1 & b \\ a_1 - b_1 * t & a - b * t \end{bmatrix} When I need a term t but there are no more my internal state: \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} is transposed thus \begin{bmatrix} a_1 & a_1 \\ b_1 & b_1 \end{bmatrix} I am done when b1 and b are zero. Demonstrate your solution by calculating: :[1;5,2] + 1/2 :[3;7] + 1/2 :[3;7] divided by 4 Using 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. The 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.
/* Interface for all matrixNG classes Nigel Galloway, February 10th., 2013. */ class matrixNG { private: virtual void consumeTerm(){} virtual void consumeTerm(int n){} virtual const bool needTerm(){} protected: int cfn = 0, thisTerm; bool haveTerm = false; friend class NG; }; /* Implement the babyNG matrix Nigel Galloway, February 10th., 2013. */ class NG_4 : public matrixNG { private: int a1, a, b1, b, t; const bool needTerm() { if (b1==0 and b==0) return false; if (b1==0 or b==0) return true; else thisTerm = a/b; if (thisTerm==(int)(a1/b1)){ t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; haveTerm=true; return false; } return true; } void consumeTerm(){a=a1; b=b1;} void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;} public: NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){} }; /* Implement a Continued Fraction which returns the result of an arithmetic operation on 1 or more Continued Fractions (Currently 1 or 2). Nigel Galloway, February 10th., 2013. */ class NG : public ContinuedFraction { private: matrixNG* ng; ContinuedFraction* n[2]; public: NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;} NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;} const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;} const bool moreTerms(){ while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm(); return ng->haveTerm; } };
Convert seconds to compound duration
C++11
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrate that it passes the following three test-cases: '''''Test Cases''''' :::::{| class="wikitable" |- ! input number ! output string |- | 7259 | 2 hr, 59 sec |- | 86400 | 1 d |- | 6000000 | 9 wk, 6 d, 10 hr, 40 min |} '''''Details''''' The following five units should be used: :::::{| class="wikitable" |- ! unit ! suffix used in output ! conversion |- | week | wk | 1 week = 7 days |- | day | d | 1 day = 24 hours |- | hour | hr | 1 hour = 60 minutes |- | minute | min | 1 minute = 60 seconds |- | second | sec | |} However, '''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"). Give 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) Mimic 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).
#include <iostream> #include <vector> using entry = std::pair<int, const char*>; void print(const std::vector<entry>& entries, std::ostream& out = std::cout) { bool first = true; for(const auto& e: entries) { if(!first) out << ", "; first = false; out << e.first << " " << e.second; } out << '\n'; } std::vector<entry> convert(int seconds) { static const entry time_table[] = { {7*24*60*60, "wk"}, {24*60*60, "d"}, {60*60, "hr"}, {60, "min"}, {1, "sec"} }; std::vector<entry> result; for(const auto& e: time_table) { int time = seconds / e.first; if(time != 0) result.emplace_back(time, e.second); seconds %= e.first; } return result; } int main() { std::cout << " 7259 sec is "; print(convert( 7259)); std::cout << " 86400 sec is "; print(convert( 86400)); std::cout << "6000000 sec is "; print(convert(6000000)); }
Copy stdin to stdout
C++
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.
#include <iostream> #include <iterator> int main() { using namespace std; noskipws(cin); copy( istream_iterator<char>(cin), istream_iterator<char>(), ostream_iterator<char>(cout) ); return 0; }
Count the coins
C++
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and 5 pennies :::# A nickel and 10 pennies :::# 15 pennies ;Task: How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents). ;Optional: Less 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? (Note: the answer is larger than 232). ;References: * an algorithm from the book ''Structure and Interpretation of Computer Programs''. * an article in the algorithmist. * Change-making problem on Wikipedia.
#include <iostream> #include <stack> #include <vector> struct DataFrame { int sum; std::vector<int> coins; std::vector<int> avail_coins; }; int main() { std::stack<DataFrame> s; s.push({ 100, {}, { 25, 10, 5, 1 } }); int ways = 0; while (!s.empty()) { DataFrame top = s.top(); s.pop(); if (top.sum < 0) continue; if (top.sum == 0) { ++ways; continue; } if (top.avail_coins.empty()) continue; DataFrame d = top; d.sum -= top.avail_coins[0]; d.coins.push_back(top.avail_coins[0]); s.push(d); d = top; d.avail_coins.erase(std::begin(d.avail_coins)); s.push(d); } std::cout << ways << std::endl; return 0; }
Create an HTML table
C++
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * 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. * The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. * The numbers should be aligned in the same fashion for all columns.
#include <fstream> #include <boost/array.hpp> #include <string> #include <cstdlib> #include <ctime> #include <sstream> void makeGap( int gap , std::string & text ) { for ( int i = 0 ; i < gap ; i++ ) text.append( " " ) ; } int main( ) { boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ; int headgap = 3 ; int bodygap = 3 ; int tablegap = 6 ; int rowgap = 9 ; std::string tabletext( "<html>\n" ) ; makeGap( headgap , tabletext ) ; tabletext += "<head></head>\n" ; makeGap( bodygap , tabletext ) ; tabletext += "<body>\n" ; makeGap( tablegap , tabletext ) ; tabletext += "<table>\n" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "<thead align=\"right\">\n" ; makeGap( tablegap, tabletext ) ; tabletext += "<tr><th></th>" ; for ( int i = 0 ; i < 3 ; i++ ) { tabletext += "<td>" ; tabletext += *(chars.begin( ) + i ) ; tabletext += "</td>" ; } tabletext += "</tr>\n" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "</thead>" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "<tbody align=\"right\">\n" ; srand( time( 0 ) ) ; for ( int row = 0 ; row < 5 ; row++ ) { makeGap( rowgap , tabletext ) ; std::ostringstream oss ; tabletext += "<tr><td>" ; oss << row ; tabletext += oss.str( ) ; for ( int col = 0 ; col < 3 ; col++ ) { oss.str( "" ) ; int randnumber = rand( ) % 10000 ; oss << randnumber ; tabletext += "<td>" ; tabletext.append( oss.str( ) ) ; tabletext += "</td>" ; } tabletext += "</tr>\n" ; } makeGap( tablegap + 1 , tabletext ) ; tabletext += "</tbody>\n" ; makeGap( tablegap , tabletext ) ; tabletext += "</table>\n" ; makeGap( bodygap , tabletext ) ; tabletext += "</body>\n" ; tabletext += "</html>\n" ; std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ; htmltable << tabletext ; htmltable.close( ) ; return 0 ; }
Currying
C++
{{Wikipedia|Currying}} ;Task: Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
Currying may be achieved in [[C++]] using the [[wp:Standard Template Library|Standard Template Library]] function object adapters (<code>binder1st</code> and <code>binder2nd</code>), and more generically using the [[wp:Boost library|Boost]] <code>bind</code> mechanism.
Curzon numbers
C++
A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''. '''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'''. ''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.'' Generalized Curzon numbers only exist for even base integers. ;Task * Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''. ;Stretch * Find and show the '''one thousandth'''. ;See also ;* Numbers Aplenty - Curzon numbers ;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers) ''and even though it is not specifically mentioned that they are Curzon numbers:'' ;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; } bool is_curzon(uint64_t n, uint64_t k) { const uint64_t r = k * n; return modpow(k, n, r + 1) == r; } int main() { for (uint64_t k = 2; k <= 10; k += 2) { std::cout << "Curzon numbers with base " << k << ":\n"; uint64_t count = 0, n = 1; for (; count < 50; ++n) { if (is_curzon(n, k)) { std::cout << std::setw(4) << n << (++count % 10 == 0 ? '\n' : ' '); } } for (;;) { if (is_curzon(n, k)) ++count; if (count == 1000) break; ++n; } std::cout << "1000th Curzon number with base " << k << ": " << n << "\n\n"; } return 0; }
Cut a rectangle
C++ from Java
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. [[file:rect-cut.svg]] Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts. Possibly related task: [[Maze generation]] for depth-first search.
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) { auto it = row.cbegin(); auto end = row.cend(); std::cout << '['; if (it != end) { std::cout << *it; it = std::next(it); } while (it != end) { std::cout << ", " << *it; it = std::next(it); } std::cout << "]\n"; } } void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) { return; } std::vector<std::vector<int>> grid(h, std::vector<int>(w)); std::stack<int> stack; int half = (w * h) / 2; long bits = (long)pow(2, half) - 1; for (; bits > 0; bits -= 2) { for (int i = 0; i < half; i++) { int r = i / w; int c = i % w; grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0; grid[h - r - 1][w - c - 1] = 1 - grid[r][c]; } stack.push(0); grid[0][0] = 2; int count = 1; while (!stack.empty()) { int pos = stack.top(); stack.pop(); int r = pos / w; int c = pos % w; for (auto dir : DIRS) { int nextR = r + dir.first; int nextC = c + dir.second; if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) { if (grid[nextR][nextC] == 1) { stack.push(nextR * w + nextC); grid[nextR][nextC] = 2; count++; } } } } if (count == half) { printResult(grid); std::cout << '\n'; } } } int main() { cutRectangle(2, 2); cutRectangle(4, 3); return 0; }
Cyclotomic polynomial
C++ from Java
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. ;Task: * Find and print the first 30 cyclotomic polynomials. * Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient. ;See also * Wikipedia article, Cyclotomic polynomial, showing ways to calculate them. * The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.
#include <algorithm> #include <iostream> #include <initializer_list> #include <map> #include <vector> const int MAX_ALL_FACTORS = 100000; const int algorithm = 2; int divisions = 0; //Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage. class Term { private: long m_coefficient; long m_exponent; public: Term(long c, long e) : m_coefficient(c), m_exponent(e) { // empty } Term(const Term &t) : m_coefficient(t.m_coefficient), m_exponent(t.m_exponent) { // empty } long coefficient() const { return m_coefficient; } long degree() const { return m_exponent; } Term operator -() const { return { -m_coefficient, m_exponent }; } Term operator *(const Term &rhs) const { return { m_coefficient * rhs.m_coefficient, m_exponent + rhs.m_exponent }; } Term operator +(const Term &rhs) const { if (m_exponent != rhs.m_exponent) { throw std::runtime_error("Exponents not equal"); } return { m_coefficient + rhs.m_coefficient, m_exponent }; } friend std::ostream &operator<<(std::ostream &, const Term &); }; std::ostream &operator<<(std::ostream &os, const Term &t) { if (t.m_coefficient == 0) { return os << '0'; } if (t.m_exponent == 0) { return os << t.m_coefficient; } if (t.m_coefficient == 1) { if (t.m_exponent == 1) { return os << 'x'; } return os << "x^" << t.m_exponent; } if (t.m_coefficient == -1) { if (t.m_exponent == 1) { return os << "-x"; } return os << "-x^" << t.m_exponent; } if (t.m_exponent == 1) { return os << t.m_coefficient << 'x'; } return os << t.m_coefficient << "x^" << t.m_exponent; } class Polynomial { public: std::vector<Term> polynomialTerms; Polynomial() { polynomialTerms.push_back({ 0, 0 }); } Polynomial(std::initializer_list<int> values) { if (values.size() % 2 != 0) { throw std::runtime_error("Length must be even."); } bool ready = false; long t; for (auto v : values) { if (ready) { polynomialTerms.push_back({ t, v }); } else { t = v; } ready = !ready; } std::sort( polynomialTerms.begin(), polynomialTerms.end(), [](const Term &t, const Term &u) { return u.degree() < t.degree(); } ); } Polynomial(const std::vector<Term> &termList) { if (termList.size() == 0) { polynomialTerms.push_back({ 0, 0 }); } else { for (auto t : termList) { if (t.coefficient() != 0) { polynomialTerms.push_back(t); } } if (polynomialTerms.size() == 0) { polynomialTerms.push_back({ 0, 0 }); } std::sort( polynomialTerms.begin(), polynomialTerms.end(), [](const Term &t, const Term &u) { return u.degree() < t.degree(); } ); } } Polynomial(const Polynomial &p) : Polynomial(p.polynomialTerms) { // empty } long leadingCoefficient() const { return polynomialTerms[0].coefficient(); } long degree() const { return polynomialTerms[0].degree(); } bool hasCoefficientAbs(int coeff) { for (auto term : polynomialTerms) { if (abs(term.coefficient()) == coeff) { return true; } } return false; } Polynomial operator+(const Term &term) const { std::vector<Term> termList; bool added = false; for (size_t index = 0; index < polynomialTerms.size(); index++) { auto currentTerm = polynomialTerms[index]; if (currentTerm.degree() == term.degree()) { added = true; if (currentTerm.coefficient() + term.coefficient() != 0) { termList.push_back(currentTerm + term); } } else { termList.push_back(currentTerm); } } if (!added) { termList.push_back(term); } return Polynomial(termList); } Polynomial operator*(const Term &term) const { std::vector<Term> termList; for (size_t index = 0; index < polynomialTerms.size(); index++) { auto currentTerm = polynomialTerms[index]; termList.push_back(currentTerm * term); } return Polynomial(termList); } Polynomial operator+(const Polynomial &p) const { std::vector<Term> termList; int thisCount = polynomialTerms.size(); int polyCount = p.polynomialTerms.size(); while (thisCount > 0 || polyCount > 0) { if (thisCount == 0) { auto polyTerm = p.polynomialTerms[polyCount - 1]; termList.push_back(polyTerm); polyCount--; } else if (polyCount == 0) { auto thisTerm = polynomialTerms[thisCount - 1]; termList.push_back(thisTerm); thisCount--; } else { auto polyTerm = p.polynomialTerms[polyCount - 1]; auto thisTerm = polynomialTerms[thisCount - 1]; if (thisTerm.degree() == polyTerm.degree()) { auto t = thisTerm + polyTerm; if (t.coefficient() != 0) { termList.push_back(t); } thisCount--; polyCount--; } else if (thisTerm.degree() < polyTerm.degree()) { termList.push_back(thisTerm); thisCount--; } else { termList.push_back(polyTerm); polyCount--; } } } return Polynomial(termList); } Polynomial operator/(const Polynomial &v) { divisions++; Polynomial q; Polynomial r(*this); long lcv = v.leadingCoefficient(); long dv = v.degree(); while (r.degree() >= v.degree()) { long lcr = r.leadingCoefficient(); long s = lcr / lcv; Term term(s, r.degree() - dv); q = q + term; r = r + v * -term; } return q; } friend std::ostream &operator<<(std::ostream &, const Polynomial &); }; std::ostream &operator<<(std::ostream &os, const Polynomial &p) { auto it = p.polynomialTerms.cbegin(); auto end = p.polynomialTerms.cend(); if (it != end) { os << *it; it = std::next(it); } while (it != end) { if (it->coefficient() > 0) { os << " + " << *it; } else { os << " - " << -*it; } it = std::next(it); } return os; } std::vector<int> getDivisors(int number) { std::vector<int> divisiors; long root = (long)sqrt(number); for (int i = 1; i <= root; i++) { if (number % i == 0) { divisiors.push_back(i); int div = number / i; if (div != i && div != number) { divisiors.push_back(div); } } } return divisiors; } std::map<int, std::map<int, int>> allFactors; std::map<int, int> getFactors(int number) { if (allFactors.find(number) != allFactors.end()) { return allFactors[number]; } std::map<int, int> factors; if (number % 2 == 0) { auto factorsDivTwo = getFactors(number / 2); factors.insert(factorsDivTwo.begin(), factorsDivTwo.end()); if (factors.find(2) != factors.end()) { factors[2]++; } else { factors.insert(std::make_pair(2, 1)); } if (number < MAX_ALL_FACTORS) { allFactors.insert(std::make_pair(number, factors)); } return factors; } long root = (long)sqrt(number); long i = 3; while (i <= root) { if (number % i == 0) { auto factorsDivI = getFactors(number / i); factors.insert(factorsDivI.begin(), factorsDivI.end()); if (factors.find(i) != factors.end()) { factors[i]++; } else { factors.insert(std::make_pair(i, 1)); } if (number < MAX_ALL_FACTORS) { allFactors.insert(std::make_pair(number, factors)); } return factors; } i += 2; } factors.insert(std::make_pair(number, 1)); if (number < MAX_ALL_FACTORS) { allFactors.insert(std::make_pair(number, factors)); } return factors; } std::map<int, Polynomial> COMPUTED; Polynomial cyclotomicPolynomial(int n) { if (COMPUTED.find(n) != COMPUTED.end()) { return COMPUTED[n]; } if (n == 1) { // Polynomial: x - 1 Polynomial p({ 1, 1, -1, 0 }); COMPUTED.insert(std::make_pair(1, p)); return p; } auto factors = getFactors(n); if (factors.find(n) != factors.end()) { // n prime std::vector<Term> termList; for (int index = 0; index < n; index++) { termList.push_back({ 1, index }); } Polynomial cyclo(termList); COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else if (factors.size() == 2 && factors.find(2) != factors.end() && factors[2] == 1 && factors.find(n / 2) != factors.end() && factors[n / 2] == 1) { // n = 2p int prime = n / 2; std::vector<Term> termList; int coeff = -1; for (int index = 0; index < prime; index++) { coeff *= -1; termList.push_back({ coeff, index }); } Polynomial cyclo(termList); COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else if (factors.size() == 1 && factors.find(2) != factors.end()) { // n = 2^h int h = factors[2]; std::vector<Term> termList; termList.push_back({ 1, (int)pow(2, h - 1) }); termList.push_back({ 1, 0 }); Polynomial cyclo(termList); COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else if (factors.size() == 1 && factors.find(n) != factors.end()) { // n = p^k int p = 0; int k = 0; for (auto iter = factors.begin(); iter != factors.end(); ++iter) { p = iter->first; k = iter->second; } std::vector<Term> termList; for (int index = 0; index < p; index++) { termList.push_back({ 1, index * (int)pow(p, k - 1) }); } Polynomial cyclo(termList); COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else if (factors.size() == 2 && factors.find(2) != factors.end()) { // n = 2^h * p^k int p = 0; for (auto iter = factors.begin(); iter != factors.end(); ++iter) { if (iter->first != 2) { p = iter->first; } } std::vector<Term> termList; int coeff = -1; int twoExp = (int)pow(2, factors[2] - 1); int k = factors[p]; for (int index = 0; index < p; index++) { coeff *= -1; termList.push_back({ coeff, index * twoExp * (int)pow(p, k - 1) }); } Polynomial cyclo(termList); COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else if (factors.find(2) != factors.end() && ((n / 2) % 2 == 1) && (n / 2) > 1) { // CP(2m)[x] = CP(-m)[x], n odd integer > 1 auto cycloDiv2 = cyclotomicPolynomial(n / 2); std::vector<Term> termList; for (auto term : cycloDiv2.polynomialTerms) { if (term.degree() % 2 == 0) { termList.push_back(term); } else { termList.push_back(-term); } } Polynomial cyclo(termList); COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } // General Case if (algorithm == 0) { // slow - uses basic definition auto divisors = getDivisors(n); // Polynomial: (x^n - 1) Polynomial cyclo({ 1, n, -1, 0 }); for (auto i : divisors) { auto p = cyclotomicPolynomial(i); cyclo = cyclo / p; } COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else if (algorithm == 1) { // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor auto divisors = getDivisors(n); int maxDivisor = INT_MIN; for (auto div : divisors) { maxDivisor = std::max(maxDivisor, div); } std::vector<int> divisorExceptMax; for (auto div : divisors) { if (maxDivisor % div != 0) { divisorExceptMax.push_back(div); } } // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor auto cyclo = Polynomial({ 1, n, -1, 0 }) / Polynomial({ 1, maxDivisor, -1, 0 }); for (int i : divisorExceptMax) { auto p = cyclotomicPolynomial(i); cyclo = cyclo / p; } COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else if (algorithm == 2) { // Fastest // Let p ; q be primes such that p does not divide n, and q q divides n. // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x] int m = 1; auto cyclo = cyclotomicPolynomial(m); std::vector<int> primes; for (auto iter = factors.begin(); iter != factors.end(); ++iter) { primes.push_back(iter->first); } std::sort(primes.begin(), primes.end()); for (auto prime : primes) { // CP(m)[x] auto cycloM = cyclo; // Compute CP(m)[x^p]. std::vector<Term> termList; for (auto t : cycloM.polynomialTerms) { termList.push_back({ t.coefficient(), t.degree() * prime }); } cyclo = Polynomial(termList) / cycloM; m = m * prime; } // Now, m is the largest square free divisor of n int s = n / m; // Compute CP(n)[x] = CP(m)[x^s] std::vector<Term> termList; for (auto t : cyclo.polynomialTerms) { termList.push_back({ t.coefficient(), t.degree() * s }); } cyclo = Polynomial(termList); COMPUTED.insert(std::make_pair(n, cyclo)); return cyclo; } else { throw std::runtime_error("Invalid algorithm"); } } int main() { // initialization std::map<int, int> factors; factors.insert(std::make_pair(2, 1)); allFactors.insert(std::make_pair(2, factors)); // rest of main std::cout << "Task 1: cyclotomic polynomials for n <= 30:\n"; for (int i = 1; i <= 30; i++) { auto p = cyclotomicPolynomial(i); std::cout << "CP[" << i << "] = " << p << '\n'; } std::cout << "Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\n"; int n = 0; for (int i = 1; i <= 10; i++) { while (true) { n++; auto cyclo = cyclotomicPolynomial(n); if (cyclo.hasCoefficientAbs(i)) { std::cout << "CP[" << n << "] has coefficient with magnitude = " << i << '\n'; n--; break; } } } return 0; }
Damm algorithm
C++ from C#
The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. ;Task: Verify the checksum, stored as last digit of an input.
#include <string> #include <cstdio> inline constexper int TABLE[][10] = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; [[nodiscard]] bool damm(std::string s) noexcept { int interim = 0; for (const auto c : s) { interim = TABLE[interim][c - '0']; } return interim == 0; } int main() { for (const auto num : { 5724, 5727, 112946, 112949 }) { if (damm(std::to_string(num))) { std::printf("%6d is valid\n", num); } else std::printf("%6d is invalid\n", num); } }
De Bruijn sequences
C++ from D
{{DISPLAYTITLE:de Bruijn sequences}} The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn. A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized unless 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 capitalized. In combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on a size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every possible length-''n'' string (computer science, formal theory) on ''A'' occurs exactly once as a contiguous substring. Such a sequence is denoted by ''B''(''k'', ''n'') and has length ''k''''n'', which is also the number of distinct substrings of length ''n'' on ''A''; de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1) / kn distinct de Bruijn sequences ''B''(''k'', ''n''). ;Task: For this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on a PIN-like code lock that does not have an "enter" key and accepts the last ''n'' digits entered. Note: automated teller machines (ATMs) used to work like this, but their software has been updated to not allow a brute-force attack. ;Example: A digital door lock with a 4-digit code would have ''B'' (10, 4) solutions, with a length of '''10,000''' (digits). Therefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to open the lock. Trying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses. ;Task requirements: :* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code. :::* Show the length of the generated de Bruijn sequence. :::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page). :::* Show the first and last '''130''' digits of the de Bruijn sequence. :* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence. :::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros). :* Reverse the de Bruijn sequence. :* Again, perform the (above) verification test. :* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence. :::* Perform the verification test (again). There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly. The verification processes should list any and all missing PIN codes.) Show all output here, on this page. ;References: :* Wikipedia entry: de Bruijn sequence. :* MathWorld entry: de Bruijn sequence. :* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
#include <algorithm> #include <functional> #include <iostream> #include <iterator> #include <string> #include <sstream> #include <vector> typedef unsigned char byte; std::string deBruijn(int k, int n) { std::vector<byte> a(k * n, 0); std::vector<byte> seq; std::function<void(int, int)> db; db = [&](int t, int p) { if (t > n) { if (n % p == 0) { for (int i = 1; i < p + 1; i++) { seq.push_back(a[i]); } } } else { a[t] = a[t - p]; db(t + 1, p); auto j = a[t - p] + 1; while (j < k) { a[t] = j & 0xFF; db(t + 1, t); j++; } } }; db(1, 1); std::string buf; for (auto i : seq) { buf.push_back('0' + i); } return buf + buf.substr(0, n - 1); } bool allDigits(std::string s) { for (auto c : s) { if (c < '0' || '9' < c) { return false; } } return true; } void validate(std::string db) { auto le = db.size(); std::vector<int> found(10000, 0); std::vector<std::string> errs; // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for (size_t i = 0; i < le - 3; i++) { auto s = db.substr(i, 4); if (allDigits(s)) { auto n = stoi(s); found[n]++; } } for (int i = 0; i < 10000; i++) { if (found[i] == 0) { std::stringstream ss; ss << " PIN number " << i << " missing"; errs.push_back(ss.str()); } else if (found[i] > 1) { std::stringstream ss; ss << " PIN number " << i << " occurs " << found[i] << " times"; errs.push_back(ss.str()); } } if (errs.empty()) { std::cout << " No errors found\n"; } else { auto pl = (errs.size() == 1) ? "" : "s"; std::cout << " " << errs.size() << " error" << pl << " found:\n"; for (auto e : errs) { std::cout << e << '\n'; } } } int main() { std::ostream_iterator<byte> oi(std::cout, ""); auto db = deBruijn(10, 4); std::cout << "The length of the de Bruijn sequence is " << db.size() << "\n\n"; std::cout << "The first 130 digits of the de Bruijn sequence are: "; std::copy_n(db.cbegin(), 130, oi); std::cout << "\n\nThe last 130 digits of the de Bruijn sequence are: "; std::copy(db.cbegin() + (db.size() - 130), db.cend(), oi); std::cout << "\n"; std::cout << "\nValidating the de Bruijn sequence:\n"; validate(db); std::cout << "\nValidating the reversed de Bruijn sequence:\n"; auto rdb = db; std::reverse(rdb.begin(), rdb.end()); validate(rdb); auto by = db; by[4443] = '.'; std::cout << "\nValidating the overlaid de Bruijn sequence:\n"; validate(by); return 0; }
Deepcopy
C++
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This 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. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: * Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. * Any limitations of the method. * That the structure and its copy are different. * Suitable links to external documentation for common libraries.
#include <array> #include <iostream> #include <list> #include <map> #include <vector> int main() { // make a nested structure to copy - a map of arrays containing vectors of strings auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"}; auto myColors = std::vector<std::string>{"red", "green", "blue"}; auto myArray = std::array<std::vector<std::string>, 2>{myNumbers, myColors}; auto myMap = std::map<int, decltype(myArray)> {{3, myArray}, {7, myArray}}; // make a deep copy of the map auto mapCopy = myMap; // modify the copy mapCopy[3][0][1] = "2"; mapCopy[7][1][2] = "purple"; std::cout << "the original values:\n"; std::cout << myMap[3][0][1] << "\n"; std::cout << myMap[7][1][2] << "\n\n"; std::cout << "the modified copy:\n"; std::cout << mapCopy[3][0][1] << "\n"; std::cout << mapCopy[7][1][2] << "\n"; }
Department numbers
C++
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
#include <iostream> #include <iomanip> int main( int argc, char* argv[] ) { int sol = 1; std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n"; for( int f = 1; f < 8; f++ ) { for( int p = 1; p < 8; p++ ) { for( int s = 1; s < 8; s++ ) { if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) { std::cout << "SOLUTION #" << std::setw( 2 ) << sol++ << std::setw( 2 ) << ":\t" << std::setw( 2 ) << f << "\t\t " << std::setw( 3 ) << p << "\t\t" << std::setw( 6 ) << s << "\n"; } } } } return 0; }
Descending primes
C++ from C#
Generate and show all primes with strictly descending decimal digits. ;See also ;* OEIS:A052014 - Primes with distinct digits in descending order ;Related: *[[Ascending primes]]
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
Detect division by zero
C++
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
#include<iostream> #include<csignal> /* for signal */ #include<cstdlib> using namespace std; void fpe_handler(int signal) { cerr << "Floating Point Exception: division by zero" << endl; exit(signal); } int main() { // Register floating-point exception handler. signal(SIGFPE, fpe_handler); int a = 1; int b = 0; cout << a/b << endl; return 0; }
Determinant and permanent
C++ from Java
permanent of the matrix. The determinant is given by :: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i} while the permanent is given by :: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i} In 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.) More 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. ;Related task: * [[Permutations by swapping]]
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
Determine if a string has all the same characters
C++
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
#include <iostream> #include <string> void all_characters_are_the_same(const std::string& str) { size_t len = str.length(); std::cout << "input: \"" << str << "\", length: " << len << '\n'; if (len > 0) { char ch = str[0]; for (size_t i = 1; i < len; ++i) { if (str[i] != ch) { std::cout << "Not all characters are the same.\n"; std::cout << "Character '" << str[i] << "' (hex " << std::hex << static_cast<unsigned int>(str[i]) << ") at position " << std::dec << i + 1 << " is not the same as '" << ch << "'.\n\n"; return; } } } std::cout << "All characters are the same.\n\n"; } int main() { all_characters_are_the_same(""); all_characters_are_the_same(" "); all_characters_are_the_same("2"); all_characters_are_the_same("333"); all_characters_are_the_same(".55"); all_characters_are_the_same("tttTTT"); all_characters_are_the_same("4444 444k"); return 0; }
Determine if a string has all unique characters
C++
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as unique ::* process the strings from left-to-right ::* if unique, display a message saying such ::* if not unique, then: ::::* display a message saying such ::::* display what character is duplicated ::::* only the 1st non-unique character need be displayed ::::* display where "both" duplicated characters are in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the duplicated character Use (at least) these five test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 1 which is a single period ('''.''') :::* a string of length 6 which contains: '''abcABC''' :::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX''' :::* a string of length 36 which ''doesn't'' contain the letter "oh": :::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ''' Show all output here on this page.
#include <iostream> #include <string> void string_has_repeated_character(const std::string& str) { size_t len = str.length(); std::cout << "input: \"" << str << "\", length: " << len << '\n'; for (size_t i = 0; i < len; ++i) { for (size_t j = i + 1; j < len; ++j) { if (str[i] == str[j]) { std::cout << "String contains a repeated character.\n"; std::cout << "Character '" << str[i] << "' (hex " << std::hex << static_cast<unsigned int>(str[i]) << ") occurs at positions " << std::dec << i + 1 << " and " << j + 1 << ".\n\n"; return; } } } std::cout << "String contains no repeated characters.\n\n"; } int main() { string_has_repeated_character(""); string_has_repeated_character("."); string_has_repeated_character("abcABC"); string_has_repeated_character("XYZ ZYX"); string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"); return 0; }
Determine if a string is collapsible
C++
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ''immediately repeated'' character is any character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.} ;Examples: In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated by underscores (above), even though they (those characters) appear elsewhere in the character string. So, after ''collapsing'' the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate ''repeated'' characters and ''collapse'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: string number ++ 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | 5 | --- Harry S Truman | <###### has many repeated blanks +------------------------------------------------------------------------+
#include <string> #include <iostream> #include <algorithm> template<typename char_type> std::basic_string<char_type> collapse(std::basic_string<char_type> str) { auto i = std::unique(str.begin(), str.end()); str.erase(i, str.end()); return str; } void test(const std::string& str) { std::cout << "original string: <<<" << str << ">>>, length = " << str.length() << '\n'; std::string collapsed(collapse(str)); std::cout << "result string: <<<" << collapsed << ">>>, length = " << collapsed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test(""); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "); test("..1111111111111111111111111111111111111111111111111111111111111117777888"); test("I never give 'em hell, I just tell the truth, and they think it's hell. "); test(" --- Harry S Truman "); return 0; }
Determine if a string is squeezable
C++
Determine if a character string is ''squeezable''. And if so, squeeze the string (by removing any number of a ''specified'' ''immediately repeated'' character). This task is very similar to the task '''Determine if a character string is collapsible''' except that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''. If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). A specified ''immediately repeated'' character is any specified character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''squeeze'''.} ;Examples: In the following character string with a specified ''immediately repeated'' character of '''e''': The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''e''' is an specified repeated character, indicated by an underscore (above), even though they (the characters) appear elsewhere in the character string. So, after ''squeezing'' the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string, using a specified immediately repeated character '''s''': headmistressship The "squeezed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character and ''squeeze'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the specified repeated character (to be searched for and possibly ''squeezed''): :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: immediately string repeated number character ( | a blank, a minus, a seven, a period) ++ 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-' 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7' 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.' 5 | --- Harry S Truman | (below) <###### has many repeated blanks +------------------------------------------------------------------------+ | | | For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: * a blank * a minus * a lowercase '''r''' Note: there should be seven results shown, one each for the 1st four strings, and three results for the 5th string.
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.end()); return str; } void test(const std::string& str, char ch) { std::cout << "character: '" << ch << "'\n"; std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n'; std::string squeezed(squeeze(str, ch)); std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test("", ' '); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); std::string truman(" --- Harry S Truman "); test(truman, ' '); test(truman, '-'); test(truman, 'r'); return 0; }