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; }

Data Origins

Original dataset: https://huggingface.co/datasets/jondurbin/rosettacode-raw/

Cleaner code: https://github.com/the-crypt-keeper/rosettacode-parser

Data Fields

Field Type Description
title string problem title
task string problem description
language string solution language/variant
soulution string solution source code

Languages

One .jsonl is provided per language group, the sublanguage field in the data denotes the specific language version/variant or the source language the example was ported from.

Language Python problems 510 rows 621
Language C problems 350 rows 350
Language C++ problems 403 rows 416
Language C sharp problems 322 rows 342
Language Go problems 496 rows 503
Language JavaScript problems 269 rows 301
Language Java problems 470 rows 512
Language Lua problems 335 rows 339
Language Kotlin problems 435 rows 435
Language Ruby problems 418 rows 444

Total 4894 done 565 skip 4329 failed 0 rows 4263
Downloads last month
81
Edit dataset card