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 d...
#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(); ...
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 ...
#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:...
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 comp...
/** * 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 ...
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 progr...
#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"; ...
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. +--------------+ +--------------+ | | | | |...
//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 specifi...
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...
// 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?h...
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...
// 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...
#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 = toup...
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 | ...
#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...
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 deletio...
#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; ...
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 abbrevi...
#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::g...
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 EXTra...
#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 NF...
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 chan...
#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...
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 ...
#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::ostrea...
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 ''...
#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); ...
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...
#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 _intV...
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...
// 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; } ...
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 terminati...
#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 p...
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 v...
#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 constr...
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 ...
#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(), ri...
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''...
#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; ...
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 ...
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....
#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++)...
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...
#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;...
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( ...
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 [[referen...
#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(); ...
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_...
#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"; ...
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...
#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 += ...
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. T...
/* * 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 ...
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''' |- ...
#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; ...
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 s...
#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 ...
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 t...
#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_twis...
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(*i...
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...
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}...
#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.si...
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 Hollingdal...
#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 ...
#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 ...
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 "+...
#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') r...
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...
#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 ); DeleteObje...
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....
#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(); ...
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...
//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 <s...
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. Di...
#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++) ...
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]...
#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(limi...
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 chan...
#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 ...
Bioinformatics/base count
C++
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCA...
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'...
#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++) { ...
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 ...
#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 d...
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 ...
#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 : ...
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 ...
#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 = ',' ) ...
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 ta...
#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 mess...
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); co...
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 :* ...
#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 ...
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 '''...
#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 add...
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] =...
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 you...
#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 pro...
Casting out nines
C++
Task (in three parts): ;Part 1 Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky. Note that this function does nothing more than calculate the least posi...
// Casting Out Nines // // Nigel Galloway. June 24th., 2012 // #include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 <...
Catalan numbers/Pascal's triangle
C++
Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle. ;See: * Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction. * Catalan's Triangle for a Number Triangle that generates Catalan Numbers using...
// Generate Catalan Numbers // // Nigel Galloway: June 9th., 2012 // #include <iostream> int main() { const int N = 15; int t[N+2] = {0,1}; for(int i = 1; i<=N; i++){ for(int j = i; j>1; j--) t[j] = t[j] + t[j-1]; t[i+1] = t[i]; for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1]; std::cout << t[i+1] ...
Catamorphism
C++
''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. ;Task: Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language. ;See also: * W...
#include <iostream> #include <numeric> #include <functional> #include <vector> int main() { std::vector<int> nums = { 1, 2, 3, 4, 5 }; auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>()); auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, con...
Chaocipher
C++ from C#
Description: The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#include <iostream> enum class Mode { ENCRYPT, DECRYPT, }; const std::string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; const std::string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; std::string exec(std::string text, Mode mode, bool showSteps = false) { auto left = L_ALPHABET; auto right = R_ALPHABET;...
Chaos game
C++
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. ;Task Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a...
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
Check output device is a terminal
C++ from C
Demonstrate how to check whether the output device is a terminal or not. ;Related task: * [[Check input device is a terminal]]
#if _WIN32 #include <io.h> #define ISATTY _isatty #define FILENO _fileno #else #include <unistd.h> #define ISATTY isatty #define FILENO fileno #endif #include <iostream> int main() { if (ISATTY(FILENO(stdout))) { std::cout << "stdout is a tty\n"; } else { std::cout << "stdout is not a tty\n"; ...
Cheryl's birthday
C++ from Go
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the ''month'' of ...
#include <algorithm> #include <iostream> #include <vector> using namespace std; const vector<string> MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; struct Birthday { int month, day; friend ostream &operator<<(ostream &, const Birthday &); }; ostream ...
Chinese remainder theorem
C++
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv ...
// Requires C++17 #include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x...
Chinese zodiac
C++
Determine the Chinese zodiac sign and related associations for a given year. Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two l...
#include <iostream> #include <cmath> using namespace std; const string animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}; const string elements[]={"Wood","Fire","Earth","Metal","Water"}; string getElement(int year) { int element = floor((year-4)%10/2); ret...
Church numerals
C++
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. * '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. *...
#include <iostream> // apply the function zero times (return an identity function) auto Zero = [](auto){ return [](auto x){ return x; }; }; // define Church True and False auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; // apply the function f one m...
Circles of given radius through two points
C++11
2 circles with a given radius through 2 points in 2D space. Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. ;Exceptions: # r==0.0 should be treated as never describing circles (except in the case where the points are coincident). # If the points are coinc...
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
Cistercian numerals
C++ from Go
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''. ;How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number ...
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); ...
Closures/Value capture
C++11
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. Display ...
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
Colour bars/Display
C++
Display a series of vertical color bars across the width of the display. The color bars should either use: :::* the system palette, or :::* the sequence of colors: ::::::* black ::::::* red ::::::* green ::::::* blue ::::::* magenta ::::::* cyan ::::::* yellow ::::::* white
#include <QtGui> #include "colorbars.h" MyWidget::MyWidget( ) : width( 640 ) , height( 240 ) , colornumber( 8 ) { setGeometry( 0, 0 , width , height ) ; } void MyWidget::paintEvent ( QPaintEvent * ) { int rgbtriplets[ ] = { 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 0 , 0 , 0 , 255 , 255 , 0 , 255 ,...
Comma quibbling
C++
Comma quibbling is a task originally set by Eric Lippert in his blog. ;Task: Write a function to generate a string output which is the concatenation of input words from a list/sequence where: # An input of no words produces the output string of just the two brace characters "{}". # An input of just one word, e.g. ["...
#include <iostream> template<class T> void quibble(std::ostream& o, T i, T e) { o << "{"; if (e != i) { T n = i++; const char* more = ""; while (e != i) { o << more << *n; more = ", "; n = i++; } o << (*more?" and ":"") << *n; } o << "}"; } int main(int argc, char** argv)...
Command-line arguments
C++
{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]]. See also [[Program name]]. For parsing command line arguments intelligently, see [[Parsing command-line arguments]]. ...
#include <iostream> int main(int argc, const char* argv[]) { std::cout << "This program is named " << argv[0] << '\n' << "There are " << argc - 1 << " arguments given.\n"; for (int i = 1; i < argc; ++i) std::cout << "The argument #" << i << " is " << argv[i] << '\n'; }
Compare a list of strings
C++
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each of those two tests should result in a single true or false value, which could...
Assuming that the <code>strings</code> variable is of type <code>T&lt;std::string&gt;</code> where <code>T</code> is an ordered STL container such as <code>std::vector</code>:
Compare a list of strings
C++ 11
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each of those two tests should result in a single true or false value, which could...
#include <algorithm> #include <string> // Bug: calling operator++ on an empty collection invokes undefined behavior. std::all_of( ++(strings.begin()), strings.end(), [&](std::string a){ return a == strings.front(); } ) // All equal std::is_sorted( strings.begin(), strings.end(), [](std::...
Compile-time calculation
C++
Some programming languages allow calculation of values at compile time. ;Task: Calculate 10! (ten factorial) at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#include <iostream> template<int i> struct Fac { static const int result = i * Fac<i-1>::result; }; template<> struct Fac<1> { static const int result = 1; }; int main() { std::cout << "10! = " << Fac<10>::result << "\n"; return 0; }
Compile-time calculation
C++11
Some programming languages allow calculation of values at compile time. ;Task: Calculate 10! (ten factorial) at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#include <stdio.h> constexpr int factorial(int n) { return n ? (n * factorial(n - 1)) : 1; } constexpr int f10 = factorial(10); int main() { printf("%d\n", f10); return 0; }
Compiler/lexical analyzer
C++
The C and Python versions can be considered reference implementations. ;Related Tasks * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task
#include <charconv> // std::from_chars #include <fstream> // file_to_string, string_to_file #include <functional> // std::invoke #include <iomanip> // std::setw #include <ios> // std::left #include <iostream> #include <map> // keywords #include <sstream> #include <string> #includ...
Conjugate transpose
C++
Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M. ::: (M^H)_{ji} = \overline{M_{ij}} This means that row j, column i of the conjugate transpose equals the complex conjugate of row i, column j of the original matrix. In the next li...
#include <cassert> #include <cmath> #include <complex> #include <iomanip> #include <iostream> #include <sstream> #include <vector> template <typename scalar_type> class complex_matrix { public: using element_type = std::complex<scalar_type>; complex_matrix(size_t rows, size_t columns) : rows_(rows), c...
Continued fraction
C++
A number may be represented as a continued fraction (see Mathworld for more information) as follows: :a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}} The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and p...
#include <iomanip> #include <iostream> #include <tuple> typedef std::tuple<double,double> coeff_t; // coefficients type typedef coeff_t (*func_t)(int); // callback function type double calc(func_t func, int n) { double a, b, temp = 0; for (; n > 0; --n) { std::tie(a, b) = func(n); temp = b / (...
Continued fraction/Arithmetic/Construct from rational number
C++
To understand this task in context please see [[Continued fraction arithmetic]] The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming: :N_1 is the numerator :N_2 is the denominator The ...
#include <iostream> /* Interface for all Continued Fractions Nigel Galloway, February 9th., 2013. */ class ContinuedFraction { public: virtual const int nextTerm(){}; virtual const bool moreTerms(){}; }; /* Create a continued fraction from a rational number Nigel Galloway, February 9th., 2013. */ class r2cf : ...
Continued fraction/Arithmetic/G(matrix ng, continued fraction n)
C++
This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG: : \begin{bmatrix} a_1 & a \\ b_1 & b \end{bmatrix} I may perform perform the following operations: :Input the next term of N1 :Output a term of the continued fraction resulti...
/* Interface for all matrixNG classes Nigel Galloway, February 10th., 2013. */ class matrixNG { private: virtual void consumeTerm(){} virtual void consumeTerm(int n){} virtual const bool needTerm(){} protected: int cfn = 0, thisTerm; bool haveTerm = false; friend class NG; }; /* Implement th...
Convert seconds to compound duration
C++11
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"...
#include <iostream> #include <vector> using entry = std::pair<int, const char*>; void print(const std::vector<entry>& entries, std::ostream& out = std::cout) { bool first = true; for(const auto& e: entries) { if(!first) out << ", "; first = false; out << e.first << " " << e.second; ...
Copy stdin to stdout
C++
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#include <iostream> #include <iterator> int main() { using namespace std; noskipws(cin); copy( istream_iterator<char>(cin), istream_iterator<char>(), ostream_iterator<char>(cout) ); return 0; }
Count the coins
C++
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and ...
#include <iostream> #include <stack> #include <vector> struct DataFrame { int sum; std::vector<int> coins; std::vector<int> avail_coins; }; int main() { std::stack<DataFrame> s; s.push({ 100, {}, { 25, 10, 5, 1 } }); int ways = 0; while (!s.empty()) { DataFrame top = s.top(); s.pop(); if (to...
Create an HTML table
C++
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. *...
#include <fstream> #include <boost/array.hpp> #include <string> #include <cstdlib> #include <ctime> #include <sstream> void makeGap( int gap , std::string & text ) { for ( int i = 0 ; i < gap ; i++ ) text.append( " " ) ; } int main( ) { boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ; int headgap ...
Currying
C++
{{Wikipedia|Currying}} ;Task: Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
Currying may be achieved in [[C++]] using the [[wp:Standard Template Library|Standard Template Library]] function object adapters (<code>binder1st</code> and <code>binder2nd</code>), and more generically using the [[wp:Boost library|Boost]] <code>bind</code> mechanism.
Curzon numbers
C++
A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''. '''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''....
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod;...
Cut a rectangle
C++ from Java
A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 an...
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) {...
Cyclotomic polynomial
C++ from Java
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n. ;Task: * Find and print the first 30 cyclotomic polynomials. * Find and print the order of the fi...
#include <algorithm> #include <iostream> #include <initializer_list> #include <map> #include <vector> const int MAX_ALL_FACTORS = 100000; const int algorithm = 2; int divisions = 0; //Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage. class Term { private: long m_...
Damm algorithm
C++ from C#
The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. ;Task: Verify the checksum, stored as last digit of an input.
#include <string> #include <cstdio> inline constexper int TABLE[][10] = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5,...
De Bruijn sequences
C++ from D
{{DISPLAYTITLE:de Bruijn sequences}} The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn. A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized unless it's the first word in a sentence. Rosetta Code (more or less by de...
#include <algorithm> #include <functional> #include <iostream> #include <iterator> #include <string> #include <sstream> #include <vector> typedef unsigned char byte; std::string deBruijn(int k, int n) { std::vector<byte> a(k * n, 0); std::vector<byte> seq; std::function<void(int, int)> db; db = [&](i...
Deepcopy
C++
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the languag...
#include <array> #include <iostream> #include <list> #include <map> #include <vector> int main() { // make a nested structure to copy - a map of arrays containing vectors of strings auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"}; auto myColors = std::vector<std::string>{"red", "gr...
Department numbers
C++
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different fro...
#include <iostream> #include <iomanip> int main( int argc, char* argv[] ) { int sol = 1; std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n"; for( int f = 1; f < 8; f++ ) { for( int p = 1; p < 8; p++ ) { for( int s = 1; s < 8; s++ ) { if( f != p && f != s && p != s && !( p...
Descending primes
C++ from C#
Generate and show all primes with strictly descending decimal digits. ;See also ;* OEIS:A052014 - Primes with distinct digits in descending order ;Related: *[[Ascending primes]]
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true...
Detect division by zero
C++
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
#include<iostream> #include<csignal> /* for signal */ #include<cstdlib> using namespace std; void fpe_handler(int signal) { cerr << "Floating Point Exception: division by zero" << endl; exit(signal); } int main() { // Register floating-point exception handler. signal(SIGFPE, fpe_handler); int a ...
Determinant and permanent
C++ from Java
permanent of the matrix. The determinant is given by :: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i} while the permanent is given by :: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i} In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A perm...
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *i...
Determine if a string has all the same characters
C++
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its lengt...
#include <iostream> #include <string> void all_characters_are_the_same(const std::string& str) { size_t len = str.length(); std::cout << "input: \"" << str << "\", length: " << len << '\n'; if (len > 0) { char ch = str[0]; for (size_t i = 1; i < len; ++i) { if (str[i] != ch) { ...
Determine if a string has all unique characters
C++
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings...
#include <iostream> #include <string> void string_has_repeated_character(const std::string& str) { size_t len = str.length(); std::cout << "input: \"" << str << "\", length: " << len << '\n'; for (size_t i = 0; i < len; ++i) { for (size_t j = i + 1; j < len; ++j) { if (str[i] == str[j])...
Determine if a string is collapsible
C++
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ...
#include <string> #include <iostream> #include <algorithm> template<typename char_type> std::basic_string<char_type> collapse(std::basic_string<char_type> str) { auto i = std::unique(str.begin(), str.end()); str.erase(i, str.end()); return str; } void test(const std::string& str) { std::cout << "origi...
Determine if a string is squeezable
C++
Determine if a character string is ''squeezable''. And if so, squeeze the string (by removing any number of a ''specified'' ''immediately repeated'' character). This task is very similar to the task '''Determine if a character string is collapsible''' except that only a specified character is '...
#include <algorithm> #include <string> #include <iostream> template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.en...