title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Ramer-Douglas-Peucker line simplification
C++
The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape. ;Task: Using the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is: '''1.0'''. Display the remaining points here. ;Reference: :* the Wikipedia article: Ramer-Douglas-Peucker algorithm.
#include <iostream> #include <cmath> #include <utility> #include <vector> #include <stdexcept> using namespace std; typedef std::pair<double, double> Point; double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd) { double dx = lineEnd.first - lineStart.first; double dy = lineEnd.second - lineStart.second; //Normalise double mag = pow(pow(dx,2.0)+pow(dy,2.0),0.5); if(mag > 0.0) { dx /= mag; dy /= mag; } double pvx = pt.first - lineStart.first; double pvy = pt.second - lineStart.second; //Get dot product (project pv onto normalized direction) double pvdot = dx * pvx + dy * pvy; //Scale line direction vector double dsx = pvdot * dx; double dsy = pvdot * dy; //Subtract this from pv double ax = pvx - dsx; double ay = pvy - dsy; return pow(pow(ax,2.0)+pow(ay,2.0),0.5); } void RamerDouglasPeucker(const vector<Point> &pointList, double epsilon, vector<Point> &out) { if(pointList.size()<2) throw invalid_argument("Not enough points to simplify"); // Find the point with the maximum distance from line between start and end double dmax = 0.0; size_t index = 0; size_t end = pointList.size()-1; for(size_t i = 1; i < end; i++) { double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]); if (d > dmax) { index = i; dmax = d; } } // If max distance is greater than epsilon, recursively simplify if(dmax > epsilon) { // Recursive call vector<Point> recResults1; vector<Point> recResults2; vector<Point> firstLine(pointList.begin(), pointList.begin()+index+1); vector<Point> lastLine(pointList.begin()+index, pointList.end()); RamerDouglasPeucker(firstLine, epsilon, recResults1); RamerDouglasPeucker(lastLine, epsilon, recResults2); // Build the result list out.assign(recResults1.begin(), recResults1.end()-1); out.insert(out.end(), recResults2.begin(), recResults2.end()); if(out.size()<2) throw runtime_error("Problem assembling output"); } else { //Just return start and end points out.clear(); out.push_back(pointList[0]); out.push_back(pointList[end]); } } int main() { vector<Point> pointList; vector<Point> pointListOut; pointList.push_back(Point(0.0, 0.0)); pointList.push_back(Point(1.0, 0.1)); pointList.push_back(Point(2.0, -0.1)); pointList.push_back(Point(3.0, 5.0)); pointList.push_back(Point(4.0, 6.0)); pointList.push_back(Point(5.0, 7.0)); pointList.push_back(Point(6.0, 8.1)); pointList.push_back(Point(7.0, 9.0)); pointList.push_back(Point(8.0, 9.0)); pointList.push_back(Point(9.0, 9.0)); RamerDouglasPeucker(pointList, 1.0, pointListOut); cout << "result" << endl; for(size_t i=0;i< pointListOut.size();i++) { cout << pointListOut[i].first << "," << pointListOut[i].second << endl; } return 0; }
Random Latin squares
C++ from Java
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. For the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero. ;Example n=4 randomised Latin square: 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 ;Task: # Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. # Use the function to generate ''and show here'', two randomly generated squares of size 5. ;Note: Strict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task. ;Related tasks: * [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]] * [[Latin Squares in reduced form]] ;Reference: * Wikipedia: Latin square * OEIS: A002860
#include <algorithm> #include <chrono> #include <iostream> #include <random> #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 << ", "; os << *it; it = std::next(it); } return os << ']'; } void printSquare(const std::vector<std::vector<int>> &latin) { for (auto &row : latin) { std::cout << row << '\n'; } std::cout << '\n'; } void latinSquare(int n) { if (n <= 0) { std::cout << "[]\n"; return; } // obtain a time-based seed: unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); auto g = std::default_random_engine(seed); std::vector<std::vector<int>> latin; for (int i = 0; i < n; ++i) { std::vector<int> inner; for (int j = 0; j < n; ++j) { inner.push_back(j); } latin.push_back(inner); } // first row std::shuffle(latin[0].begin(), latin[0].end(), g); // middle row(s) for (int i = 1; i < n - 1; ++i) { bool shuffled = false; while (!shuffled) { std::shuffle(latin[i].begin(), latin[i].end(), g); for (int k = 0; k < i; ++k) { for (int j = 0; j < n; ++j) { if (latin[k][j] == latin[i][j]) { goto shuffling; } } } shuffled = true; shuffling: {} } } // last row for (int j = 0; j < n; ++j) { std::vector<bool> used(n, false); for (int i = 0; i < n - 1; ++i) { used[latin[i][j]] = true; } for (int k = 0; k < n; ++k) { if (!used[k]) { latin[n - 1][j] = k; break; } } } printSquare(latin); } int main() { latinSquare(5); latinSquare(5); latinSquare(10); return 0; }
Random number generator (device)
C++
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then: show how to obtain a random 32-bit number from that mechanism. ;Related task * [[Random_number_generator_(included)]]
<code>std::random_device</code> is a uniformly-distributed integer random number generator that produces non-deterministic random numbers. Note that <code>std::random_device</code> may be implemented in terms of a pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. See the C++ section on [[Random_number_generator_(included)#C.2B.2B|Random number generator (included)]] for the list of pseudo-random number engines available.
Random number generator (device)
C++11
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then: show how to obtain a random 32-bit number from that mechanism. ;Related task * [[Random_number_generator_(included)]]
#include <iostream> #include <random> int main() { std::random_device rd; std::uniform_int_distribution<long> dist; // long is guaranteed to be 32 bits std::cout << "Random Number: " << dist(rd) << std::endl; }
Random number generator (included)
C++
The task is to: : State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. : If possible, give a link to a wider explanation of the algorithm used. Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
As part of the C++11 specification the language now includes various forms of random number generation. While the default engine is implementation specific (ex, unspecified), the following Pseudo-random generators are available in the standard: * Linear congruential (minstd_rand0, minstd_rand) * Mersenne twister (mt19937, mt19937_64) * Subtract with carry (ranlux24_base, ranlux48_base) * Discard block (ranlux24, ranlux48) * Shuffle order (knuth_b) Additionally, the following distributions are supported: * Uniform distributions: uniform_int_distribution, uniform_real_distribution * Bernoulli distributions: bernoulli_distribution, geometric_distribution, binomial_distribution, negative_binomial_distribution * Poisson distributions: poisson_distribution, gamma_distribution, exponential_distribution, weibull_distribution, extreme_value_distribution * Normal distributions: normal_distribution, fisher_f_distribution, cauchy_distribution, lognormal_distribution, chi_squared_distribution, student_t_distribution * Sampling distributions: discrete_distribution, piecewise_linear_distribution, piecewise_constant_distribution Example of use:
Random number generator (included)
C++11
The task is to: : State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. : If possible, give a link to a wider explanation of the algorithm used. Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#include <iostream> #include <string> #include <random> int main() { std::random_device rd; std::uniform_int_distribution<int> dist(1, 10); std::mt19937 mt(rd()); std::cout << "Random Number (hardware): " << dist(rd) << std::endl; std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl; }
Range consolidation
C++
Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''. That range can be shown as: ::::::::: '''[b0, b1]''' :::::::: or equally as: ::::::::: '''[b1, b0]''' Given two ranges, the act of consolidation between them compares the two ranges: * If one range covers all of the other then the result is that encompassing range. * If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges. * Otherwise the act of consolidation is to return the two non-touching ranges. Given '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If '''N < 2''' then range consolidation has no strict meaning and the input can be returned. ;Example 1: : Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then : there is no common region between the ranges and the result is the same as the input. ;Example 2: : Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then : there is : an overlap '''[2.5, 1.8]''' between the ranges and : the result is the single range '''[1, 4.7]'''. : Note that order of bounds in a range is not (yet) stated. ;Example 3: : Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then : they touch at '''7.2''' and : the result is the single range '''[6.1, 8.3]'''. ;Example 4: : Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]''' : then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]''' : but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and : consolidate to produce the range '''[1, 5]'''. : This range, in turn, overlaps the other range '''[4, 8]''', and : so consolidates to the final output of the single range '''[1, 8]'''. ;Task: Let a normalized range display show the smaller bound to the left; and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the ''normalized'' result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. ;See also: * [[Set consolidation]] * [[Set of real numbers]]
#include <algorithm> #include <iostream> #include <utility> #include <vector> // A range is represented as std::pair<from, to> template <typename iterator> void normalize_ranges(iterator begin, iterator end) { for (iterator i = begin; i != end; ++i) { if (i->second < i->first) std::swap(i->first, i->second); } std::sort(begin, end); } // Merges a range of ranges in-place. Returns an iterator to the // end of the resulting range, similarly to std::remove. template <typename iterator> iterator merge_ranges(iterator begin, iterator end) { iterator out = begin; for (iterator i = begin; i != end; ) { iterator j = i; while (++j != end && j->first <= i->second) i->second = std::max(i->second, j->second); *out++ = *i; i = j; } return out; } template <typename iterator> iterator consolidate_ranges(iterator begin, iterator end) { normalize_ranges(begin, end); return merge_ranges(begin, end); } template <typename pair> void print_range(std::ostream& out, const pair& range) { out << '[' << range.first << ", " << range.second << ']'; } template <typename iterator> void print_ranges(std::ostream& out, iterator begin, iterator end) { if (begin != end) { print_range(out, *begin++); for (; begin != end; ++begin) { out << ", "; print_range(out, *begin); } } } int main() { std::vector<std::pair<double, double>> test_cases[] = { { {1.1, 2.2} }, { {6.1, 7.2}, {7.2, 8.3} }, { {4, 3}, {2, 1} }, { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} }, { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} } }; for (auto&& ranges : test_cases) { print_ranges(std::cout, std::begin(ranges), std::end(ranges)); std::cout << " -> "; auto i = consolidate_ranges(std::begin(ranges), std::end(ranges)); print_ranges(std::cout, std::begin(ranges), i); std::cout << '\n'; } return 0; }
Range expansion
C++
{{:Range extraction/Format}} ;Task: Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the '''range from minus 3 to ''minus'' 1'''. ;Related task: * [[Range extraction]]
#include <iostream> #include <sstream> #include <iterator> #include <climits> #include <deque> // parse a list of numbers with ranges // // arguments: // is: the stream to parse // out: the output iterator the parsed list is written to. // // returns true if the parse was successful. false otherwise template<typename OutIter> bool parse_number_list_with_ranges(std::istream& is, OutIter out) { int number; // the list always has to start with a number while (is >> number) { *out++ = number; char c; if (is >> c) switch(c) { case ',': continue; case '-': { int number2; if (is >> number2) { if (number2 < number) return false; while (number < number2) *out++ = ++number; char c2; if (is >> c2) if (c2 == ',') continue; else return false; else return is.eof(); } else return false; } default: return is.eof(); } else return is.eof(); } // if we get here, something went wrong (otherwise we would have // returned from inside the loop) return false; } int main() { std::istringstream example("-6,-3--1,3-5,7-11,14,15,17-20"); std::deque<int> v; bool success = parse_number_list_with_ranges(example, std::back_inserter(v)); if (success) { std::copy(v.begin(), v.end()-1, std::ostream_iterator<int>(std::cout, ",")); std::cout << v.back() << "\n"; } else std::cout << "an error occured."; }
Range extraction
C++
{{:Range extraction/Format}} ;Task: * Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. * Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 * Show the output of your program. ;Related task: * [[Range expansion]]
#include <iostream> #include <iterator> #include <cstddef> template<typename InIter> void extract_ranges(InIter begin, InIter end, std::ostream& os) { if (begin == end) return; int current = *begin++; os << current; int count = 1; while (begin != end) { int next = *begin++; if (next == current+1) ++count; else { if (count > 2) os << '-'; else os << ','; if (count > 1) os << current << ','; os << next; count = 1; } current = next; } if (count > 1) os << (count > 2? '-' : ',') << current; } template<typename T, std::size_t n> T* end(T (&array)[n]) { return array+n; } int main() { int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; extract_ranges(data, end(data), std::cout); std::cout << std::endl; }
Rate counter
C++
Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed. Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: * Run N seconds worth of jobs and/or Y jobs. * Report at least three distinct times. Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can. '''See also:''' [[System time]], [[Time a function]]
#include <iostream> #include <ctime> // We only get one-second precision on most systems, as // time_t only holds seconds. class CRateState { protected: time_t m_lastFlush; time_t m_period; size_t m_tickCount; public: CRateState(time_t period); void Tick(); }; CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)), m_period(period), m_tickCount(0) { } void CRateState::Tick() { m_tickCount++; time_t now = std::time(NULL); if((now - m_lastFlush) >= m_period) { //TPS Report size_t tps = 0.0; if(m_tickCount > 0) tps = m_tickCount / (now - m_lastFlush); std::cout << tps << " tics per second" << std::endl; //Reset m_tickCount = 0; m_lastFlush = now; } } // A stub function that simply represents whatever it is // that we want to multiple times. void something_we_do() { // We use volatile here, as many compilers will optimize away // the for() loop otherwise, even without optimizations // explicitly enabled. // // volatile tells the compiler not to make any assumptions // about the variable, implying that the programmer knows more // about that variable than the compiler, in this case. volatile size_t anchor = 0; for(size_t x = 0; x < 0xffff; ++x) { anchor = x; } } int main() { time_t start = std::time(NULL); CRateState rateWatch(5); // Loop for twenty seconds for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL)) { // Do something. something_we_do(); // Note that we did something. rateWatch.Tick(); } return 0; }
Read a specific line from a file
C++
Some languages have special semantics for obtaining a known line number from a file. ;Task: Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message. If no special semantics are available for obtaining the required line, it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << " !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << " !\n" ; return 1 ; } }
Recaman's sequence
C++ from C#
The '''Recaman's sequence''' generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated. If the conditions ''don't'' hold then a(n) = a(n-1) + n. ;Task: # Generate and show here the first 15 members of the sequence. # Find and show here, the first duplicated number in the sequence. # '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. ;References: * A005132, The On-Line Encyclopedia of Integer Sequences. * The Slightly Spooky Recaman Sequence, Numberphile video. * Recaman's sequence, on Wikipedia.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
Remove lines from a file
C++
Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Rep-string
C++
Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''. For example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string. ;Task: * Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). * There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. * Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 * Show your output on this page.
#include <string> #include <vector> #include <boost/regex.hpp> bool is_repstring( const std::string & teststring , std::string & repunit ) { std::string regex( "^(.+)\\1+(.*)$" ) ; boost::regex e ( regex ) ; boost::smatch what ; if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { std::string firstbracket( what[1 ] ) ; std::string secondbracket( what[ 2 ] ) ; if ( firstbracket.length( ) >= secondbracket.length( ) && firstbracket.find( secondbracket ) != std::string::npos ) { repunit = firstbracket ; } } return !repunit.empty( ) ; } int main( ) { std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" , "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; std::string theRep ; for ( std::string myString : teststrings ) { if ( is_repstring( myString , theRep ) ) { std::cout << myString << " is a rep string! Here is a repeating string:\n" ; std::cout << theRep << " " ; } else { std::cout << myString << " is no rep string!" ; } theRep.clear( ) ; std::cout << std::endl ; } return 0 ; }
Repeat
C++
Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
template <typename Function> void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--) f(); }
Resistor mesh
C++ from C#
Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown, find the resistance between points '''A''' and '''B'''. ;See also: * (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits) * An article on how to calculate this and an implementation in Mathematica
#include <iomanip> #include <iostream> #include <vector> class Node { private: double v; int fixed; public: Node() : v(0.0), fixed(0) { // empty } Node(double v, int fixed) : v(v), fixed(fixed) { // empty } double getV() const { return v; } void setV(double nv) { v = nv; } int getFixed() const { return fixed; } void setFixed(int nf) { fixed = nf; } }; void setBoundary(std::vector<std::vector<Node>>& m) { m[1][1].setV(1.0); m[1][1].setFixed(1); m[6][7].setV(-1.0); m[6][7].setFixed(-1); } double calculateDifference(const std::vector<std::vector<Node>>& m, std::vector<std::vector<Node>>& d, const int w, const int h) { double total = 0.0; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { double v = 0.0; int n = 0; if (i > 0) { v += m[i - 1][j].getV(); n++; } if (j > 0) { v += m[i][j - 1].getV(); n++; } if (i + 1 < h) { v += m[i + 1][j].getV(); n++; } if (j + 1 < w) { v += m[i][j + 1].getV(); n++; } v = m[i][j].getV() - v / n; d[i][j].setV(v); if (m[i][j].getFixed() == 0) { total += v * v; } } } return total; } double iter(std::vector<std::vector<Node>>& m, const int w, const int h) { using namespace std; vector<vector<Node>> d; for (int i = 0; i < h; ++i) { vector<Node> t(w); d.push_back(t); } double curr[] = { 0.0, 0.0, 0.0 }; double diff = 1e10; while (diff > 1e-24) { setBoundary(m); diff = calculateDifference(m, d, w, h); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { m[i][j].setV(m[i][j].getV() - d[i][j].getV()); } } } for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { int k = 0; if (i != 0) ++k; if (j != 0) ++k; if (i < h - 1) ++k; if (j < w - 1) ++k; curr[m[i][j].getFixed() + 1] += d[i][j].getV()*k; } } return (curr[2] - curr[0]) / 2.0; } const int S = 10; int main() { using namespace std; vector<vector<Node>> mesh; for (int i = 0; i < S; ++i) { vector<Node> t(S); mesh.push_back(t); } double r = 2.0 / iter(mesh, S, S); cout << "R = " << setprecision(15) << r << '\n'; return 0; }
Reverse words in a string
C++
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified. ;Example: Hey you, Bub! would be shown reversed as: Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string (or one just containing spaces) would be the result. '''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) ;Input data (ten lines within the box) line +----------------------------------------+ 1 | ---------- Ice and Fire ------------ | 2 | | <--- a blank line here. 3 | fire, in end will world the say Some | 4 | ice. in say Some | 5 | desire of tasted I've what From | 6 | fire. favor who those with hold I | 7 | | <--- a blank line here. 8 | ... elided paragraph last ... | 9 | | <--- a blank line here. 10 | Frost Robert ----------------------- | +----------------------------------------+ ;Cf. * [[Phrase reversals]]
#include <algorithm> #include <functional> #include <string> #include <iostream> #include <vector> //code for a C++11 compliant compiler template <class BidirectionalIterator, class T> void block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) { std::reverse(first, last); auto block_last = first; do { using std::placeholders::_1; auto block_first = std::find_if_not(block_last, last, std::bind(std::equal_to<T>(),_1, separator)); block_last = std::find(block_first, last, separator); std::reverse(block_first, block_last); } while(block_last != last); } //code for a C++03 compliant compiler template <class BidirectionalIterator, class T> void block_reverse_cpp03(BidirectionalIterator first, BidirectionalIterator last, T const& separator) { std::reverse(first, last); BidirectionalIterator block_last = first; do { BidirectionalIterator block_first = std::find_if(block_last, last, std::bind2nd(std::not_equal_to<T>(), separator)); block_last = std::find(block_first, last, separator); std::reverse(block_first, block_last); } while(block_last != last); } int main() { std::string str1[] = { "---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------" }; std::for_each(begin(str1), end(str1), [](std::string& s){ block_reverse_cpp11(begin(s), end(s), ' '); std::cout << s << std::endl; }); std::for_each(begin(str1), end(str1), [](std::string& s){ block_reverse_cpp03(begin(s), end(s), ' '); std::cout << s << std::endl; }); return 0; }
Rhonda numbers
C++
A positive integer '''''n''''' is said to be a Rhonda number to base '''''b''''' if the product of the base '''''b''''' digits of '''''n''''' is equal to '''''b''''' times the sum of '''''n''''''s prime factors. ''These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.'' '''25662''' is a Rhonda number to base-'''10'''. The prime factorization is '''2 x 3 x 7 x 13 x 47'''; the product of its base-'''10''' digits is equal to the base times the sum of its prime factors: 2 x 5 x 6 x 6 x 2 = 720 = 10 x (2 + 3 + 7 + 13 + 47) Rhonda numbers only exist in bases that are not a prime. ''Rhonda numbers to base 10 '''always''' contain at least 1 digit 5 and '''always''' contain at least 1 even digit.'' ;Task * For the non-prime bases '''''b''''' from '''2''' through '''16''' , find and display here, on this page, at least the first '''10''' '''Rhonda numbers''' to base '''''b'''''. Display the found numbers at least in base '''10'''. ;Stretch * Extend out to base '''36'''. ;See also ;* Wolfram Mathworld - Rhonda numbers ;* Numbers Aplenty - Rhonda numbers ;* OEIS:A100968 - Integers n that are Rhonda numbers to base 4 ;* OEIS:A100969 - Integers n that are Rhonda numbers to base 6 ;* OEIS:A100970 - Integers n that are Rhonda numbers to base 8 ;* OEIS:A100973 - Integers n that are Rhonda numbers to base 9 ;* OEIS:A099542 - Rhonda numbers to base 10 ;* OEIS:A100971 - Integers n that are Rhonda numbers to base 12 ;* OEIS:A100972 - Integers n that are Rhonda numbers to base 14 ;* OEIS:A100974 - Integers n that are Rhonda numbers to base 15 ;* OEIS:A100975 - Integers n that are Rhonda numbers to base 16 ;* OEIS:A255735 - Integers n that are Rhonda numbers to base 18 ;* OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20) ;* OEIS:A255736 - Integers that are Rhonda numbers to base 30 ;* Related Task: Smith numbers
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int digit_product(int base, int n) { int product = 1; for (; n != 0; n /= base) product *= n % base; return product; } int prime_factor_sum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2; for (int p = 3; p * p <= n; p += 2) for (; n % p == 0; n /= p) sum += p; if (n > 1) sum += n; return sum; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } bool is_rhonda(int base, int n) { return digit_product(base, n) == base * prime_factor_sum(n); } std::string to_string(int base, int n) { assert(base <= 36); static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::string str; for (; n != 0; n /= base) str += digits[n % base]; std::reverse(str.begin(), str.end()); return str; } int main() { const int limit = 15; for (int base = 2; base <= 36; ++base) { if (is_prime(base)) continue; std::cout << "First " << limit << " Rhonda numbers to base " << base << ":\n"; int numbers[limit]; for (int n = 1, count = 0; count < limit; ++n) { if (is_rhonda(base, n)) numbers[count++] = n; } std::cout << "In base 10:"; for (int i = 0; i < limit; ++i) std::cout << ' ' << numbers[i]; std::cout << "\nIn base " << base << ':'; for (int i = 0; i < limit; ++i) std::cout << ' ' << to_string(base, numbers[i]); std::cout << "\n\n"; } }
Roman numerals/Decode
C++
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any '''0'''s (zeroes). '''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and '''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII). The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
#include <exception> #include <string> #include <iostream> using namespace std; namespace Roman { int ToInt(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } throw exception("Invalid character"); } int ToInt(const string& s) { int retval = 0, pvs = 0; for (auto pc = s.rbegin(); pc != s.rend(); ++pc) { const int inc = ToInt(*pc); retval += inc < pvs ? -inc : inc; pvs = inc; } return retval; } } int main(int argc, char* argv[]) { try { cout << "MCMXC = " << Roman::ToInt("MCMXC") << "\n"; cout << "MMVIII = " << Roman::ToInt("MMVIII") << "\n"; cout << "MDCLXVI = " << Roman::ToInt("MDCLXVI") << "\n"; } catch (exception& e) { cerr << e.what(); return -1; } return 0; }
Roman numerals/Encode
C++
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numerals: * 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC * 2008 is written as 2000=MM, 8=VIII; or MMVIII * 1666 uses each Roman symbol in descending order: MDCLXVI
#include <iostream> #include <string> std::string to_roman(int x) { if (x <= 0) return "Negative or zero!"; auto roman_digit = [](char one, char five, char ten, int x) { if (x <= 3) return std::string().assign(x, one); if (x <= 5) return std::string().assign(5 - x, one) + five; if (x <= 8) return five + std::string().assign(x - 5, one); return std::string().assign(10 - x, one) + ten; }; if (x >= 1000) return x - 1000 > 0 ? "M" + to_roman(x - 1000) : "M"; if (x >= 100) { auto s = roman_digit('C', 'D', 'M', x / 100); return x % 100 > 0 ? s + to_roman(x % 100) : s; } if (x >= 10) { auto s = roman_digit('X', 'L', 'C', x / 10); return x % 10 > 0 ? s + to_roman(x % 10) : s; } return roman_digit('I', 'V', 'X', x); } int main() { for (int i = 0; i < 2018; i++) std::cout << i << " --> " << to_roman(i) << std::endl; }
Runge-Kutta method
C++
Given the example Differential equation: :y'(t) = t \times \sqrt {y(t)} With initial condition: :t_0 = 0 and y_0 = y(t_0) = y(0) = 1 This equation has an exact solution: :y(t) = \tfrac{1}{16}(t^2 +4)^2 ;Task Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation. * Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given) * Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution. ;Method summary Starting with a given y_n and t_n calculate: :\delta y_1 = \delta t\times y'(t_n, y_n)\quad :\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1) :\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2) :\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad then: :y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4) :t_{n+1} = t_n + \delta t\quad
/* * compiled with: * g++ (Debian 8.3.0-6) 8.3.0 * * g++ -std=c++14 -o rk4 % * */ # include <iostream> # include <math.h> auto rk4(double f(double, double)) { return [f](double t, double y, double dt) -> double { double dy1 { dt * f( t , y ) }, dy2 { dt * f( t+dt/2, y+dy1/2 ) }, dy3 { dt * f( t+dt/2, y+dy2/2 ) }, dy4 { dt * f( t+dt , y+dy3 ) }; return ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6; }; } int main(void) { constexpr double TIME_MAXIMUM { 10.0 }, T_START { 0.0 }, Y_START { 1.0 }, DT { 0.1 }, WHOLE_TOLERANCE { 1e-12 }; auto dy = rk4( [](double t, double y) -> double { return t*sqrt(y); } ) ; for ( auto y { Y_START }, t { T_START }; t <= TIME_MAXIMUM; y += dy(t,y,DT), t += DT ) if (ceilf(t)-t < WHOLE_TOLERANCE) printf("y(%4.1f)\t=%12.6f \t error: %12.6e\n", t, y, std::fabs(y - pow(t*t+4,2)/16)); return 0; }
Ruth-Aaron numbers
C++
A '''Ruth-Aaron''' pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A '''Ruth-Aaron''' triple consists of '''''three''''' consecutive integers with the same properties. There is a second variant of '''Ruth-Aaron''' numbers, one which uses prime ''factors'' rather than prime ''divisors''. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits. It is common to refer to each '''Ruth-Aaron''' group by the first number in it. ;Task * Find and show, here on this page, the first '''30''' '''Ruth-Aaron numbers''' (factors). * Find and show, here on this page, the first '''30''' '''Ruth-Aaron numbers''' (divisors). ;Stretch * Find and show the first '''Ruth-Aaron triple''' (factors). * Find and show the first '''Ruth-Aaron triple''' (divisors). ;See also ;*Wikipedia: Ruth-Aaron pair ;*OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 ;*OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
#include <iomanip> #include <iostream> int prime_factor_sum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2; for (int p = 3, sq = 9; sq <= n; p += 2) { for (; n % p == 0; n /= p) sum += p; sq += (p + 1) << 2; } if (n > 1) sum += n; return sum; } int prime_divisor_sum(int n) { int sum = 0; if ((n & 1) == 0) { sum += 2; n >>= 1; while ((n & 1) == 0) n >>= 1; } for (int p = 3, sq = 9; sq <= n; p += 2) { if (n % p == 0) { sum += p; n /= p; while (n % p == 0) n /= p; } sq += (p + 1) << 2; } if (n > 1) sum += n; return sum; } int main() { const int limit = 30; int dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0; std::cout << "First " << limit << " Ruth-Aaron numbers (factors):\n"; for (int n = 2, count = 0; count < limit; ++n) { fsum2 = prime_factor_sum(n); if (fsum1 == fsum2) { ++count; std::cout << std::setw(5) << n - 1 << (count % 10 == 0 ? '\n' : ' '); } fsum1 = fsum2; } std::cout << "\nFirst " << limit << " Ruth-Aaron numbers (divisors):\n"; for (int n = 2, count = 0; count < limit; ++n) { dsum2 = prime_divisor_sum(n); if (dsum1 == dsum2) { ++count; std::cout << std::setw(5) << n - 1 << (count % 10 == 0 ? '\n' : ' '); } dsum1 = dsum2; } dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0; for (int n = 2;; ++n) { int fsum3 = prime_factor_sum(n); if (fsum1 == fsum2 && fsum2 == fsum3) { std::cout << "\nFirst Ruth-Aaron triple (factors): " << n - 2 << '\n'; break; } fsum1 = fsum2; fsum2 = fsum3; } for (int n = 2;; ++n) { int dsum3 = prime_divisor_sum(n); if (dsum1 == dsum2 && dsum2 == dsum3) { std::cout << "\nFirst Ruth-Aaron triple (divisors): " << n - 2 << '\n'; break; } dsum1 = dsum2; dsum2 = dsum3; } }
Sailors, coconuts and a monkey problem
C++ from C#
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.) ;The task: # Calculate the minimum possible size of the initial pile of coconuts collected during the first day. # Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.) # Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course). # Show your answers here. ;Extra credit (optional): * Give some indication of the number of coconuts each sailor hides during the night. ;Note: * Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics. * The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale! ;C.f: * Monkeys and Coconuts - Numberphile (Video) Analytical solution. * A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { x++; } std::cout << n << ": " << x << std::endl; } return 0; }
Same fringe
C++
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons. Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
#include <algorithm> #include <coroutine> #include <iostream> #include <memory> #include <tuple> #include <variant> using namespace std; class BinaryTree { // C++ does not have a built in tree type. The binary tree is a recursive // data type that is represented by an empty tree or a node the has a value // and a left and right sub-tree. A tuple represents the node and unique_ptr // represents an empty vs. non-empty tree. using Node = tuple<BinaryTree, int, BinaryTree>; unique_ptr<Node> m_tree; public: // Provide ways to make trees BinaryTree() = default; // Make an empty tree BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild) : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {} BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){} BinaryTree(BinaryTree&& leftChild, int value) : BinaryTree(move(leftChild), value, BinaryTree{}){} BinaryTree(int value, BinaryTree&& rightChild) : BinaryTree(BinaryTree{}, value, move(rightChild)){} // Test if the tree is empty explicit operator bool() const { return (bool)m_tree; } // Get the value of the root node of the tree int Value() const { return get<1>(*m_tree); } // Get the left child tree const BinaryTree& LeftChild() const { return get<0>(*m_tree); } // Get the right child tree const BinaryTree& RightChild() const { return get<2>(*m_tree); } }; // Define a promise type to be used for coroutines struct TreeWalker { struct promise_type { int val; suspend_never initial_suspend() noexcept {return {};} suspend_never return_void() noexcept {return {};} suspend_always final_suspend() noexcept {return {};} void unhandled_exception() noexcept { } TreeWalker get_return_object() { return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)}; } suspend_always yield_value(int x) noexcept { val=x; return {}; } }; coroutine_handle<promise_type> coro; TreeWalker(coroutine_handle<promise_type> h): coro(h) {} ~TreeWalker() { if(coro) coro.destroy(); } // Define an iterator type to work with the coroutine class Iterator { const coroutine_handle<promise_type>* m_h = nullptr; public: Iterator() = default; constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){} Iterator& operator++() { m_h->resume(); return *this; } Iterator operator++(int) { auto old(*this); m_h->resume(); return old; } int operator*() const { return m_h->promise().val; } bool operator!=(monostate) const noexcept { return !m_h->done(); return m_h && !m_h->done(); } bool operator==(monostate) const noexcept { return !operator!=(monostate{}); } }; constexpr Iterator begin() const noexcept { return Iterator(&coro); } constexpr monostate end() const noexcept { return monostate{}; } }; // Allow the iterator to be used like a standard library iterator namespace std { template<> class iterator_traits<TreeWalker::Iterator> { public: using difference_type = std::ptrdiff_t; using size_type = std::size_t; using value_type = int; using pointer = int*; using reference = int&; using iterator_category = std::input_iterator_tag; }; } // A coroutine that iterates though all of the fringe nodes TreeWalker WalkFringe(const BinaryTree& tree) { if(tree) { auto& left = tree.LeftChild(); auto& right = tree.RightChild(); if(!left && !right) { // a fringe node because it has no children co_yield tree.Value(); } for(auto v : WalkFringe(left)) { co_yield v; } for(auto v : WalkFringe(right)) { co_yield v; } } co_return; } // Print a tree void PrintTree(const BinaryTree& tree) { if(tree) { cout << "("; PrintTree(tree.LeftChild()); cout << tree.Value(); PrintTree(tree.RightChild()); cout <<")"; } } // Compare two trees void Compare(const BinaryTree& tree1, const BinaryTree& tree2) { // Create a lazy range for both trees auto walker1 = WalkFringe(tree1); auto walker2 = WalkFringe(tree2); // Compare the ranges. bool sameFringe = ranges::equal(walker1.begin(), walker1.end(), walker2.begin(), walker2.end()); // Print the results PrintTree(tree1); cout << (sameFringe ? " has same fringe as " : " has different fringe than "); PrintTree(tree2); cout << "\n"; } int main() { // Create two trees that that are different but have the same fringe nodes BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77, BinaryTree{77, BinaryTree{9}}}); BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{ BinaryTree{3}, 77, BinaryTree{9}}}); // Create a tree with a different fringe BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}}); // Compare the trees Compare(tree1, tree2); Compare(tree1, tree3); }
Selectively replace multiple instances of a character within a string
C++
Task This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically: * the first 'a' with 'A' * the second 'a' with 'B' * the fourth 'a' with 'C' * the fifth 'a' with 'D' * the first 'b' with 'E' * the second 'r' with 'F' Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD".
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, // replacement string is reversed {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second.empty()) { *it = f->second.back(); f->second.pop_back(); } } std::cout << magic << "\n"; }
Self-describing numbers
C++
{{task}}There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example, '''2020''' is a four-digit self describing number: * position 0 has value 2 and there are two 0s in the number; * position 1 has value 0 and there are no 1s in the number; * position 2 has value 2 and there are two 2s; * position 3 has value 0 and there are zero 3s. Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000. ;Task Description # Write a function/routine/method/... that will check whether a given positive integer is self-describing. # As an optional stretch goal - generate and display the set of self-describing numbers. ;Related tasks: * [[Fours is the number of letters in the ...]] * [[Look-and-say sequence]] * [[Number names]] * [[Self-referential sequence]] * [[Spelling of ordinal numbers]]
#include <iostream> //-------------------------------------------------------------------------------------------------- typedef unsigned long long bigint; //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- class sdn { public: bool check( bigint n ) { int cc = digitsCount( n ); return compare( n, cc ); } void displayAll( bigint s ) { for( bigint y = 1; y < s; y++ ) if( check( y ) ) cout << y << " is a Self-Describing Number." << endl; } private: bool compare( bigint n, int cc ) { bigint a; while( cc ) { cc--; a = n % 10; if( dig[cc] != a ) return false; n -= a; n /= 10; } return true; } int digitsCount( bigint n ) { int cc = 0; bigint a; memset( dig, 0, sizeof( dig ) ); while( n ) { a = n % 10; dig[a]++; cc++ ; n -= a; n /= 10; } return cc; } int dig[10]; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { sdn s; s. displayAll( 1000000000000 ); cout << endl << endl; system( "pause" ); bigint n; while( true ) { system( "cls" ); cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n; if( !n ) return 0; if( s.check( n ) ) cout << n << " is"; else cout << n << " is NOT"; cout << " a Self-Describing Number!" << endl << endl; system( "pause" ); } return 0; }
Self numbers
C++ from Java
A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43. The task is: Display the first 50 self numbers; I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture. 224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it. ;See also: ;*OEIS: A003052 - Self numbers or Colombian numbers ;*Wikipedia: Self numbers
#include <array> #include <iomanip> #include <iostream> const int MC = 103 * 1000 * 10000 + 11 * 9 + 1; std::array<bool, MC + 1> SV; void sieve() { std::array<int, 10000> dS; for (int a = 9, i = 9999; a >= 0; a--) { for (int b = 9; b >= 0; b--) { for (int c = 9, s = a + b; c >= 0; c--) { for (int d = 9, t = s + c; d >= 0; d--) { dS[i--] = t + d; } } } } for (int a = 0, n = 0; a < 103; a++) { for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) { for (int c = 0, s = d + dS[b] + n; c < 10000; c++) { SV[dS[c] + s++] = true; } } } } int main() { sieve(); std::cout << "The first 50 self numbers are:\n"; for (int i = 0, count = 0; count <= 50; i++) { if (!SV[i]) { count++; if (count <= 50) { std::cout << i << ' '; } else { std::cout << "\n\n Index Self number\n"; } } } for (int i = 0, limit = 1, count = 0; i < MC; i++) { if (!SV[i]) { if (++count == limit) { //System.out.printf("%,12d %,13d%n", count, i); std::cout << std::setw(12) << count << " " << std::setw(13) << i << '\n'; limit *= 10; } } } return 0; }
Semordnilap
C++
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: ''lager'' and ''regal'' ;Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples. Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair. (Note that the word "semordnilap" is not in the above dictionary.)
#include <fstream> #include <iostream> #include <set> #include <string> int main() { std::ifstream input("unixdict.txt"); if (input) { std::set<std::string> words; // previous words std::string word; // current word size_t count = 0; // pair count while (input >> word) { std::string drow(word.rbegin(), word.rend()); // reverse if (words.find(drow) == words.end()) { // pair not found words.insert(word); } else { // pair found if (count++ < 5) std::cout << word << ' ' << drow << '\n'; } } std::cout << "\nSemordnilap pairs: " << count << '\n'; return 0; } else return 1; // couldn't open input file }
Sequence: nth number with exactly n divisors
C++ from Java
Calculate the sequence where each term an is the nth that has '''n''' divisors. ;Task Show here, on this page, at least the first '''15''' terms of the sequence. ;See also :*OEIS:A073916 ;Related tasks :*[[Sequence: smallest number greater than previous term with exactly n divisors]] :*[[Sequence: smallest number with exactly n divisors]]
#include <iostream> #include <vector> std::vector<int> smallPrimes; bool is_prime(size_t test) { if (test < 2) { return false; } if (test % 2 == 0) { return test == 2; } for (size_t d = 3; d * d <= test; d += 2) { if (test % d == 0) { return false; } } return true; } void init_small_primes(size_t numPrimes) { smallPrimes.push_back(2); int count = 0; for (size_t n = 3; count < numPrimes; n += 2) { if (is_prime(n)) { smallPrimes.push_back(n); count++; } } } size_t divisor_count(size_t n) { size_t count = 1; while (n % 2 == 0) { n /= 2; count++; } for (size_t d = 3; d * d <= n; d += 2) { size_t q = n / d; size_t r = n % d; size_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { count *= 2; } return count; } uint64_t OEISA073916(size_t n) { if (is_prime(n)) { return (uint64_t) pow(smallPrimes[n - 1], n - 1); } size_t count = 0; uint64_t result = 0; for (size_t i = 1; count < n; i++) { if (n % 2 == 1) { // The solution for an odd (non-prime) term is always a square number size_t root = (size_t) sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { const int MAX = 15; init_small_primes(MAX); for (size_t n = 1; n <= MAX; n++) { if (n == 13) { std::cout << "A073916(" << n << ") = One more bit needed to represent result.\n"; } else { std::cout << "A073916(" << n << ") = " << OEISA073916(n) << '\n'; } } return 0; }
Sequence: smallest number greater than previous term with exactly n divisors
C++ from C
Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors. ;Task Show here, on this page, at least the first '''15''' terms of the sequence. ;See also :* OEIS:A069654 ;Related tasks :* [[Sequence: smallest number with exactly n divisors]] :* [[Sequence: nth number with exactly n divisors]]
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { cout << "The first " << MAX << " terms of the sequence are:" << endl; for (int i = 1, next = 1; next <= MAX; ++i) { if (next == count_divisors(i)) { cout << i << " "; next++; } } cout << endl; return 0; }
Sequence: smallest number greater than previous term with exactly n divisors
C++ from Pascal
Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors. ;Task Show here, on this page, at least the first '''15''' terms of the sequence. ;See also :* OEIS:A069654 ;Related tasks :* [[Sequence: smallest number with exactly n divisors]] :* [[Sequence: nth number with exactly n divisors]]
#include <cstdio> #include <chrono> using namespace std::chrono; const int MAX = 32; unsigned int getDividersCnt(unsigned int n) { unsigned int d = 3, q, dRes, res = 1; while (!(n & 1)) { n >>= 1; res++; } while ((d * d) <= n) { q = n / d; if (n % d == 0) { dRes = 0; do { dRes += res; n = q; q /= d; } while (n % d == 0); res += dRes; } d += 2; } return n != 1 ? res << 1 : res; } int main() { unsigned int i, nxt, DivCnt; printf("The first %d anti-primes plus are: ", MAX); auto st = steady_clock::now(); i = nxt = 1; do { if ((DivCnt = getDividersCnt(i)) == nxt ) { printf("%d ", i); if ((++nxt > 4) && (getDividersCnt(nxt) == 2)) i = (1 << (nxt - 1)) - 1; } i++; } while (nxt <= MAX); printf("%d ms", (int)(duration<double>(steady_clock::now() - st).count() * 1000)); }
Sequence: smallest number with exactly n divisors
C++ from C
Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors. ;Task Show here, on this page, at least the first '''15''' terms of the sequence. ;Related tasks: :* [[Sequence: smallest number greater than previous term with exactly n divisors]] :* [[Sequence: nth number with exactly n divisors]] ;See also: :* OEIS:A005179
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; cout << "The first " << MAX << " terms of the sequence are:" << endl; for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) cout << seq[i] << " "; cout << endl; return 0; }
Set consolidation
C++
Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is: * The two input sets if no common item exists between the two input sets of items. * The single set that is the union of the two input sets if they share a common item. Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N<2 then consolidation has no strict meaning and the input can be returned. ;'''Example 1:''' :Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input. ;'''Example 2:''' :Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc). ;'''Example 3:''' :Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D} ;'''Example 4:''' :The consolidation of the five sets: ::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H} :Is the two sets: ::{A, C, B, D}, and {G, F, I, H, K} '''See also''' * Connected component (graph theory) * [[Range consolidation]]
#include <algorithm> #include <iostream> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; // Consolidation using a brute force approach void SimpleConsolidate(vector<unordered_set<char>>& sets) { // Loop through the sets in reverse and consolidate them for(auto last = sets.rbegin(); last != sets.rend(); ++last) for(auto other = last + 1; other != sets.rend(); ++other) { bool hasIntersection = any_of(last->begin(), last->end(), [&](auto val) { return other->contains(val); }); if(hasIntersection) { other->merge(*last); sets.pop_back(); break; } } } // As a second approach, use the connected-component-finding-algorithm // from the C# entry to consolidate struct Node { char Value; Node* Parent = nullptr; }; Node* FindTop(Node& node) { auto top = &node; while (top != top->Parent) top = top->Parent; for(auto element = &node; element->Parent != top; ) { // Point the elements to top to make it faster for the next time auto parent = element->Parent; element->Parent = top; element = parent; } return top; } vector<unordered_set<char>> FastConsolidate(const vector<unordered_set<char>>& sets) { unordered_map<char, Node> elements; for(auto& set : sets) { Node* top = nullptr; for(auto val : set) { auto itr = elements.find(val); if(itr == elements.end()) { // A new value has been found auto& ref = elements[val] = Node{val, nullptr}; if(!top) top = &ref; ref.Parent = top; } else { auto newTop = FindTop(itr->second); if(top) { top->Parent = newTop; itr->second.Parent = newTop; } else { top = newTop; } } } } unordered_map<char, unordered_set<char>> groupedByTop; for(auto& e : elements) { auto& element = e.second; groupedByTop[FindTop(element)->Value].insert(element.Value); } vector<unordered_set<char>> ret; for(auto& itr : groupedByTop) { ret.push_back(move(itr.second)); } return ret; } void PrintSets(const vector<unordered_set<char>>& sets) { for(const auto& set : sets) { cout << "{ "; for(auto value : set){cout << value << " ";} cout << "} "; } cout << "\n"; } int main() { const unordered_set<char> AB{'A', 'B'}, CD{'C', 'D'}, DB{'D', 'B'}, HIJ{'H', 'I', 'K'}, FGH{'F', 'G', 'H'}; vector <unordered_set<char>> AB_CD {AB, CD}; vector <unordered_set<char>> AB_DB {AB, DB}; vector <unordered_set<char>> AB_CD_DB {AB, CD, DB}; vector <unordered_set<char>> HIJ_AB_CD_DB_FGH {HIJ, AB, CD, DB, FGH}; PrintSets(FastConsolidate(AB_CD)); PrintSets(FastConsolidate(AB_DB)); PrintSets(FastConsolidate(AB_CD_DB)); PrintSets(FastConsolidate(HIJ_AB_CD_DB_FGH)); SimpleConsolidate(AB_CD); SimpleConsolidate(AB_DB); SimpleConsolidate(AB_CD_DB); SimpleConsolidate(HIJ_AB_CD_DB_FGH); PrintSets(AB_CD); PrintSets(AB_DB); PrintSets(AB_CD_DB); PrintSets(HIJ_AB_CD_DB_FGH); }
Set of real numbers
C++ from Java
All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of "between", depending on open or closed boundary: * [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' } * (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' } * [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' } * (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' } Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty. '''Task''' * Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below. * Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets): :* ''x'' ''A'': determine if ''x'' is an element of ''A'' :: example: 1 is in [1, 2), while 2, 3, ... are not. :* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''} :: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3] :* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''} :: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set :* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''} :: example: [0, 2) - (1, 3) = [0, 1] * Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets: :* (0, 1] [0, 2) :* [0, 2) (1, 2] :* [0, 3) - (0, 1) :* [0, 3) - [0, 1] '''Implementation notes''' * 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply. * Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored. * You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). '''Optional work''' * Create a function to determine if a given set is empty (contains no element). * Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that |sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.
#include <cassert> #include <functional> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }; class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate; public: RealSet(double low, double high, const std::function<bool(double)>& predicate) { this->low = low; this->high = high; this->predicate = predicate; } RealSet(double start, double end, RangeType rangeType) { low = start; high = end; switch (rangeType) { case CLOSED: predicate = [start, end](double d) { return start <= d && d <= end; }; break; case BOTH_OPEN: predicate = [start, end](double d) { return start < d && d < end; }; break; case LEFT_OPEN: predicate = [start, end](double d) { return start < d && d <= end; }; break; case RIGHT_OPEN: predicate = [start, end](double d) { return start <= d && d < end; }; break; default: assert(!"Unexpected range type encountered."); } } bool contains(double d) const { return predicate(d); } RealSet unionSet(const RealSet& rhs) const { double low2 = fmin(low, rhs.low); double high2 = fmax(high, rhs.high); return RealSet( low2, high2, [this, &rhs](double d) { return predicate(d) || rhs.predicate(d); } ); } RealSet intersect(const RealSet& rhs) const { double low2 = fmin(low, rhs.low); double high2 = fmax(high, rhs.high); return RealSet( low2, high2, [this, &rhs](double d) { return predicate(d) && rhs.predicate(d); } ); } RealSet subtract(const RealSet& rhs) const { return RealSet( low, high, [this, &rhs](double d) { return predicate(d) && !rhs.predicate(d); } ); } double length() const { if (isinf(low) || isinf(high)) return -1.0; // error value if (high <= low) return 0.0; double p = low; int count = 0; do { if (predicate(p)) count++; p += interval; } while (p < high); return count * interval; } bool empty() const { if (high == low) { return !predicate(low); } return length() == 0.0; } }; int main() { using namespace std; RealSet a(0.0, 1.0, LEFT_OPEN); RealSet b(0.0, 2.0, RIGHT_OPEN); RealSet c(1.0, 2.0, LEFT_OPEN); RealSet d(0.0, 3.0, RIGHT_OPEN); RealSet e(0.0, 1.0, BOTH_OPEN); RealSet f(0.0, 1.0, CLOSED); RealSet g(0.0, 0.0, CLOSED); for (int i = 0; i <= 2; ++i) { cout << "(0, 1] ∪ [0, 2) contains " << i << " is " << boolalpha << a.unionSet(b).contains(i) << "\n"; cout << "[0, 2) ∩ (1, 2] contains " << i << " is " << boolalpha << b.intersect(c).contains(i) << "\n"; cout << "[0, 3) - (0, 1) contains " << i << " is " << boolalpha << d.subtract(e).contains(i) << "\n"; cout << "[0, 3) - [0, 1] contains " << i << " is " << boolalpha << d.subtract(f).contains(i) << "\n"; cout << endl; } cout << "[0, 0] is empty is " << boolalpha << g.empty() << "\n"; cout << endl; RealSet aa( 0.0, 10.0, [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x * x)) > 0.5; } ); RealSet bb( 0.0, 10.0, [](double x) { return (0.0 < x && x < 10.0) && abs(sin(M_PI * x)) > 0.5; } ); auto cc = aa.subtract(bb); cout << "Approximate length of A - B is " << cc.length() << endl; return 0; }
Set right-adjacent bits
C++
Given a left-to-right ordered collection of e bits, b, where 1 <= e <= 10000, and a zero or more integer n : * Output the result of setting the n bits to the right of any set bit in b (if those bits are present in b and therefore also preserving the width, e). '''Some examples:''' Set of examples showing how one bit in a nibble gets changed: n = 2; Width e = 4: Input b: 1000 Result: 1110 Input b: 0100 Result: 0111 Input b: 0010 Result: 0011 Input b: 0000 Result: 0000 Set of examples with the same input with set bits of varying distance apart: n = 0; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 010000000000100000000010000000010000000100000010000010000100010010 n = 1; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011000000000110000000011000000011000000110000011000011000110011011 n = 2; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011100000000111000000011100000011100000111000011100011100111011111 n = 3; Width e = 66: Input b: 010000000000100000000010000000010000000100000010000010000100010010 Result: 011110000000111100000011110000011110000111100011110011110111111111 '''Task:''' * Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width e. * Use it to show, here, the results for the input examples above. * Print the output aligned in a way that allows easy checking by eye of the binary input vs output.
#include <iostream> #include <string> void setRightAdjacent(std::string text, int32_t number) { std::cout << "n = " << number << ", Width = " << text.size() << ", Input: " << text << std::endl; std::string result = text; for ( uint32_t i = 0; i < result.size(); i++ ) { if ( text[i] == '1' ) { for ( uint32_t j = i + 1; j <= i + number && j < result.size(); j++ ) { result[j] = '1'; } } } std::cout << std::string(16 + std::to_string(text.size()).size(), ' ') << "Result: " + result << "\n" << std::endl; } int main() { setRightAdjacent("1000", 2); setRightAdjacent("0100", 2); setRightAdjacent("0010", 2); setRightAdjacent("0000", 2); std::string test = "010000000000100000000010000000010000000100000010000010000100010010"; setRightAdjacent(test, 0); setRightAdjacent(test, 1); setRightAdjacent(test, 2); setRightAdjacent(test, 3); }
Shoelace formula for polygonal area
C++ from D
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) ;Task: Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
Shortest common supersequence
C++ from Java
The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task. ;;Task: Given two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique. Demonstrate this by printing s where u = "abcbdab" and v = "bdcaba". ;Also see: * Wikipedia: shortest common supersequence
#include <iostream> std::string scs(std::string x, std::string y) { if (x.empty()) { return y; } if (y.empty()) { return x; } if (x[0] == y[0]) { return x[0] + scs(x.substr(1), y.substr(1)); } if (scs(x, y.substr(1)).size() <= scs(x.substr(1), y).size()) { return y[0] + scs(x, y.substr(1)); } else { return x[0] + scs(x.substr(1), y); } } int main() { auto res = scs("abcbdab", "bdcaba"); std::cout << res << '\n'; return 0; }
Show ASCII table
C++
Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.
#include <string> #include <iomanip> #include <iostream> inline constexpr auto HEIGHT = 16; inline constexpr auto WIDTH = 6; inline constexpr auto ASCII_START = 32; // ASCII special characters inline constexpr auto SPACE = 32; inline constexpr auto DELETE = 127; std::string displayAscii(char ascii) { switch (ascii) { case SPACE: return "Spc"; case DELETE: return "Del"; default: return std::string(1, ascii); } } int main() { for (std::size_t row = 0; row < HEIGHT; ++row) { for (std::size_t col = 0; col < WIDTH; ++col) { const auto ascii = ASCII_START + row + col * HEIGHT; std::cout << std::right << std::setw(3) << ascii << " : " << std::left << std::setw(6) << displayAscii(ascii); } std::cout << '\n'; } }
Sierpinski pentagon
C++ from D
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. ;See also * Sierpinski pentagon
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); /// Define a position struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } /// Mock turtle implementation sufficiant to handle "drawing" the pentagons struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } /// Move the turtle through space void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } /// Turn the turtle void right(double angle) { theta -= angle; } /// Start/Stop exporting the points of the polygon void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; /// Use the provided turtle to draw a pentagon of the specified size void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } /// Draw a sierpinski pentagon of the desired order void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { // create four more turtles for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); // recurse for each spawned turtle sierpinski(order, spawn, new_size); } // recurse for the original turtle sierpinski(order, turtle, new_size); } else { // The bottom has been reached for this turtle pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } /// Run the generation of a P(5) sierpinksi pentagon int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" -//W3C//DTD SVG 1.1//EN\"\n"; std::cout << " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"; std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n"; size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
Sierpinski triangle/Graphical
C++
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this: [[File:Sierpinski_Triangle_Unicon.PNG]]
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; 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 sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
Smith numbers
C++
sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are ''excluded'' as they (naturally) satisfy this condition! Smith numbers are also known as ''joke'' numbers. ;Example Using the number '''166''' Find the prime factors of '''166''' which are: '''2''' x '''83''' Then, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13''' Then, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13''' Therefore, the number '''166''' is a Smith number. ;Task Write a program to find all Smith numbers ''below'' 10000. ;See also * from Wikipedia: [Smith number]. * from MathWorld: [Smith number]. * from OEIS A6753: [OEIS sequence A6753]. * from OEIS A104170: [Number of Smith numbers below 10^n]. * from The Prime pages: [Smith numbers].
#include <iostream> #include <vector> #include <iomanip> void primeFactors( unsigned n, std::vector<unsigned>& r ) { int f = 2; if( n == 1 ) r.push_back( 1 ); else { while( true ) { if( !( n % f ) ) { r.push_back( f ); n /= f; if( n == 1 ) return; } else f++; } } } unsigned sumDigits( unsigned n ) { unsigned sum = 0, m; while( n ) { m = n % 10; sum += m; n -= m; n /= 10; } return sum; } unsigned sumDigits( std::vector<unsigned>& v ) { unsigned sum = 0; for( std::vector<unsigned>::iterator i = v.begin(); i != v.end(); i++ ) { sum += sumDigits( *i ); } return sum; } void listAllSmithNumbers( unsigned n ) { std::vector<unsigned> pf; for( unsigned i = 4; i < n; i++ ) { primeFactors( i, pf ); if( pf.size() < 2 ) continue; if( sumDigits( i ) == sumDigits( pf ) ) std::cout << std::setw( 4 ) << i << " "; pf.clear(); } std::cout << "\n\n"; } int main( int argc, char* argv[] ) { listAllSmithNumbers( 10000 ); return 0; }
Soloway's recurring rainfall
C++
Soloway's Recurring Rainfall is commonly used to assess general programming knowledge by requiring basic program structure, input/output, and program exit procedure. '''The problem:''' Write a program that will read in integers and output their average. Stop reading when the value 99999 is input. For languages that aren't traditionally interactive, the program can read in values as makes sense and stopping once 99999 is encountered. The classic rainfall problem comes from identifying success of Computer Science programs with their students, so the original problem statement is written above -- though it may not strictly apply to a given language in the modern era. '''Implementation Details:''' * Only Integers are to be accepted as input * Output should be floating point * Rainfall can be negative (https://www.geographyrealm.com/what-is-negative-rainfall/) * For languages where the user is inputting data, the number of data inputs can be "infinite" * A complete implementation should handle error cases reasonably (asking the user for more input, skipping the bad value when encountered, etc) The purpose of this problem, as originally proposed in the 1980's through its continued use today, is to just show fundamentals of CS: iteration, branching, program structure, termination, management of data types, input/output (where applicable), etc with things like input validation or management of numerical limits being more "advanced". It isn't meant to literally be a rainfall calculator so implementations should strive to implement the solution clearly and simply. '''References:''' * http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf * https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf * https://en.wikipedia.org/wiki/Moving_average#Cumulative_average
#include <iostream> #include <limits> int main() { float currentAverage = 0; unsigned int currentEntryNumber = 0; for (;;) { int entry; std::cout << "Enter rainfall int, 99999 to quit: "; std::cin >> entry; if (!std::cin.fail()) { if (entry == 99999) { std::cout << "User requested quit." << std::endl; break; } else { currentEntryNumber++; currentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage; std::cout << "New Average: " << currentAverage << std::endl; } } else { std::cout << "Invalid input" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } return 0; }
Solve a Hidato puzzle
C++
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: * You are given a grid with some numbers placed in it. The other squares in the grid will be blank. ** The grid is not necessarily rectangular. ** The grid may have holes in it. ** The grid is always connected. ** The number "1" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. ** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. * The aim is to place a natural number in each blank square so that in the sequence of numbered squares from "1" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). ** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. ** A square may only contain one number. * In a proper Hidato puzzle, the solution is unique. For example the following problem Sample Hidato problem, from Wikipedia has the following solution, with path marked on it: Solution to sample Hidato problem ;Related tasks: * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Holy Knight's tour]] * [[Solve a Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]];
#include <iostream> #include <sstream> #include <iterator> #include <vector> //------------------------------------------------------------------------------ using namespace std; //------------------------------------------------------------------------------ struct node { int val; unsigned char neighbors; }; //------------------------------------------------------------------------------ class hSolver { public: hSolver() { dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; dy[0] = -1; dy[1] = -1; dy[2] = -1; dy[3] = 0; dy[4] = 0; dy[5] = 1; dy[6] = 1; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = 0; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); weHave = new bool[len + 1]; memset( weHave, 0, len + 1 ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); if( arr[c].val > 0 ) weHave[arr[c].val] = true; if( max < arr[c].val ) max = arr[c].val; c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; delete [] weHave; } private: bool search( int x, int y, int w ) { if( w == max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); if( weHave[w] ) { for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == w ) if( search( a, b, w + 1 ) ) return true; } } return false; } for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int m = -1, a, b; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( !yy && !xx ) continue; m++; a = x + xx, b = y + yy; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << m ); } return c; } void solveIt() { int x, y; findStart( x, y ); if( x < 0 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, 2 ); } void findStart( int& x, int& y ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 1 ) { x = a; y = b; return; } x = y = -1; } int wid, hei, max, dx[8], dy[8]; node* arr; bool* weHave; }; //------------------------------------------------------------------------------ int main( int argc, char* argv[] ) { int wid; string p = ". 33 35 . . * * * . . 24 22 . * * * . . . 21 . . * * . 26 . 13 40 11 * * 27 . . . 9 . 1 * * * . . 18 . . * * * * * . 7 . . * * * * * * 5 ."; wid = 8; //string p = "54 . 60 59 . 67 . 69 . . 55 . . 63 65 . 72 71 51 50 56 62 . * * * * . . . 14 * * 17 . * 48 10 11 * 15 . 18 . 22 . 46 . * 3 . 19 23 . . 44 . 5 . 1 33 32 . . 43 7 . 36 . 27 . 31 42 . . 38 . 35 28 . 30"; wid = 9; //string p = ". 58 . 60 . . 63 66 . 57 55 59 53 49 . 65 . 68 . 8 . . 50 . 46 45 . 10 6 . * * * . 43 70 . 11 12 * * * 72 71 . . 14 . * * * 30 39 . 15 3 17 . 28 29 . . 40 . . 19 22 . . 37 36 . 1 20 . 24 . 26 . 34 33"; wid = 9; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); hSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); } //--------------------------------------------------------------------------------------------------
Solve a Holy Knight's tour
C++
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: ;Example: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. ;Related tasks: * [[A* search algorithm]] * [[Knight's tour]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; //p = "* . . . * * * * * . * . . * * * * . . . . . . . . . . * * . * . . * . * * . . . 1 . . . . . . * * * . . * . * * * * * . . . * *"; wid = 8; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Solve a Hopido puzzle
C++
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7x7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . . Extra credits are available for other interesting designs. ;Related tasks: * [[A* search algorithm]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Solve a Numbrix puzzle
C++
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: ;Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 ;Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 ;Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. ;Related tasks: * [[A* search algorithm]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve the no connection puzzle]]
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false); for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; } solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } } private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true; node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; } for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == 0) { arr[a + b * wid].val = w; if (search(a, b, w + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; } hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int a = x + dx[xx], b = y + dy[xx]; if (a < 0 || b < 0 || a >= wid || b >= hei) continue; if (arr[a + b * wid].val > -1) retval.set(xx); } return retval; } void solveIt() { int x, y, z; findStart(x, y, z); if (z == 99999) { cout << "\nCan't find start point!\n"; return; } search(x, y, z + 1, 1); if (z > 1) search(x, y, z - 1, -1); } void findStart(int& x, int& y, int& z) { z = 99999; for (int b = 0; b < hei; b++) for (int a = 0; a < wid; a++) if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z) { x = a; y = b; z = arr[a + wid * b].val; } } vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; }; //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { int wid; string p; //p = ". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . ."; wid = 9; //p = ". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . ."; wid = 9; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; istringstream iss(p); vector<string> puzz; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz)); nSolver s; s.solve(puzz, wid); int c = 0; for (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }
Sparkline in unicode
C++
A sparkline is a graph of successive values laid out horizontally where the height of the line is proportional to the values in succession. ;Task: Use the following series of Unicode characters to create a program that takes a series of numbers separated by one or more whitespace or comma characters and generates a sparkline-type bar graph of the values on a single line of output. The eight characters: '########' (Unicode values U+2581 through U+2588). Use your program to show sparklines for the following input, here on this page: # 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 # 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 :(note the mix of separators in this second case)! ;Notes: * A space is not part of the generated sparkline. * The sparkline may be accompanied by simple statistics of the data such as its range. * A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases: :: "0, 1, 19, 20" -> #### :: (Aiming to use just two spark levels) :: "0, 999, 4000, 4999, 7000, 7999" -> ###### :: (Aiming to use just three spark levels) :: It may be helpful to include these cases in output tests. * You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = ", "; std::vector<float> data; // Get first non-delimiter std::string::size_type last = spark.find_first_not_of(delim, 0); // Get end of token std::string::size_type pos = spark.find_first_of(delim, last); while( pos != std::string::npos || last != std::string::npos ){ std::string tok = spark.substr(last, pos-last); // Convert to float: std::stringstream ss(tok); float entry; ss >> entry; data.push_back( entry ); last = spark.find_first_not_of(delim, pos); pos = spark.find_first_of(delim, last); } // Get range of dataset float min = *std::min_element( data.begin(), data.end() ); float max = *std::max_element( data.begin(), data.end() ); float skip = (charset.length()-1) / (max - min); std::wcout<<L"Min: "<<min<<L"; Max: "<<max<<L"; Range: "<<(max-min)<<std::endl; std::vector<float>::const_iterator it; for(it = data.begin(); it != data.end(); it++){ float v = ( (*it) - min ) * skip; std::wcout<<charset[ (int)floor( v ) ]; } std::wcout<<std::endl; } private: std::wstring &charset; }; int main( int argc, char **argv ){ std::wstring charset = L"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"; // Mainly just set up utf-8, so wcout won't narrow our characters. std::locale::global(std::locale("en_US.utf8")); Sparkline sl(charset); sl.print("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"); sl.print("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"); return 0; }
Spelling of ordinal numbers
C++
'''Ordinal numbers''' (as used in this Rosetta Code task), are numbers that describe the ''position'' of something in a list. It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number. The ordinal numbers are (at least, one form of them): 1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th *** etc sometimes expressed as: 1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th *** For this task, the following (English-spelled form) will be used: first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth Furthermore, the American version of numbers will be used here (as opposed to the British). '''2,000,000,000''' is two billion, ''not'' two milliard. ;Task: Write a driver and a function (subroutine/routine ***) that returns the English-spelled ordinal version of a specified number (a positive integer). Optionally, try to support as many forms of an integer that can be expressed: '''123''' '''00123.0''' '''1.23e2''' all are forms of the same integer. Show all output here. ;Test cases: Use (at least) the test cases of: 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 ;Related tasks: * [[Number names]] * [[N'th]]
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; integer number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string number_name(integer n, bool ordinal) { std::string result; if (n < 20) result = get_name(small[n], ordinal); else if (n < 100) { if (n % 10 == 0) { result = get_name(tens[n/10 - 2], ordinal); } else { result = get_name(tens[n/10 - 2], false); result += "-"; result += get_name(small[n % 10], ordinal); } } else { const named_number& num = get_named_number(n); integer p = num.number; result = number_name(n/p, false); result += " "; if (n % p == 0) { result += get_name(num, ordinal); } else { result += get_name(num, false); result += " "; result += number_name(n % p, ordinal); } } return result; } void test_ordinal(integer n) { std::cout << n << ": " << number_name(n, true) << '\n'; } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
Sphenic numbers
C++
Definitions A '''sphenic number''' is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below). For the purposes of this task, a '''sphenic triplet''' is a group of three sphenic numbers which are consecutive. Note that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct. ;Examples 30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one. [1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers. ;Task Calculate and show here: 1. All sphenic numbers less than 1,000. 2. All sphenic triplets less than 10,000. ;Stretch 3. How many sphenic numbers are there less than 1 million? 4. How many sphenic triplets are there less than 1 million? 5. What is the 200,000th sphenic number and its 3 prime factors? 6. What is the 5,000th sphenic triplet? Hint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6. ;References * Wikipedia: Sphenic number * OEIS:A007304 - Sphenic numbers * OEIS:A165936 - Sphenic triplets (in effect) ;Related tasks * [[Almost prime]] * [[Square-free integers]]
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(int limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3, sq = 9; sq < limit; p += 2) { if (sieve[p]) { for (int q = sq; q < limit; q += p << 1) sieve[q] = false; } sq += (p + 1) << 2; } return sieve; } std::vector<int> prime_factors(int n) { std::vector<int> factors; if (n > 1 && (n & 1) == 0) { factors.push_back(2); while ((n & 1) == 0) n >>= 1; } for (int p = 3; p * p <= n; p += 2) { if (n % p == 0) { factors.push_back(p); while (n % p == 0) n /= p; } } if (n > 1) factors.push_back(n); return factors; } int main() { const int limit = 1000000; const int imax = limit / 6; std::vector<bool> sieve = prime_sieve(imax + 1); std::vector<bool> sphenic(limit + 1, false); for (int i = 0; i <= imax; ++i) { if (!sieve[i]) continue; int jmax = std::min(imax, limit / (i * i)); if (jmax <= i) break; for (int j = i + 1; j <= jmax; ++j) { if (!sieve[j]) continue; int p = i * j; int kmax = std::min(imax, limit / p); if (kmax <= j) break; for (int k = j + 1; k <= kmax; ++k) { if (!sieve[k]) continue; assert(p * k <= limit); sphenic[p * k] = true; } } } std::cout << "Sphenic numbers < 1000:\n"; for (int i = 0, n = 0; i < 1000; ++i) { if (!sphenic[i]) continue; ++n; std::cout << std::setw(3) << i << (n % 15 == 0 ? '\n' : ' '); } std::cout << "\nSphenic triplets < 10,000:\n"; for (int i = 0, n = 0; i < 10000; ++i) { if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) { ++n; std::cout << "(" << i - 2 << ", " << i - 1 << ", " << i << ")" << (n % 3 == 0 ? '\n' : ' '); } } int count = 0, triplets = 0, s200000 = 0, t5000 = 0; for (int i = 0; i < limit; ++i) { if (!sphenic[i]) continue; ++count; if (count == 200000) s200000 = i; if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) { ++triplets; if (triplets == 5000) t5000 = i; } } std::cout << "\nNumber of sphenic numbers < 1,000,000: " << count << '\n'; std::cout << "Number of sphenic triplets < 1,000,000: " << triplets << '\n'; auto factors = prime_factors(s200000); assert(factors.size() == 3); std::cout << "The 200,000th sphenic number: " << s200000 << " = " << factors[0] << " * " << factors[1] << " * " << factors[2] << '\n'; std::cout << "The 5,000th sphenic triplet: (" << t5000 - 2 << ", " << t5000 - 1 << ", " << t5000 << ")\n"; }
Split a character string based on change of character
C++
Split a (character) string into comma (plus a blank) delimited strings based on a change of character (left to right). Show the output here (use the 1st example below). Blanks should be treated as any other character (except they are problematic to display clearly). The same applies to commas. For instance, the string: gHHH5YY++///\ should be split and show: g, HHH, 5, YY, ++, ///, \
// Solution for http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character #include<string> #include<iostream> auto split(const std::string& input, const std::string& delim){ std::string res; for(auto ch : input){ if(!res.empty() && ch != res.back()) res += delim; res += ch; } return res; } int main(){ std::cout << split("gHHH5 ))YY++,,,///\\", ", ") << std::endl; }
Square-free integers
C++
Write a function to test if a number is ''square-free''. A ''square-free'' is an integer which is divisible by no perfect square other than '''1''' (unity). For this task, only positive square-free numbers will be used. Show here (on this page) all square-free integers (in a horizontal format) that are between: ::* '''1''' ---> '''145''' (inclusive) ::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive) (One trillion = 1,000,000,000,000) Show here (on this page) the count of square-free integers from: ::* '''1''' ---> one hundred (inclusive) ::* '''1''' ---> one thousand (inclusive) ::* '''1''' ---> ten thousand (inclusive) ::* '''1''' ---> one hundred thousand (inclusive) ::* '''1''' ---> one million (inclusive) ;See also: :* the Wikipedia entry: square-free integer
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return false; } } return true; } void print_square_free_numbers(integer from, integer to) { std::cout << "Square-free numbers between " << from << " and " << to << ":\n"; std::string line; for (integer i = from; i <= to; ++i) { if (square_free(i)) { if (!line.empty()) line += ' '; line += std::to_string(i); if (line.size() >= 80) { std::cout << line << '\n'; line.clear(); } } } if (!line.empty()) std::cout << line << '\n'; } void print_square_free_count(integer from, integer to) { integer count = 0; for (integer i = from; i <= to; ++i) { if (square_free(i)) ++count; } std::cout << "Number of square-free numbers between " << from << " and " << to << ": " << count << '\n'; } int main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000LL, 1000000000145LL); print_square_free_count(1, 100); print_square_free_count(1, 1000); print_square_free_count(1, 10000); print_square_free_count(1, 100000); print_square_free_count(1, 1000000); return 0; }
Square but not cube
C++ from C
Show the first '''30''' positive integers which are squares but not cubes of such integers. Optionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.
#include <iostream> #include <cmath> int main() { int n = 1; int count = 0; int sq; int cr; for (; count < 30; ++n) { sq = n * n; cr = cbrt(sq); if (cr * cr * cr != sq) { count++; std::cout << sq << '\n'; } else { std::cout << sq << " is square and cube\n"; } } return 0; }
Stair-climbing puzzle
C++
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers? Here's a pseudo-code of a simple recursive solution without using variables: func step_up() { if not step() { step_up(); step_up(); } } Inductive proof that step_up() steps up one step, if it terminates: * Base case (if the step() call returns true): it stepped up one step. QED * Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED The second (tail) recursion above can be turned into an iteration, as follows: func step_up() { while not step() { step_up(); } }
void step_up() { for (int i = 0; i < 1; step()? ++i : --i); }
Statistics/Normal distribution
C++
The derive normally distributed random numbers from a uniform generator. ;The task: # Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. # Mention any native language support for the generation of normally distributed random numbers. ;Reference: * You may refer to code in [[Statistics/Basic]] if available.
#include <random> #include <map> #include <string> #include <iostream> #include <cmath> #include <iomanip> int main( ) { std::random_device myseed ; std::mt19937 engine ( myseed( ) ) ; std::normal_distribution<> normDistri ( 2 , 3 ) ; std::map<int , int> normalFreq ; int sum = 0 ; //holds the sum of the randomly created numbers double mean = 0.0 ; double stddev = 0.0 ; for ( int i = 1 ; i < 10001 ; i++ ) ++normalFreq[ normDistri ( engine ) ] ; for ( auto MapIt : normalFreq ) { sum += MapIt.first * MapIt.second ; } mean = sum / 10000 ; stddev = sqrt( sum / 10000 ) ; std::cout << "The mean of the distribution is " << mean << " , the " ; std::cout << "standard deviation " << stddev << " !\n" ; std::cout << "And now the histogram:\n" ; for ( auto MapIt : normalFreq ) { std::cout << std::left << std::setw( 4 ) << MapIt.first << std::string( MapIt.second / 100 , '*' ) << std::endl ; } return 0 ; }
Stern-Brocot sequence
C++
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]]. # The first and second members of the sequence are both 1: #* 1, 1 # Start by considering the second member of the sequence # Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence: #* 1, 1, 2 # Append the considered member of the sequence to the end of the sequence: #* 1, 1, 2, 1 # Consider the next member of the series, (the third member i.e. 2) # GOTO 3 #* #* --- Expanding another loop we get: --- #* # Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence: #* 1, 1, 2, 1, 3 # Append the considered member of the sequence to the end of the sequence: #* 1, 1, 2, 1, 3, 2 # Consider the next member of the series, (the fourth member i.e. 1) ;The task is to: * Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. * Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) * Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence. * Show the (1-based) index of where the number 100 first appears in the sequence. * Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. ;Related tasks: :* [[Fusc sequence]]. :* [[Continued fraction/Arithmetic]] ;Ref: * Infinite Fractions - Numberphile (Video). * Trees, Teeth, and Time: The mathematics of clock making. * A002487 The On-Line Encyclopedia of Integer Sequences.
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
Stream merge
C++ from C#
2-stream merge : Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. : Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. ; ''N''-stream merge : The same as above, but reading from ''N'' sources. : Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]]. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
//#include <functional> #include <iostream> #include <vector> template <typename C, typename A> void merge2(const C& c1, const C& c2, const A& action) { auto i1 = std::cbegin(c1); auto i2 = std::cbegin(c2); while (i1 != std::cend(c1) && i2 != std::cend(c2)) { if (*i1 <= *i2) { action(*i1); i1 = std::next(i1); } else { action(*i2); i2 = std::next(i2); } } while (i1 != std::cend(c1)) { action(*i1); i1 = std::next(i1); } while (i2 != std::cend(c2)) { action(*i2); i2 = std::next(i2); } } template <typename A, typename C> void mergeN(const A& action, std::initializer_list<C> all) { using I = typename C::const_iterator; using R = std::pair<I, I>; std::vector<R> vit; for (auto& c : all) { auto p = std::make_pair(std::cbegin(c), std::cend(c)); vit.push_back(p); } bool done; R* least; do { done = true; auto it = vit.begin(); auto end = vit.end(); least = nullptr; // search for the first non-empty range to use for comparison while (it != end && it->first == it->second) { it++; } if (it != end) { least = &(*it); } while (it != end) { // search for the next non-empty range to use for comaprison while (it != end && it->first == it->second) { it++; } if (least != nullptr && it != end && it->first != it->second && *(it->first) < *(least->first)) { // found a smaller value least = &(*it); } if (it != end) { it++; } } if (least != nullptr && least->first != least->second) { done = false; action(*(least->first)); least->first = std::next(least->first); } } while (!done); } void display(int num) { std::cout << num << ' '; } int main() { std::vector<int> v1{ 0, 3, 6 }; std::vector<int> v2{ 1, 4, 7 }; std::vector<int> v3{ 2, 5, 8 }; merge2(v2, v1, display); std::cout << '\n'; mergeN(display, { v1 }); std::cout << '\n'; mergeN(display, { v3, v2, v1 }); std::cout << '\n'; }
Strip control codes and extended characters from a string
C++
Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results: :* a string with control codes stripped (but extended characters not stripped) :* a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
#include <string> #include <iostream> #include <algorithm> #include <boost/lambda/lambda.hpp> #include <boost/lambda/casts.hpp> #include <ctime> #include <cstdlib> using namespace boost::lambda ; struct MyRandomizer { char operator( )( ) { return static_cast<char>( rand( ) % 256 ) ; } } ; std::string deleteControls ( std::string startstring ) { std::string noControls( " " ) ;//creating space for //the standard algorithm remove_copy_if std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noControls.begin( ) , ll_static_cast<int>( _1 ) < 32 && ll_static_cast<int>( _1 ) == 127 ) ; return noControls ; } std::string deleteExtended( std::string startstring ) { std::string noExtended ( " " ) ;//same as above std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noExtended.begin( ) , ll_static_cast<int>( _1 ) > 127 || ll_static_cast<int>( _1 ) < 32 ) ; return noExtended ; } int main( ) { std::string my_extended_string ; for ( int i = 0 ; i < 40 ; i++ ) //we want the extended string to be 40 characters long my_extended_string.append( " " ) ; srand( time( 0 ) ) ; std::generate_n( my_extended_string.begin( ) , 40 , MyRandomizer( ) ) ; std::string no_controls( deleteControls( my_extended_string ) ) ; std::string no_extended ( deleteExtended( my_extended_string ) ) ; std::cout << "string with all characters: " << my_extended_string << std::endl ; std::cout << "string without control characters: " << no_controls << std::endl ; std::cout << "string without extended characters: " << no_extended << std::endl ; return 0 ; }
Subleq
C++
One-Instruction Set Computer (OISC). It is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. ;Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers. These integers may be interpreted in three ways: ::::* simple numeric values ::::* memory addresses ::::* characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows: :# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory. :# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''. :# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused. :# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused. :# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer. :# If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero). For purposes of this task, show the output of your solution when fed the below "Hello, world!" program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1 ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#include <fstream> #include <iostream> #include <iterator> #include <vector> class subleq { public: void load_and_run( std::string file ) { std::ifstream f( file.c_str(), std::ios_base::in ); std::istream_iterator<int> i_v, i_f( f ); std::copy( i_f, i_v, std::back_inserter( memory ) ); f.close(); run(); } private: void run() { int pc = 0, next, a, b, c; char z; do { next = pc + 3; a = memory[pc]; b = memory[pc + 1]; c = memory[pc + 2]; if( a == -1 ) { std::cin >> z; memory[b] = static_cast<int>( z ); } else if( b == -1 ) { std::cout << static_cast<char>( memory[a] ); } else { memory[b] -= memory[a]; if( memory[b] <= 0 ) next = c; } pc = next; } while( pc >= 0 ); } std::vector<int> memory; }; int main( int argc, char* argv[] ) { subleq s; if( argc > 1 ) { s.load_and_run( argv[1] ); } else { std::cout << "usage: subleq <filename>\n"; } return 0; }
Substring/Top and tail
C++
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: * String with first character removed * String with last character removed * String with both the first and last characters removed If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
Sum and product puzzle
C++ from C
* Wikipedia: Sum and Product Puzzle
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod; } return os << '\n'; } void print_count(const std::vector<std::pair<int, int>> &candidates) { auto c = candidates.size(); if (c == 0) { std::cout << "no candidates\n"; } else if (c == 1) { std::cout << "one candidate\n"; } else { std::cout << c << " candidates\n"; } } auto setup() { std::vector<std::pair<int, int>> candidates; // numbers must be greater than 1 for (int x = 2; x <= 98; x++) { // numbers must be unique, and sum no more than 100 for (int y = x + 1; y <= 98; y++) { if (x + y <= 100) { candidates.push_back(std::make_pair(x, y)); } } } return candidates; } void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [sum](const std::pair<int, int> &pair) { auto s = pair.first + pair.second; return s == sum; } ), candidates.end()); } void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [prod](const std::pair<int, int> &pair) { auto p = pair.first * pair.second; return p == prod; } ), candidates.end()); } void statement1(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] == 1) { auto sum = pair.first + pair.second; remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } void statement2(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] > 1) { remove_by_prod(candidates, prod); loop = true; break; } } } while (loop); } void statement3(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto sum = pair.first + pair.second; uniqueMap[sum]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto sum = pair.first + pair.second; if (uniqueMap[sum] > 1) { remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } int main() { auto candidates = setup(); print_count(candidates); statement1(candidates); print_count(candidates); statement2(candidates); print_count(candidates); statement3(candidates); print_count(candidates); std::cout << candidates; return 0; }
Sum digits of an integer
C++
Take a Natural Number in a given base and return the sum of its digits: :* '''1'''10 sums to '''1''' :* '''1234'''10 sums to '''10''' :* '''fe'''16 sums to '''29''' :* '''f0e'''16 sums to '''29'''
#include <iostream> #include <cmath> int SumDigits(const unsigned long long int digits, const int BASE = 10) { int sum = 0; unsigned long long int x = digits; for (int i = log(digits)/log(BASE); i>0; i--){ const double z = std::pow(BASE,i); const unsigned long long int t = x/z; sum += t; x -= t*z; } return x+sum; } int main() { std::cout << SumDigits(1) << ' ' << SumDigits(12345) << ' ' << SumDigits(123045) << ' ' << SumDigits(0xfe, 16) << ' ' << SumDigits(0xf0e, 16) << std::endl; return 0; }
Sum multiples of 3 and 5
C++
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. Show output for ''n'' = 1000. This is is the same as Project Euler problem 1. '''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
#include <iostream> //-------------------------------------------------------------------------------------------------- typedef unsigned long long bigInt; using namespace std; //-------------------------------------------------------------------------------------------------- class m35 { public: void doIt( bigInt i ) { bigInt sum = 0; for( bigInt a = 1; a < i; a++ ) if( !( a % 3 ) || !( a % 5 ) ) sum += a; cout << "Sum is " << sum << " for n = " << i << endl << endl; } // this method uses less than half iterations than the first one void doIt_b( bigInt i ) { bigInt sum = 0; for( bigInt a = 0; a < 28; a++ ) { if( !( a % 3 ) || !( a % 5 ) ) { sum += a; for( bigInt s = 30; s < i; s += 30 ) if( a + s < i ) sum += ( a + s ); } } cout << "Sum is " << sum << " for n = " << i << endl << endl; } }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { m35 m; m.doIt( 1000 ); return system( "pause" ); }
Sum of elements below main diagonal of matrix
C++
Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ::: --- Matrix to be used: --- [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#include <iostream> #include <vector> template<typename T> T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) { T sum = 0; for (std::size_t y = 0; y < matrix.size(); y++) for (std::size_t x = 0; x < matrix[y].size() && x < y; x++) sum += matrix[y][x]; return sum; } int main() { std::vector<std::vector<int>> matrix = { {1,3,7,8,10}, {2,4,16,14,4}, {3,1,9,18,11}, {12,14,17,18,20}, {7,1,3,9,5} }; std::cout << sum_below_diagonal(matrix) << std::endl; return 0; }
Summarize and say sequence
C++
There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) ;Task: Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 ;Related tasks: * [[Fours is the number of letters in the ...]] * [[Look-and-say sequence]] * [[Number names]] * [[Self-describing numbers]] * [[Spelling of ordinal numbers]] ;Also see: * The On-Line Encyclopedia of Integer Sequences.
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> std::map<char, int> _map; std::vector<std::string> _result; size_t longest = 0; void make_sequence( std::string n ) { _map.clear(); for( std::string::iterator i = n.begin(); i != n.end(); i++ ) _map.insert( std::make_pair( *i, _map[*i]++ ) ); std::string z; for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) { char c = ( *i ).second + 48; z.append( 1, c ); z.append( 1, i->first ); } if( longest <= z.length() ) { longest = z.length(); if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) { _result.push_back( z ); make_sequence( z ); } } } int main( int argc, char* argv[] ) { std::vector<std::string> tests; tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" ); for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) { make_sequence( *i ); std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n"; for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) { std::cout << *j << "\n"; } std::cout << "\n\n"; } return 0; }
Summarize primes
C++
Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; for (int p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
Super-d numbers
C++ from D
A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where 2 <= d <= 9 For instance, 753 is a super-3 number because 3 x 7533 = 1280873331. '''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''. ;Task: :* Write a function/procedure/routine to find super-d numbers. :* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers. ;Extra credit: :* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional). ;See also: :* Wolfram MathWorld - Super-d Number. :* OEIS: A014569 - Super-3 Numbers.
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; vector<string> rd{ "22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999" }; for (uint64_t ii = 2; ii < 5; ii++) { cout << "First 10 super-" << ii << " numbers:\n"; int count = 0; for (uint64_t j = 3; /* empty */; j++) { auto k = ii * ipow(j, ii); auto kstr = to_string(k); auto needle = rd[(size_t)(ii - 2)]; auto res = kstr.find(needle); if (res != string::npos) { count++; cout << j << ' '; if (count == 10) { cout << "\n\n"; break; } } } } return 0; }
Super-d numbers
C++ from C
A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where 2 <= d <= 9 For instance, 753 is a super-3 number because 3 x 7533 = 1280873331. '''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''. ;Task: :* Write a function/procedure/routine to find super-d numbers. :* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers. ;Extra credit: :* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional). ;See also: :* Wolfram MathWorld - Super-d Number. :* OEIS: A014569 - Super-3 Numbers.
#include <iostream> #include <gmpxx.h> using big_int = mpz_class; int main() { for (unsigned int d = 2; d <= 9; ++d) { std::cout << "First 10 super-" << d << " numbers:\n"; std::string digits(d, '0' + d); big_int bignum; for (unsigned int count = 0, n = 1; count < 10; ++n) { mpz_ui_pow_ui(bignum.get_mpz_t(), n, d); bignum *= d; auto str(bignum.get_str()); if (str.find(digits) != std::string::npos) { std::cout << n << ' '; ++count; } } std::cout << '\n'; } return 0; }
Super-d numbers
C++ from C#
A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where 2 <= d <= 9 For instance, 753 is a super-3 number because 3 x 7533 = 1280873331. '''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''. ;Task: :* Write a function/procedure/routine to find super-d numbers. :* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers. ;Extra credit: :* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional). ;See also: :* Wolfram MathWorld - Super-d Number. :* OEIS: A014569 - Super-3 Numbers.
#include <cstdio> #include <sstream> #include <chrono> using namespace std; using namespace chrono; struct LI { uint64_t a, b, c, d, e; }; const uint64_t Lm = 1e18; auto st = steady_clock::now(); LI k[10][10]; string padZ(uint64_t x, int n = 18) { string r = to_string(x); return string(max((int)(n - r.length()), 0), '0') + r; } uint64_t ipow(uint64_t b, uint64_t e) { uint64_t r = 1; while (e) { if (e & 1) r *= b; e >>= 1; b *= b; } return r; } uint64_t fa(uint64_t x) { // factorial uint64_t r = 1; while (x > 1) r *= x--; return r; } void set(LI &d, uint64_t s) { // d = s d.a = s; d.b = d.c = d.d = d.e = 0; } void inc(LI &d, LI s) { // d += s d.a += s.a; while (d.a >= Lm) { d.a -= Lm; d.b++; } d.b += s.b; while (d.b >= Lm) { d.b -= Lm; d.c++; } d.c += s.c; while (d.c >= Lm) { d.c -= Lm; d.d++; } d.d += s.d; while (d.d >= Lm) { d.d -= Lm; d.e++; } d.e += s.e; } string scale(uint32_t s, LI &x) { // multiplies x by s, converts to string uint64_t A = x.a * s, B = x.b * s, C = x.c * s, D = x.d * s, E = x.e * s; while (A >= Lm) { A -= Lm; B++; } while (B >= Lm) { B -= Lm; C++; } while (C >= Lm) { C -= Lm; D++; } while (D >= Lm) { D -= Lm; E++; } if (E > 0) return to_string(E) + padZ(D) + padZ(C) + padZ(B) + padZ(A); if (D > 0) return to_string(D) + padZ(C) + padZ(B) + padZ(A); if (C > 0) return to_string(C) + padZ(B) + padZ(A); if (B > 0) return to_string(B) + padZ(A); return to_string(A); } void fun(int d) { auto m = k[d]; string s = string(d, '0' + d); printf("%d: ", d); for (int i = d, c = 0; c < 10; i++) { if (scale((uint32_t)d, m[0]).find(s) != string::npos) { printf("%d ", i); ++c; } for (int j = d, k = d - 1; j > 0; j = k--) inc(m[k], m[j]); } printf("%ss\n", to_string(duration<double>(steady_clock::now() - st).count()).substr(0,5).c_str()); } static void init() { for (int v = 1; v < 10; v++) { uint64_t f[v + 1], l[v + 1]; for (int j = 0; j <= v; j++) { if (j == v) for (int y = 0; y <= v; y++) set(k[v][y], v != y ? (uint64_t)f[y] : fa(v)); l[0] = f[0]; f[0] = ipow(j + 1, v); for (int a = 0, b = 1; b <= v; a = b++) { l[b] = f[b]; f[b] = f[a] - l[a]; } } } } int main() { init(); for (int i = 2; i <= 9; i++) fun(i); }
Superpermutation minimisation
C++ from Kotlin
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches. ;Reference: * The Minimal Superpermutation Problem. by Nathaniel Johnston. * oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. * Superpermutations - Numberphile. A video * Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. * New Superpermutations Discovered! Standupmaths & Numberphile.
#include <array> #include <iostream> #include <vector> constexpr int MAX = 12; static std::vector<char> sp; static std::array<int, MAX> count; static int pos = 0; int factSum(int n) { int s = 0; int x = 0; int f = 1; while (x < n) { f *= ++x; s += f; } return s; } bool r(int n) { if (n == 0) { return false; } char c = sp[pos - n]; if (--count[n] == 0) { count[n] = n; if (!r(n - 1)) { return false; } } sp[pos++] = c; return true; } void superPerm(int n) { pos = n; int len = factSum(n); if (len > 0) { sp.resize(len); } for (size_t i = 0; i <= n; i++) { count[i] = i; } for (size_t i = 1; i <= n; i++) { sp[i - 1] = '0' + i; } while (r(n)) {} } int main() { for (size_t n = 0; n < MAX; n++) { superPerm(n); std::cout << "superPerm(" << n << ") len = " << sp.size() << '\n'; } return 0; }
Tarjan
C++
{{wikipedia|Graph}} Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph. It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm. Tarjan's Algorithm is named for its discoverer, Robert Tarjan. ;References: * The article on Wikipedia. See also: [[Kosaraju]]
// // C++ implementation of Tarjan's strongly connected components algorithm // See https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm // #include <algorithm> #include <iostream> #include <list> #include <string> #include <vector> struct noncopyable { noncopyable() {} noncopyable(const noncopyable&) = delete; noncopyable& operator=(const noncopyable&) = delete; }; template <typename T> class tarjan; template <typename T> class vertex : private noncopyable { public: explicit vertex(const T& t) : data_(t) {} void add_neighbour(vertex* v) { neighbours_.push_back(v); } void add_neighbours(const std::initializer_list<vertex*>& vs) { neighbours_.insert(neighbours_.end(), vs); } const T& get_data() { return data_; } private: friend tarjan<T>; T data_; int index_ = -1; int lowlink_ = -1; bool on_stack_ = false; std::vector<vertex*> neighbours_; }; template <typename T> class graph : private noncopyable { public: vertex<T>* add_vertex(const T& t) { vertexes_.emplace_back(t); return &vertexes_.back(); } private: friend tarjan<T>; std::list<vertex<T>> vertexes_; }; template <typename T> class tarjan : private noncopyable { public: using component = std::vector<vertex<T>*>; std::list<component> run(graph<T>& graph) { index_ = 0; stack_.clear(); strongly_connected_.clear(); for (auto& v : graph.vertexes_) { if (v.index_ == -1) strongconnect(&v); } return strongly_connected_; } private: void strongconnect(vertex<T>* v) { v->index_ = index_; v->lowlink_ = index_; ++index_; stack_.push_back(v); v->on_stack_ = true; for (auto w : v->neighbours_) { if (w->index_ == -1) { strongconnect(w); v->lowlink_ = std::min(v->lowlink_, w->lowlink_); } else if (w->on_stack_) { v->lowlink_ = std::min(v->lowlink_, w->index_); } } if (v->lowlink_ == v->index_) { strongly_connected_.push_back(component()); component& c = strongly_connected_.back(); for (;;) { auto w = stack_.back(); stack_.pop_back(); w->on_stack_ = false; c.push_back(w); if (w == v) break; } } } int index_ = 0; std::list<vertex<T>*> stack_; std::list<component> strongly_connected_; }; template <typename T> void print_vector(const std::vector<vertex<T>*>& vec) { if (!vec.empty()) { auto i = vec.begin(); std::cout << (*i)->get_data(); for (++i; i != vec.end(); ++i) std::cout << ' ' << (*i)->get_data(); } std::cout << '\n'; } int main() { graph<std::string> g; auto andy = g.add_vertex("Andy"); auto bart = g.add_vertex("Bart"); auto carl = g.add_vertex("Carl"); auto dave = g.add_vertex("Dave"); auto earl = g.add_vertex("Earl"); auto fred = g.add_vertex("Fred"); auto gary = g.add_vertex("Gary"); auto hank = g.add_vertex("Hank"); andy->add_neighbour(bart); bart->add_neighbour(carl); carl->add_neighbour(andy); dave->add_neighbours({bart, carl, earl}); earl->add_neighbours({dave, fred}); fred->add_neighbours({carl, gary}); gary->add_neighbour(fred); hank->add_neighbours({earl, gary, hank}); tarjan<std::string> t; for (auto&& s : t.run(g)) print_vector(s); return 0; }
Tau function
C++
Given a positive integer, count the number of its positive divisors. ;Task Show the result for the first '''100''' positive integers. ;Related task * [[Tau number]]
#include <iomanip> #include <iostream> // See https://en.wikipedia.org/wiki/Divisor_function unsigned int divisor_count(unsigned int n) { unsigned int total = 1; // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) ++total; // Odd prime factors up to the square root for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } // If n > 1 then it's prime if (n > 1) total *= 2; return total; } int main() { const unsigned int limit = 100; std::cout << "Count of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(3) << divisor_count(n); if (n % 20 == 0) std::cout << '\n'; } }
Teacup rim text
C++
On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*). It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word. So start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''. That got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu. For English, we will use the unixdict (now) located at: unixdict.txt. (This will maintain continuity with other Rosetta Code tasks that also use it.) ;Task: Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.) Having listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc. The words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.) The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''. All of the possible permutations, using this particular permutation technique, must be words in the list. The set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method. Display one line for each set of teacup rim words.
#include <algorithm> #include <fstream> #include <iostream> #include <set> #include <string> #include <vector> // filename is expected to contain one lowercase word per line std::set<std::string> load_dictionary(const std::string& filename) { std::ifstream in(filename); if (!in) throw std::runtime_error("Cannot open file " + filename); std::set<std::string> words; std::string word; while (getline(in, word)) words.insert(word); return words; } void find_teacup_words(const std::set<std::string>& words) { std::vector<std::string> teacup_words; std::set<std::string> found; for (auto w = words.begin(); w != words.end(); ++w) { std::string word = *w; size_t len = word.size(); if (len < 3 || found.find(word) != found.end()) continue; teacup_words.clear(); teacup_words.push_back(word); for (size_t i = 0; i + 1 < len; ++i) { std::rotate(word.begin(), word.begin() + 1, word.end()); if (word == *w || words.find(word) == words.end()) break; teacup_words.push_back(word); } if (teacup_words.size() == len) { found.insert(teacup_words.begin(), teacup_words.end()); std::cout << teacup_words[0]; for (size_t i = 1; i < len; ++i) std::cout << ' ' << teacup_words[i]; std::cout << '\n'; } } } int main(int argc, char** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " dictionary\n"; return EXIT_FAILURE; } try { find_teacup_words(load_dictionary(argv[1])); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Temperature conversion
C++
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. : 0 degrees Celsius corresponds to 273.15 kelvin. : 0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. : 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. : 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. ;Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. ;Example: K 21.00 C -252.15 F -421.87 R 37.80
#include <iostream> #include <iomanip> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- class converter { public: converter() : KTC( 273.15f ), KTDel( 3.0f / 2.0f ), KTF( 9.0f / 5.0f ), KTNew( 33.0f / 100.0f ), KTRank( 9.0f / 5.0f ), KTRe( 4.0f / 5.0f ), KTRom( 21.0f / 40.0f ) {} void convert( float kelvin ) { float cel = kelvin - KTC, del = ( 373.15f - kelvin ) * KTDel, fah = kelvin * KTF - 459.67f, net = cel * KTNew, rnk = kelvin * KTRank, rea = cel * KTRe, rom = cel * KTRom + 7.5f; cout << endl << left << "TEMPERATURES:" << endl << "===============" << endl << setw( 13 ) << "CELSIUS:" << cel << endl << setw( 13 ) << "DELISLE:" << del << endl << setw( 13 ) << "FAHRENHEIT:" << fah << endl << setw( 13 ) << "KELVIN:" << kelvin << endl << setw( 13 ) << "NEWTON:" << net << endl << setw( 13 ) << "RANKINE:" << rnk << endl << setw( 13 ) << "REAUMUR:" << rea << endl << setw( 13 ) << "ROMER:" << rom << endl << endl << endl; } private: const float KTRank, KTC, KTF, KTRe, KTDel, KTNew, KTRom; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { converter con; float k; while( true ) { cout << "Enter the temperature in Kelvin to convert: "; cin >> k; con.convert( k ); system( "pause" ); system( "cls" ); } return 0; } //--------------------------------------------------------------------------------------------------
Test integerness
C++
{| class="wikitable" |- ! colspan=2 | Input ! colspan=2 | Output ! rowspan=2 | Comment |- ! Type ! Value ! exact ! tolerance = 0.00001 |- | rowspan=3 | decimal | 25.000000 | colspan=2 | true | |- | 24.999999 | false | true | |- | 25.000100 | colspan=2 | false | |- | rowspan=4 | floating-point | -2.1e120 | colspan=2 | true | This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such. |- | -5e-2 | colspan=2 | false | |- | NaN | colspan=2 | false | |- | Inf | colspan=2 | false | This one is debatable. If your code considers it an integer, that's okay too. |- | rowspan=2 | complex | 5.0+0.0i | colspan=2 | true | |- | 5-5i | colspan=2 | false | |} (The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
#include <complex> #include <math.h> #include <iostream> template<class Type> struct Precision { public: static Type GetEps() { return eps; } static void SetEps(Type e) { eps = e; } private: static Type eps; }; template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7); template<class DigType> bool IsDoubleEqual(DigType d1, DigType d2) { return (fabs(d1 - d2) < Precision<DigType>::GetEps()); } template<class DigType> DigType IntegerPart(DigType value) { return (value > 0) ? floor(value) : ceil(value); } template<class DigType> DigType FractionPart(DigType value) { return fabs(IntegerPart<DigType>(value) - value); } template<class Type> bool IsInteger(const Type& value) { return false; } #define GEN_CHECK_INTEGER(type) \ template<> \ bool IsInteger<type>(const type& value) \ { \ return true; \ } #define GEN_CHECK_CMPL_INTEGER(type) \ template<> \ bool IsInteger<std::complex<type> >(const std::complex<type>& value) \ { \ type zero = type(); \ return value.imag() == zero; \ } #define GEN_CHECK_REAL(type) \ template<> \ bool IsInteger<type>(const type& value) \ { \ type zero = type(); \ return IsDoubleEqual<type>(FractionPart<type>(value), zero); \ } #define GEN_CHECK_CMPL_REAL(type) \ template<> \ bool IsInteger<std::complex<type> >(const std::complex<type>& value) \ { \ type zero = type(); \ return IsDoubleEqual<type>(value.imag(), zero); \ } #define GEN_INTEGER(type) \ GEN_CHECK_INTEGER(type) \ GEN_CHECK_CMPL_INTEGER(type) #define GEN_REAL(type) \ GEN_CHECK_REAL(type) \ GEN_CHECK_CMPL_REAL(type) GEN_INTEGER(char) GEN_INTEGER(unsigned char) GEN_INTEGER(short) GEN_INTEGER(unsigned short) GEN_INTEGER(int) GEN_INTEGER(unsigned int) GEN_INTEGER(long) GEN_INTEGER(unsigned long) GEN_INTEGER(long long) GEN_INTEGER(unsigned long long) GEN_REAL(float) GEN_REAL(double) GEN_REAL(long double) template<class Type> inline void TestValue(const Type& value) { std::cout << "Value: " << value << " of type: " << typeid(Type).name() << " is integer - " << std::boolalpha << IsInteger(value) << std::endl; } int main() { char c = -100; unsigned char uc = 200; short s = c; unsigned short us = uc; int i = s; unsigned int ui = us; long long ll = i; unsigned long long ull = ui; std::complex<unsigned int> ci1(2, 0); std::complex<int> ci2(2, 4); std::complex<int> ci3(-2, 4); std::complex<unsigned short> cs1(2, 0); std::complex<short> cs2(2, 4); std::complex<short> cs3(-2, 4); std::complex<double> cd1(2, 0); std::complex<float> cf1(2, 4); std::complex<double> cd2(-2, 4); float f1 = 1.0; float f2 = -2.0; float f3 = -2.4f; float f4 = 1.23e-5f; float f5 = 1.23e-10f; double d1 = f5; TestValue(c); TestValue(uc); TestValue(s); TestValue(us); TestValue(i); TestValue(ui); TestValue(ll); TestValue(ull); TestValue(ci1); TestValue(ci2); TestValue(ci3); TestValue(cs1); TestValue(cs2); TestValue(cs3); TestValue(cd1); TestValue(cd2); TestValue(cf1); TestValue(f1); TestValue(f2); TestValue(f3); TestValue(f4); TestValue(f5); std::cout << "Set float precision: 1e-15f\n"; Precision<float>::SetEps(1e-15f); TestValue(f5); TestValue(d1); return 0; }
Textonyms
C++
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -> WXYZ ;Task: Write a program that finds textonyms in a list of words such as [[Textonyms/wordlist]] or unixdict.txt. The task should produce a report: There are #{0} words in #{1} which can be represented by the digit key mapping. They require #{2} digit combinations to represent them. #{3} digit combinations represent Textonyms. Where: #{0} is the number of words in the list which can be represented by the digit key mapping. #{1} is the URL of the wordlist being used. #{2} is the number of digit combinations required to represent the words in #{0}. #{3} is the number of #{2} which represent more than one word. At your discretion show a couple of examples of your solution displaying Textonyms. E.G.: 2748424767 -> "Briticisms", "criticisms" ;Extra credit: Use a word list and keypad mapping other than English.
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mapping(std::string &result, const std::string &input) { static std::unordered_map<char, char> mapping = { {'A', '2'}, {'B', '2'}, {'C', '2'}, {'D', '3'}, {'E', '3'}, {'F', '3'}, {'G', '4'}, {'H', '4'}, {'I', '4'}, {'J', '5'}, {'K', '5'}, {'L', '5'}, {'M', '6'}, {'N', '6'}, {'O', '6'}, {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'}, {'T', '8'}, {'U', '8'}, {'V', '8'}, {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'} }; result = input; for (char &c : result) { if (!isalnum(c)) return 0; if (isalpha(c)) c = mapping[toupper(c)]; } return 1; } public: Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { } ~Textonym_Checker() { } void add(const std::string &str) { std::string mapping; total++; if (!get_mapping(mapping, str)) return; const int num_strings = values[mapping].size(); if (num_strings == 1) textonyms++; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.push_back(mapping); max_found = num_strings; } else if (num_strings == max_found) max_strings.push_back(mapping); values[mapping].push_back(str); } void results(const std::string &filename) { std::cout << "Read " << total << " words from " << filename << "\n\n"; std::cout << "There are " << elements << " words in " << filename; std::cout << " which can be represented by the digit key mapping.\n"; std::cout << "They require " << values.size() << " digit combinations to represent them.\n"; std::cout << textonyms << " digit combinations represent Textonyms.\n\n"; std::cout << "The numbers mapping to the most words map to "; std::cout << max_found + 1 << " words each:\n"; for (auto it1 : max_strings) { std::cout << '\t' << it1 << " maps to: "; for (auto it2 : values[it1]) std::cout << it2 << " "; std::cout << '\n'; } std::cout << '\n'; } void match(const std::string &str) { auto match = values.find(str); if (match == values.end()) { std::cout << "Key '" << str << "' not found\n"; } else { std::cout << "Key '" << str << "' matches: "; for (auto it : values[str]) std::cout << it << " "; std::cout << '\n'; } } }; int main() { auto filename = "unixdict.txt"; std::ifstream input(filename); Textonym_Checker tc; if (input.is_open()) { std::string line; while (getline(input, line)) tc.add(line); } input.close(); tc.results(filename); tc.match("001"); tc.match("228"); tc.match("27484247"); tc.match("7244967473642"); }
The Name Game
C++ from C#
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like this: Gary, Gary, bo-bary Banana-fana fo-fary Fee-fi-mo-mary Gary! At the end of every line, the name gets repeated without the first letter: Gary becomes ary If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this: (X), (X), bo-b(Y) Banana-fana fo-f(Y) Fee-fi-mo-m(Y) (X)! Vowel as first letter of the name If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name. The verse looks like this: Earl, Earl, bo-bearl Banana-fana fo-fearl Fee-fi-mo-mearl Earl! 'B', 'F' or 'M' as first letter of the name In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule. The line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name. The verse for the name Billy looks like this: Billy, Billy, bo-illy Banana-fana fo-filly Fee-fi-mo-milly Billy! For the name 'Felix', this would be right: Felix, Felix, bo-belix Banana-fana fo-elix Fee-fi-mo-melix Felix!
#include <algorithm> #include <iostream> #include <string> #include <vector> static void printVerse(const std::string& name) { std::string x = name; std::transform(x.begin(), x.end(), x.begin(), ::tolower); x[0] = toupper(x[0]); std::string y; switch (x[0]) { case 'A': case 'E': case 'I': case 'O': case 'U': y = x; std::transform(y.begin(), y.end(), y.begin(), ::tolower); break; default: y = x.substr(1); break; } std::string b("b" + y); std::string f("f" + y); std::string m("m" + y); switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str()); printf("Banana-fana fo-%s\n", f.c_str()); printf("Fee-fi-mo-%s\n", m.c_str()); printf("%s!\n\n", x.c_str()); } int main() { using namespace std; vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; for (auto& name : nameList) { printVerse(name); } return 0; }
The Twelve Days of Christmas
C++
Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
#include <iostream> #include <array> #include <string> using namespace std; int main() { const array<string, 12> days { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" }; const array<string, 12> gifts { "And a partridge in a pear tree", "Two turtle doves", "Three french hens", "Four calling birds", "FIVE GOLDEN RINGS", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming" }; for(int i = 0; i < days.size(); ++i) { cout << "On the " << days[i] << " day of christmas, my true love gave to me\n"; if(i == 0) { cout << "A partridge in a pear tree\n"; } else { int j = i + 1; while(j-- > 0) cout << gifts[j] << '\n'; } cout << '\n'; } return 0; }
Thue-Morse
C++
Create a Thue-Morse sequence. ;See also * YouTube entry: The Fairest Sharing Sequence Ever * YouTube entry: Math and OCD - My story with the Thue-Morse sequence * Task: [[Fairshare between two and more]]
#include <iostream> #include <iterator> #include <vector> int main( int argc, char* argv[] ) { std::vector<bool> t; t.push_back( 0 ); size_t len = 1; std::cout << t[0] << "\n"; do { for( size_t x = 0; x < len; x++ ) t.push_back( t[x] ? 0 : 1 ); std::copy( t.begin(), t.end(), std::ostream_iterator<bool>( std::cout ) ); std::cout << "\n"; len = t.size(); } while( len < 60 ); return 0; }
Top rank per group
C++
Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
#include <string> #include <set> #include <list> #include <map> #include <iostream> struct Employee { std::string Name; std::string ID; unsigned long Salary; std::string Department; Employee(std::string _Name = "", std::string _ID = "", unsigned long _Salary = 0, std::string _Department = "") : Name(_Name), ID(_ID), Salary(_Salary), Department(_Department) { } void display(std::ostream& out) const { out << Name << "\t" << ID << "\t" << Salary << "\t" << Department << std::endl; } }; // We'll tell std::set to use this to sort our employees. struct CompareEarners { bool operator()(const Employee& e1, const Employee& e2) { return (e1.Salary > e2.Salary); } }; // A few typedefs to make the code easier to type, read and maintain. typedef std::list<Employee> EMPLOYEELIST; // Notice the CompareEarners; We're telling std::set to user our specified comparison mechanism // to sort its contents. typedef std::set<Employee, CompareEarners> DEPARTMENTPAYROLL; typedef std::map<std::string, DEPARTMENTPAYROLL> DEPARTMENTLIST; void initialize(EMPLOYEELIST& Employees) { // Initialize our employee list data source. Employees.push_back(Employee("Tyler Bennett", "E10297", 32000, "D101")); Employees.push_back(Employee("John Rappl", "E21437", 47000, "D050")); Employees.push_back(Employee("George Woltman", "E21437", 53500, "D101")); Employees.push_back(Employee("Adam Smith", "E21437", 18000, "D202")); Employees.push_back(Employee("Claire Buckman", "E39876", 27800, "D202")); Employees.push_back(Employee("David McClellan", "E04242", 41500, "D101")); Employees.push_back(Employee("Rich Holcomb", "E01234", 49500, "D202")); Employees.push_back(Employee("Nathan Adams", "E41298", 21900, "D050")); Employees.push_back(Employee("Richard Potter", "E43128", 15900, "D101")); Employees.push_back(Employee("David Motsinger", "E27002", 19250, "D202")); Employees.push_back(Employee("Tim Sampair", "E03033", 27000, "D101")); Employees.push_back(Employee("Kim Arlich", "E10001", 57000, "D190")); Employees.push_back(Employee("Timothy Grove", "E16398", 29900, "D190")); } void group(EMPLOYEELIST& Employees, DEPARTMENTLIST& Departments) { // Loop through all of our employees. for( EMPLOYEELIST::iterator iEmployee = Employees.begin(); Employees.end() != iEmployee; ++iEmployee ) { DEPARTMENTPAYROLL& groupSet = Departments[iEmployee->Department]; // Add our employee to this group. groupSet.insert(*iEmployee); } } void present(DEPARTMENTLIST& Departments, unsigned int N) { // Loop through all of our departments for( DEPARTMENTLIST::iterator iDepartment = Departments.begin(); Departments.end() != iDepartment; ++iDepartment ) { std::cout << "In department " << iDepartment->first << std::endl; std::cout << "Name\t\tID\tSalary\tDepartment" << std::endl; // Get the top three employees for each employee unsigned int rank = 1; for( DEPARTMENTPAYROLL::iterator iEmployee = iDepartment->second.begin(); ( iDepartment->second.end() != iEmployee) && (rank <= N); ++iEmployee, ++rank ) { iEmployee->display(std::cout); } std::cout << std::endl; } } int main(int argc, char* argv[]) { // Our container for our list of employees. EMPLOYEELIST Employees; // Fill our list of employees initialize(Employees); // Our departments. DEPARTMENTLIST Departments; // Sort our employees into their departments. // This will also rank them. group(Employees, Departments); // Display the top 3 earners in each department. present(Departments, 3); return 0; }
Topswops
C++
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. A round is composed of reversing the first m cards where m is the value of the topmost card. Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. For our example the swaps produce: [2, 4, 1, 3] # Initial shuffle [4, 2, 1, 3] [3, 1, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top. For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards. ;Task: The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive. ;Note: Topswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake. ;Related tasks: * [[Number reversal game]] * [[Sorting algorithms/Pancake sort]]
#include <iostream> #include <vector> #include <numeric> #include <algorithm> int topswops(int n) { std::vector<int> list(n); std::iota(std::begin(list), std::end(list), 1); int max_steps = 0; do { auto temp_list = list; for (int steps = 1; temp_list[0] != 1; ++steps) { std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]); if (steps > max_steps) max_steps = steps; } } while (std::next_permutation(std::begin(list), std::end(list))); return max_steps; } int main() { for (int i = 1; i <= 10; ++i) { std::cout << i << ": " << topswops(i) << std::endl; } return 0; }
Trabb Pardo–Knuth algorithm
C++
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: '''ask''' for 11 numbers to be read into a sequence ''S'' '''reverse''' sequence ''S'' '''for each''' ''item'' '''in''' sequence ''S'' ''result'' ''':=''' '''call''' a function to do an ''operation'' '''if''' ''result'' overflows '''alert''' user '''else''' '''print''' ''result'' The task is to implement the algorithm: # Use the function: f(x) = |x|^{0.5} + 5x^3 # The overflow condition is an answer of greater than 400. # The 'user alert' should not stop processing of other items of the sequence. # Print a prompt before accepting '''eleven''', textual, numeric inputs. # You may optionally print the item as well as its associated result, but the results must be in reverse order of input. # The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly. # ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> int main( ) { std::vector<double> input( 11 ) , results( 11 ) ; std::cout << "Please enter 11 numbers!\n" ; for ( int i = 0 ; i < input.size( ) ; i++ ) std::cin >> input[i]; std::transform( input.begin( ) , input.end( ) , results.begin( ) , [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; for ( int i = 10 ; i > -1 ; i-- ) { std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; if ( results[ i ] > 400 ) std::cout << "too large!" ; else std::cout << results[ i ] << " !" ; std::cout << std::endl ; } return 0 ; }
Tree datastructures
C++
The following shows a tree of data with nesting denoted by visual levels of indentation: RosettaCode rocks code comparison wiki mocks trolling A common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this '''the nest form'''. # E.g. if child nodes are surrounded by brackets # and separated by commas then: RosettaCode(rocks(code, ...), ...) # But only an _example_ Another datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this '''the indent form'''. 0 RosettaCode 1 rocks 2 code ... ;Task: # Create/use a nest datastructure format and textual representation for arbitrary trees. # Create/use an indent datastructure format and textual representation for arbitrary trees. # Create methods/classes/proceedures/routines etc to: ## Change from a nest tree datastructure to an indent one. ## Change from an indent tree datastructure to a nest one # Use the above to encode the example at the start into the nest format, and show it. # transform the initial nest format to indent format and show it. # transform the indent format to final nest format and show it. # Compare initial and final nest formats which should be the same. ;Note: * It's all about showing aspects of the contrasting datastructures as they hold the tree. * Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier. Show all output on this page.
#include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> #include <utility> #include <vector> class nest_tree; bool operator==(const nest_tree&, const nest_tree&); class nest_tree { public: explicit nest_tree(const std::string& name) : name_(name) {} nest_tree& add_child(const std::string& name) { children_.emplace_back(name); return children_.back(); } void print(std::ostream& out) const { print(out, 0); } const std::string& name() const { return name_; } const std::list<nest_tree>& children() const { return children_; } bool equals(const nest_tree& n) const { return name_ == n.name_ && children_ == n.children_; } private: void print(std::ostream& out, int level) const { std::string indent(level * 4, ' '); out << indent << name_ << '\n'; for (const nest_tree& child : children_) child.print(out, level + 1); } std::string name_; std::list<nest_tree> children_; }; bool operator==(const nest_tree& a, const nest_tree& b) { return a.equals(b); } class indent_tree { public: explicit indent_tree(const nest_tree& n) { items_.emplace_back(0, n.name()); from_nest(n, 0); } void print(std::ostream& out) const { for (const auto& item : items_) std::cout << item.first << ' ' << item.second << '\n'; } nest_tree to_nest() const { nest_tree n(items_[0].second); to_nest_(n, 1, 0); return n; } private: void from_nest(const nest_tree& n, int level) { for (const nest_tree& child : n.children()) { items_.emplace_back(level + 1, child.name()); from_nest(child, level + 1); } } size_t to_nest_(nest_tree& n, size_t pos, int level) const { while (pos < items_.size() && items_[pos].first == level + 1) { nest_tree& child = n.add_child(items_[pos].second); pos = to_nest_(child, pos + 1, level + 1); } return pos; } std::vector<std::pair<int, std::string>> items_; }; int main() { nest_tree n("RosettaCode"); auto& child1 = n.add_child("rocks"); auto& child2 = n.add_child("mocks"); child1.add_child("code"); child1.add_child("comparison"); child1.add_child("wiki"); child2.add_child("trolling"); std::cout << "Initial nest format:\n"; n.print(std::cout); indent_tree i(n); std::cout << "\nIndent format:\n"; i.print(std::cout); nest_tree n2(i.to_nest()); std::cout << "\nFinal nest format:\n"; n2.print(std::cout); std::cout << "\nAre initial and final nest formats equal? " << std::boolalpha << n.equals(n2) << '\n'; return 0; }
Tree from nesting levels
C++
Given a flat list of integers greater than zero, representing object nesting levels, e.g. [1, 2, 4], generate a tree formed from nested lists of those nesting level integers where: * Every int appears, in order, at its depth of nesting. * If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item The generated tree data structure should ideally be in a languages nested list format that can be used for further calculations rather than something just calculated for printing. An input of [1, 2, 4] should produce the equivalent of: [1, [2, [[4]]]] where 1 is at depth1, 2 is two deep and 4 is nested 4 deep. [1, 2, 4, 2, 2, 1] should produce [1, [2, [[4]], 2, 2], 1]. All the nesting integers are in the same order but at the correct nesting levels. Similarly [3, 1, 3, 1] should generate [[[3]], 1, [[3]], 1] ;Task: Generate and show here the results for the following inputs: :* [] :* [1, 2, 4] :* [3, 1, 3, 1] :* [1, 2, 3, 1] :* [3, 2, 1, 3] :* [3, 3, 3, 1, 1, 3, 3, 3]
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; // Make a tree that is a vector of either values or other trees vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { // add a single value tree.push_back(*first); ++first; } else // (depth < *b) { // add a subtree tree.push_back(MakeTree(first, last, depth + 1)); first = find(first + 1, last, depth); } } return tree; } // Print an input vector or tree void PrintTree(input_iterator auto first, input_iterator auto last) { cout << "["; for(auto it = first; it != last; ++it) { if(it != first) cout << ", "; if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>) { // for printing the input vector cout << *it; } else { // for printing the tree if(it->type() == typeid(unsigned int)) { // a single value cout << any_cast<unsigned int>(*it); } else { // a subtree const auto& subTree = any_cast<vector<any>>(*it); PrintTree(subTree.begin(), subTree.end()); } } } cout << "]"; } int main(void) { auto execises = vector<vector<unsigned int>> { {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3} }; for(const auto& e : execises) { auto tree = MakeTree(e.begin(), e.end()); PrintTree(e.begin(), e.end()); cout << " Nests to:\n"; PrintTree(tree.begin(), tree.end()); cout << "\n\n"; } }
Tropical algebra overloading
C++
In algebra, a max tropical semiring (also called a max-plus algebra) is the semiring (R -Inf, , ) containing the ring of real numbers R augmented by negative infinity, the max function (returns the greater of two real numbers), and addition. In max tropical algebra, x y = max(x, y) and x y = x + y. The identity for is -Inf (the max of any number with -infinity is that number), and the identity for is 0. ;Task: * Define functions or, if the language supports the symbols as operators, operators for and that fit the above description. If the language does not support and as operators but allows overloading operators for a new object type, you may instead overload + and * for a new min tropical albrbraic type. If you cannot overload operators in the language used, define ordinary functions for the purpose. Show that 2 -2 is 0, -0.001 -Inf is -0.001, 0 -Inf is -Inf, 1.5 -1 is 1.5, and -0.5 0 is -0.5. * Define exponentiation as serial , and in general that a to the power of b is a * b, where a is a real number and b must be a positive integer. Use either | or similar up arrow or the carat ^, as an exponentiation operator if this can be used to overload such "exponentiation" in the language being used. Calculate 5 | 7 using this definition. * Max tropical algebra is distributive, so that a (b c) equals a b b c, where has precedence over . Demonstrate that 5 (8 7) equals 5 8 5 7. * If the language used does not support operator overloading, you may use ordinary function names such as tropicalAdd(x, y) and tropicalMul(x, y). ;See also :;*[Tropical algebra] :;*[Tropical geometry review article] :;*[Operator overloading]
#include <iostream> #include <optional> using namespace std; class TropicalAlgebra { // use an unset std::optional to represent -infinity optional<double> m_value; public: friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&); friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept; // create a point that is initialized to -infinity TropicalAlgebra() = default; // construct with a value explicit TropicalAlgebra(double value) noexcept : m_value{value} {} // add a value to this one ( p+=q ). it is common to also overload // the += operator when overloading + TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept { if(!m_value) { // this point is -infinity so the other point is max *this = rhs; } else if (!rhs.m_value) { // since rhs is -infinity this point is max } else { // both values are valid, find the max *m_value = max(*rhs.m_value, *m_value); } return *this; } // multiply this value by another (p *= q) TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept { if(!m_value) { // since this value is -infinity this point does not need to be // modified } else if (!rhs.m_value) { // the other point is -infinity, make this -infinity too *this = rhs; } else { *m_value += *rhs.m_value; } return *this; } }; // add values (p + q) inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept { // implemented using the += operator defined above lhs += rhs; return lhs; } // multiply values (p * q) inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept { lhs *= rhs; return lhs; } // pow is the idomatic way for exponentiation in C++ inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept { auto result = base; for(unsigned int i = 1; i < exponent; i++) { // compute the power by successive multiplication result *= base; } return result; } // print the point ostream& operator<<(ostream& os, const TropicalAlgebra& pt) { if(!pt.m_value) cout << "-Inf\n"; else cout << *pt.m_value << "\n"; return os; } int main(void) { const TropicalAlgebra a(-2); const TropicalAlgebra b(-1); const TropicalAlgebra c(-0.5); const TropicalAlgebra d(-0.001); const TropicalAlgebra e(0); const TropicalAlgebra h(1.5); const TropicalAlgebra i(2); const TropicalAlgebra j(5); const TropicalAlgebra k(7); const TropicalAlgebra l(8); const TropicalAlgebra m; // -Inf cout << "2 * -2 == " << i * a; cout << "-0.001 + -Inf == " << d + m; cout << "0 * -Inf == " << e * m; cout << "1.5 + -1 == " << h + b; cout << "-0.5 * 0 == " << c * e; cout << "pow(5, 7) == " << pow(j, 7); cout << "5 * (8 + 7)) == " << j * (l + k); cout << "5 * 8 + 5 * 7 == " << j * l + j * k; }
Truncate a file
C++
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#include <string> #include <fstream> using namespace std; void truncateFile(string filename, int max_size) { std::ifstream input( filename, std::ios::binary ); char buffer; string outfile = filename + ".trunc"; ofstream appendFile(outfile, ios_base::out); for(int i=0; i<max_size; i++) { input.read( &buffer, sizeof(buffer) ); appendFile.write(&buffer,1); } appendFile.close(); } int main () { truncateFile("test.txt", 5); return 0; }
Truth table
C++ from C
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. ;Task: # Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). # Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. # Either reverse-polish or infix notation expressions are allowed. ;Related tasks: * [[Boolean values]] * [[Ternary logic]] ;See also: * Wolfram MathWorld entry on truth tables. * some "truth table" examples from Google.
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|' || c == '!' || c == '^'; } bool eval_expr(const std::string &expr) { std::stack<bool> sob; for (auto e : expr) { if (e == 'T') { sob.push(true); } else if (e == 'F') { sob.push(false); } else { auto it = std::find_if(vars.cbegin(), vars.cend(), [e](const var &v) { return v.name == e; }); if (it != vars.cend()) { sob.push(it->value); } else { int before = sob.size(); switch (e) { case '&': sob.push(pop(sob) & pop(sob)); break; case '|': sob.push(pop(sob) | pop(sob)); break; case '!': sob.push(!pop(sob)); break; case '^': sob.push(pop(sob) ^ pop(sob)); break; default: throw std::exception("Non-conformant character in expression."); } } } } if (sob.size() != 1) { throw std::exception("Stack should contain exactly one element."); } return sob.top(); } void set_vars(int pos, const std::string &expr) { if (pos > vars.size()) { throw std::exception("Argument to set_vars can't be greater than the number of variables."); } if (pos == vars.size()) { for (auto &v : vars) { std::cout << (v.value ? "T " : "F "); } std::cout << (eval_expr(expr) ? 'T' : 'F') << '\n'; //todo implement evaluation } else { vars[pos].value = false; set_vars(pos + 1, expr); vars[pos].value = true; set_vars(pos + 1, expr); } } /* removes whitespace and converts to upper case */ std::string process_expr(const std::string &src) { std::stringstream expr; for (auto c : src) { if (!isspace(c)) { expr << (char)toupper(c); } } return expr.str(); } int main() { std::cout << "Accepts single-character variables (except for 'T' and 'F',\n"; std::cout << "which specify explicit true or false values), postfix, with\n"; std::cout << "&|!^ for and, or, not, xor, respectively; optionally\n"; std::cout << "seperated by whitespace. Just enter nothing to quit.\n"; while (true) { std::cout << "\nBoolean expression: "; std::string input; std::getline(std::cin, input); auto expr = process_expr(input); if (expr.length() == 0) { break; } vars.clear(); for (auto e : expr) { if (!is_operator(e) && e != 'T' && e != 'F') { vars.push_back({ e, false }); } } std::cout << '\n'; if (vars.size() == 0) { std::cout << "No variables were entered.\n"; } else { for (auto &v : vars) { std::cout << v.name << " "; } std::cout << expr << '\n'; auto h = vars.size() * 3 + expr.length(); for (size_t i = 0; i < h; i++) { std::cout << '='; } std::cout << '\n'; set_vars(0, expr); } } return 0; }
Two bullet roulette
C++ from C
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. ;Task: # Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. # Show the results as a percentage of deaths for each type of scenario. # The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. ;Reference: Youtube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]
#include <array> #include <iomanip> #include <iostream> #include <random> #include <sstream> class Roulette { private: std::array<bool, 6> cylinder; std::mt19937 gen; std::uniform_int_distribution<> distrib; int next_int() { return distrib(gen); } void rshift() { std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end()); } void unload() { std::fill(cylinder.begin(), cylinder.end(), false); } void load() { while (cylinder[0]) { rshift(); } cylinder[0] = true; rshift(); } void spin() { int lim = next_int(); for (int i = 1; i < lim; i++) { rshift(); } } bool fire() { auto shot = cylinder[0]; rshift(); return shot; } public: Roulette() { std::random_device rd; gen = std::mt19937(rd()); distrib = std::uniform_int_distribution<>(1, 6); unload(); } int method(const std::string &s) { unload(); for (auto c : s) { switch (c) { case 'L': load(); break; case 'S': spin(); break; case 'F': if (fire()) { return 1; } break; } } return 0; } }; std::string mstring(const std::string &s) { std::stringstream ss; bool first = true; auto append = [&ss, &first](const std::string s) { if (first) { first = false; } else { ss << ", "; } ss << s; }; for (auto c : s) { switch (c) { case 'L': append("load"); break; case 'S': append("spin"); break; case 'F': append("fire"); break; } } return ss.str(); } void test(const std::string &src) { const int tests = 100000; int sum = 0; Roulette r; for (int t = 0; t < tests; t++) { sum += r.method(src); } double pc = 100.0 * sum / tests; std::cout << std::left << std::setw(40) << mstring(src) << " produces " << pc << "% deaths.\n"; } int main() { test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF"); return 0; }
UPC
C++ from Kotlin
Goal: Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink). ;Sample input: Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down, and one entry has a timing error. ;Task: Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down (the other option is to reject them). ;Notes: Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''. On the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1''' Alternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code. ;The UPC-A bar code structure: ::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly), ::* then has a ''' # # ''' sequence marking the start of the sequence, ::* then has the six "left hand" digits, ::* then has a ''' # # ''' sequence in the middle, ::* then has the six "right hand digits", ::* then has another ''' # # ''' (end sequence), and finally, ::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. ;Verification: Multiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products. The sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.
#include <iostream> #include <locale> #include <map> #include <vector> std::string trim(const std::string &str) { auto s = str; //rtrim auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end()); //ltrim auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(s.begin(), it2); return s; } template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } const std::map<std::string, int> LEFT_DIGITS = { {" ## #", 0}, {" ## #", 1}, {" # ##", 2}, {" #### #", 3}, {" # ##", 4}, {" ## #", 5}, {" # ####", 6}, {" ### ##", 7}, {" ## ###", 8}, {" # ##", 9} }; const std::map<std::string, int> RIGHT_DIGITS = { {"### # ", 0}, {"## ## ", 1}, {"## ## ", 2}, {"# # ", 3}, {"# ### ", 4}, {"# ### ", 5}, {"# # ", 6}, {"# # ", 7}, {"# # ", 8}, {"### # ", 9} }; const std::string END_SENTINEL = "# #"; const std::string MID_SENTINEL = " # # "; void decodeUPC(const std::string &input) { auto decode = [](const std::string &candidate) { using OT = std::vector<int>; OT output; size_t pos = 0; auto part = candidate.substr(pos, END_SENTINEL.length()); if (part == END_SENTINEL) { pos += END_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } for (size_t i = 0; i < 6; i++) { part = candidate.substr(pos, 7); pos += 7; auto e = LEFT_DIGITS.find(part); if (e != LEFT_DIGITS.end()) { output.push_back(e->second); } else { return std::make_pair(false, output); } } part = candidate.substr(pos, MID_SENTINEL.length()); if (part == MID_SENTINEL) { pos += MID_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } for (size_t i = 0; i < 6; i++) { part = candidate.substr(pos, 7); pos += 7; auto e = RIGHT_DIGITS.find(part); if (e != RIGHT_DIGITS.end()) { output.push_back(e->second); } else { return std::make_pair(false, output); } } part = candidate.substr(pos, END_SENTINEL.length()); if (part == END_SENTINEL) { pos += END_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } int sum = 0; for (size_t i = 0; i < output.size(); i++) { if (i % 2 == 0) { sum += 3 * output[i]; } else { sum += output[i]; } } return std::make_pair(sum % 10 == 0, output); }; auto candidate = trim(input); auto out = decode(candidate); if (out.first) { std::cout << out.second << '\n'; } else { std::reverse(candidate.begin(), candidate.end()); out = decode(candidate); if (out.first) { std::cout << out.second << " Upside down\n"; } else if (out.second.size()) { std::cout << "Invalid checksum\n"; } else { std::cout << "Invalid digit(s)\n"; } } } int main() { std::vector<std::string> barcodes = { " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", }; for (auto &barcode : barcodes) { decodeUPC(barcode); } return 0; }
URL encoding
C++
Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: * ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). * ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) * ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) * ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) * ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) * Extended characters with character codes of 128 decimal (80 hex) and above. ;Example: The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". ;Variations: * Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". * Special characters have different encodings for different standards: ** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~". ** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". ** encodeURI function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#". ;Options: It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. ;Related tasks: * [[URL decoding]] * [[URL parser]]
#include <QByteArray> #include <iostream> int main( ) { QByteArray text ( "http://foo bar/" ) ; QByteArray encoded( text.toPercentEncoding( ) ) ; std::cout << encoded.data( ) << '\n' ; return 0 ; }
Unbias a random generator
C++ from C#
Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1. ;Task details: * Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. * Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. * For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#include <iostream> #include <random> std::default_random_engine generator; bool biased(int n) { std::uniform_int_distribution<int> distribution(1, n); return distribution(generator) == 1; } bool unbiased(int n) { bool flip1, flip2; /* Flip twice, and check if the values are the same. * If so, flip again. Otherwise, return the value of the first flip. */ do { flip1 = biased(n); flip2 = biased(n); } while (flip1 == flip2); return flip1; } int main() { for (size_t n = 3; n <= 6; n++) { int biasedZero = 0; int biasedOne = 0; int unbiasedZero = 0; int unbiasedOne = 0; for (size_t i = 0; i < 100000; i++) { if (biased(n)) { biasedOne++; } else { biasedZero++; } if (unbiased(n)) { unbiasedOne++; } else { unbiasedZero++; } } std::cout << "(N = " << n << ")\n"; std::cout << "Biased:\n"; std::cout << " 0 = " << biasedZero << "; " << biasedZero / 1000.0 << "%\n"; std::cout << " 1 = " << biasedOne << "; " << biasedOne / 1000.0 << "%\n"; std::cout << "Unbiased:\n"; std::cout << " 0 = " << unbiasedZero << "; " << unbiasedZero / 1000.0 << "%\n"; std::cout << " 1 = " << unbiasedOne << "; " << unbiasedOne / 1000.0 << "%\n"; std::cout << '\n'; } return 0; }
Universal Turing machine
C++
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936-1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. ;Task: Simulate such a machine capable of taking the definition of any other Turing machine and executing it. Of course, you will not have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. '''Simple incrementer''' * '''States:''' q0, qf * '''Initial state:''' q0 * '''Terminating states:''' qf * '''Permissible symbols:''' B, 1 * '''Blank symbol:''' B * '''Rules:''' ** (q0, 1, 1, right, q0) ** (q0, B, 1, stay, qf) The input for this machine should be a tape of 1 1 1 '''Three-state busy beaver''' * '''States:''' a, b, c, halt * '''Initial state:''' a * '''Terminating states:''' halt * '''Permissible symbols:''' 0, 1 * '''Blank symbol:''' 0 * '''Rules:''' ** (a, 0, 1, right, b) ** (a, 1, 1, left, c) ** (b, 0, 1, left, a) ** (b, 1, 1, right, b) ** (c, 0, 1, left, b) ** (c, 1, 1, stay, halt) The input for this machine should be an empty tape. '''Bonus:''' '''5-state, 2-symbol probable Busy Beaver machine from Wikipedia''' * '''States:''' A, B, C, D, E, H * '''Initial state:''' A * '''Terminating states:''' H * '''Permissible symbols:''' 0, 1 * '''Blank symbol:''' 0 * '''Rules:''' ** (A, 0, 1, right, B) ** (A, 1, 1, left, C) ** (B, 0, 1, right, C) ** (B, 1, 1, right, B) ** (C, 0, 1, right, D) ** (C, 1, 0, left, E) ** (D, 0, 1, left, A) ** (D, 1, 1, left, D) ** (E, 0, 1, stay, H) ** (E, 1, 0, left, A) The input for this machine should be an empty tape. This machine runs for more than 47 millions steps.
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iomanip> //-------------------------------------------------------------------------------------------------- typedef unsigned int uint; using namespace std; const uint TAPE_MAX_LEN = 49152; //-------------------------------------------------------------------------------------------------- struct action { char write, direction; }; //-------------------------------------------------------------------------------------------------- class tape { public: tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); } void reset() { clear( '0' ); headPos = _sp; } char read(){ return _t[headPos]; } void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; } void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); } void action( const action* a ) { write( a->write ); move( a->direction ); } void print( int c = 10 ) { int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx; for( int x = st; x < ed; x++ ) { tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } cout << endl << setw( c + 1 ) << "^" << endl; } private: void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; } void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } } string _t; uint headPos, _sp; char blk; const uint MAX_LEN; }; //-------------------------------------------------------------------------------------------------- class state { public: bool operator ==( const string o ) { return o == name; } string name, next; char symbol, write, direction; }; //-------------------------------------------------------------------------------------------------- class actionTable { public: bool loadTable( string file ) { reset(); ifstream mf; mf.open( file.c_str() ); if( mf.is_open() ) { string str; state stt; while( mf.good() ) { getline( mf, str ); if( str[0] == '\'' ) break; parseState( str, stt ); states.push_back( stt ); } while( mf.good() ) { getline( mf, str ); if( str == "" ) continue; if( str[0] == '!' ) blank = str.erase( 0, 1 )[0]; if( str[0] == '^' ) curState = str.erase( 0, 1 ); if( str[0] == '>' ) input = str.erase( 0, 1 ); } mf.close(); return true; } cout << "Could not open " << file << endl; return false; } bool action( char symbol, action& a ) { vector<state>::iterator f = states.begin(); while( true ) { f = find( f, states.end(), curState ); if( f == states.end() ) return false; if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) ) { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; } f++; } return true; } void reset() { states.clear(); blank = '0'; curState = input = ""; } string getInput() { return input; } char getBlank() { return blank; } private: void parseState( string str, state& stt ) { string a[5]; int idx = 0; for( string::iterator si = str.begin(); si != str.end(); si++ ) { if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); } stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4]; } vector<state> states; char blank; string curState, input; }; //-------------------------------------------------------------------------------------------------- class utm { public: utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; } void start() { while( true ) { reset(); int t = showMenu(); if( t == 0 ) return; if( !at.loadTable( files[t - 1] ) ) return; startMachine(); } } private: void simulate() { char r; action a; while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); } cout << endl << endl; system( "pause" ); } int showMenu() { int t = -1; while( t < 0 || t > 3 ) { system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit"; cout << endl << endl << "Choose an action "; cin >> t; } return t; } void reset() { tp.reset(); at.reset(); } void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); } tape tp; actionTable at; string files[7]; }; //-------------------------------------------------------------------------------------------------- int main( int a, char* args[] ){ utm mm; mm.start(); return 0; } //--------------------------------------------------------------------------------------------------
Validate International Securities Identification Number
C++
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. ;Task: Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format, ''and'' the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. ;Details: The format of an ISIN is as follows: +------------- a 2-character ISO country code (A-Z) | +----------- a 9-character security code (A-Z, 0-9) | | +-- a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: # '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103. # '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.) ;Test cases: :::: {| class="wikitable" ! ISIN ! Validity ! Comment |- | US0378331005 || valid || |- | US0373831005 || not valid || The transposition typo is caught by the checksum constraint. |- | U50378331005 || not valid || The substitution typo is caught by the format constraint. |- | US03378331005 || not valid || The duplication typo is caught by the format constraint. |- | AU0000XVGZA3 || valid || |- | AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint. |- | FR0000988040 || valid || |} (The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.) Related task: * [[Luhn test of credit card numbers]] ;Also see: * Interactive online ISIN validator * Wikipedia article: International Securities Identification Number
#include <string> #include <regex> #include <algorithm> #include <numeric> #include <sstream> bool CheckFormat(const std::string& isin) { std::regex isinRegEpx(R"([A-Z]{2}[A-Z0-9]{9}[0-9])"); std::smatch match; return std::regex_match(isin, match, isinRegEpx); } std::string CodeISIN(const std::string& isin) { std::string coded; int offset = 'A' - 10; for (auto ch : isin) { if (ch >= 'A' && ch <= 'Z') { std::stringstream ss; ss << static_cast<int>(ch) - offset; coded += ss.str(); } else { coded.push_back(ch); } } return std::move(coded); } bool CkeckISIN(const std::string& isin) { if (!CheckFormat(isin)) return false; std::string coded = CodeISIN(isin); // from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#C.2B.2B11 return luhn(coded); } #include <iomanip> #include <iostream> int main() { std::string isins[] = { "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" }; for (const auto& isin : isins) { std::cout << isin << std::boolalpha << " - " << CkeckISIN(isin) <<std::endl; } return 0; }
Van Eck sequence
C++
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. ;Example: Using A: :0 Using B: :0 0 Using C: :0 0 1 Using B: :0 0 1 0 Using C: (zero last occurred two steps back - before the one) :0 0 1 0 2 Using B: :0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) :0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) :0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) :0 0 1 0 2 0 2 2 1 6 ... ;Task: # Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. # Use it to display here, on this page: :# The first ten terms of the sequence. :# Terms 991 - to - 1000 of the sequence. ;References: * Don't Know (the Van Eck Sequence) - Numberphile video. * Wikipedia Article: Van Eck's Sequence. * OEIS sequence: A181391.
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
Van der Corput sequence
C++ from Raku
When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 \times 2^1 + 0 \times 2^0. You can also have binary digits to the right of the "point", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. The weight for the second column to the right of the point is 2^{-2} or 1/4. And so on. If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4. Monte Carlo simulations. This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. '''Hint''' A ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 1\times 2^0. Reflected this would become .1101 or 1\times 2^{-1} + 1\times 2^{-2} + 0\times 2^{-3} + 1\times 2^{-4} ;Task description: * Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2. * Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0). * As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. ;See also: * The Basic Low Discrepancy Sequences * [[Non-decimal radices/Convert]] * Van der Corput sequence
#include <cmath> #include <iostream> double vdc(int n, double base = 2) { double vdc = 0, denom = 1; while (n) { vdc += fmod(n, base) / (denom *= base); n /= base; // note: conversion from 'double' to 'int' } return vdc; } int main() { for (double base = 2; base < 6; ++base) { std::cout << "Base " << base << "\n"; for (int n = 0; n < 10; ++n) { std::cout << vdc(n, base) << " "; } std::cout << "\n\n"; } }
Variable declaration reset
C++
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
#include <array> #include <iostream> int main() { constexpr std::array s {1,2,2,3,4,4,5}; if(!s.empty()) { int previousValue = s[0]; for(size_t i = 1; i < s.size(); ++i) { // in C++, variables in block scope are reset at each iteration const int currentValue = s[i]; if(i > 0 && previousValue == currentValue) { std::cout << i << "\n"; } previousValue = currentValue; } } }
Vector products
C++
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). If you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: * '''The dot product''' (a scalar quantity) :::: A * B = a1b1 + a2b2 + a3b3 * '''The cross product''' (a vector quantity) :::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) * '''The scalar triple product''' (a scalar quantity) :::: A * (B x C) * '''The vector triple product''' (a vector quantity) :::: A x (B x C) ;Task: Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) # Create a named function/subroutine/method to compute the dot product of two vectors. # Create a function to compute the cross product of two vectors. # Optionally create a function to compute the scalar triple product of three vectors. # Optionally create a function to compute the vector triple product of three vectors. # Compute and display: a * b # Compute and display: a x b # Compute and display: a * (b x c), the scalar triple product. # Compute and display: a x (b x c), the vector triple product. ;References: * A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}. * Wikipedia dot product. * Wikipedia cross product. * Wikipedia triple product. ;Related tasks: * [[Dot product]] * [[Quaternion type]]
#include <iostream> template< class T > class D3Vector { template< class U > friend std::ostream & operator<<( std::ostream & , const D3Vector<U> & ) ; public : D3Vector( T a , T b , T c ) { x = a ; y = b ; z = c ; } T dotproduct ( const D3Vector & rhs ) { T scalar = x * rhs.x + y * rhs.y + z * rhs.z ; return scalar ; } D3Vector crossproduct ( const D3Vector & rhs ) { T a = y * rhs.z - z * rhs.y ; T b = z * rhs.x - x * rhs.z ; T c = x * rhs.y - y * rhs.x ; D3Vector product( a , b , c ) ; return product ; } D3Vector triplevec( D3Vector & a , D3Vector & b ) { return crossproduct ( a.crossproduct( b ) ) ; } T triplescal( D3Vector & a, D3Vector & b ) { return dotproduct( a.crossproduct( b ) ) ; } private : T x , y , z ; } ; template< class T > std::ostream & operator<< ( std::ostream & os , const D3Vector<T> & vec ) { os << "( " << vec.x << " , " << vec.y << " , " << vec.z << " )" ; return os ; } int main( ) { D3Vector<int> a( 3 , 4 , 5 ) , b ( 4 , 3 , 5 ) , c( -5 , -12 , -13 ) ; std::cout << "a . b : " << a.dotproduct( b ) << "\n" ; std::cout << "a x b : " << a.crossproduct( b ) << "\n" ; std::cout << "a . b x c : " << a.triplescal( b , c ) << "\n" ; std::cout << "a x b x c : " << a.triplevec( b , c ) << "\n" ; return 0 ; }
Verhoeff algorithm
C++
Description The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code. As the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here. ;Task: Write routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable. The more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them. Write your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example. Use your routines to calculate check digits for the integers: '''236''', '''12345''' and '''123456789012''' and then validate them. Also attempt to validate the same integers if the check digits in all cases were '''9''' rather than what they actually are. Display digit by digit calculations for the first two integers but not for the third. ;Related task: * [[Damm algorithm]]
#include <iostream> #include <string> #include <array> #include <iomanip> typedef std::pair<std::string, bool> data; const std::array<const std::array<int32_t, 10>, 10> multiplication_table = { { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 }, { 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 }, { 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 }, { 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 }, { 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 }, { 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 }, { 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 }, { 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 }, { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 } } }; const std::array<int32_t, 10> inverse = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 }; const std::array<const std::array<int32_t, 10>, 8> permutation_table = { { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }, { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 }, { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 }, { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 }, { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 }, { 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 }, { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 } } }; int32_t verhoeff_checksum(std::string number, bool doValidation, bool doDisplay) { if ( doDisplay ) { std::string calculationType = doValidation ? "Validation" : "Check digit"; std::cout << calculationType << " calculations for " << number << "\n" << std::endl; std::cout << " i ni p[i, ni] c" << std::endl; std::cout << "-------------------" << std::endl; } if ( ! doValidation ) { number += "0"; } int32_t c = 0; const int32_t le = number.length() - 1; for ( int32_t i = le; i >= 0; i-- ) { const int32_t ni = number[i] - '0'; const int32_t pi = permutation_table[(le - i) % 8][ni]; c = multiplication_table[c][pi]; if ( doDisplay ) { std::cout << std::setw(2) << le - i << std::setw(3) << ni << std::setw(8) << pi << std::setw(6) << c << "\n" << std::endl; } } if ( doDisplay && ! doValidation ) { std::cout << "inverse[" << c << "] = " << inverse[c] << "\n" << std::endl;; } return doValidation ? c == 0 : inverse[c]; } int main( ) { const std::array<data, 3> tests = { std::make_pair("123", true), std::make_pair("12345", true), std::make_pair("123456789012", false) }; for ( data test : tests ) { int32_t digit = verhoeff_checksum(test.first, false, test.second); std::cout << "The check digit for " << test.first << " is " << digit << "\n" << std::endl; std::string numbers[2] = { test.first + std::to_string(digit), test.first + "9" }; for ( std::string number : numbers ) { digit = verhoeff_checksum(number, true, test.second); std::string result = ( digit == 1 ) ? "correct" : "incorrect"; std::cout << "The validation for " << number << " is " << result << ".\n" << std::endl; } } }
Visualize a tree
C++
A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as: :::* indented text (a la unix tree command) :::* nested HTML tables :::* hierarchical GUI widgets :::* 2D or 3D images :::* etc. ;Task: Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
#include <functional> #include <iostream> #include <random> class BinarySearchTree { private: struct Node { int key; Node *left, *right; Node(int k) : key(k), left(nullptr), right(nullptr) { //empty } } *root; public: BinarySearchTree() : root(nullptr) { // empty } bool insert(int key) { if (root == nullptr) { root = new Node(key); } else { auto n = root; Node *parent; while (true) { if (n->key == key) { return false; } parent = n; bool goLeft = key < n->key; n = goLeft ? n->left : n->right; if (n == nullptr) { if (goLeft) { parent->left = new Node(key); } else { parent->right = new Node(key); } break; } } } return true; } friend std::ostream &operator<<(std::ostream &, const BinarySearchTree &); }; template<typename T> void display(std::ostream &os, const T *n) { if (n != nullptr) { os << "Node("; display(os, n->left); os << ',' << n->key << ','; display(os, n->right); os << ")"; } else { os << '-'; } } std::ostream &operator<<(std::ostream &os, const BinarySearchTree &bst) { display(os, bst.root); return os; } int main() { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, 200); auto rng = std::bind(distribution, generator); BinarySearchTree tree; tree.insert(100); for (size_t i = 0; i < 20; i++) { tree.insert(rng()); } std::cout << tree << '\n'; return 0; }
Vogel's approximation method
C++ from Java
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them "A", "B", "C", "D", and "E". They estimate that: * A will require 30 hours of work, * B will require 20 hours of work, * C will require 70 hours of work, * D will require 30 hours of work, and * E will require 60 hours of work. They have identified 4 contractors willing to do the work, called "W", "X", "Y", and "Z". * W has 50 hours available to commit to working, * X has 60 hours available, * Y has 50 hours available, and * Z has 50 hours available. The cost per hour for each contractor for each task is summarized by the following table: A B C D E W 16 16 13 22 17 X 14 14 13 19 15 Y 19 19 20 23 50 Z 50 12 50 15 11 The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows: :Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply A B C D E W X Y Z 1 2 2 0 4 4 3 1 0 1 E-Z(50) Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply). Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working. Repeat until all supply and demand is met: 2 2 2 0 3 2 3 1 0 - C-W(50) 3 5 5 7 4 35 - 1 0 - E-X(10) 4 5 5 7 4 - - 1 0 - C-X(20) 5 5 5 - 4 - - 0 0 - A-X(30) 6 - 19 - 23 - - - 4 - D-Y(30) - - - - - - - - - B-Y(20) Finally calculate the cost of your solution. In the example given it is PS3100: A B C D E W 50 X 30 20 10 Y 20 30 Z 50 The optimal solution determined by GLPK is PS3100: A B C D E W 50 X 10 20 20 10 Y 20 30 Z 50 ;Cf. * Transportation problem
#include <iostream> #include <numeric> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } std::vector<int> demand = { 30, 20, 70, 30, 60 }; std::vector<int> supply = { 50, 60, 50, 50 }; std::vector<std::vector<int>> costs = { {16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11} }; int nRows = supply.size(); int nCols = demand.size(); std::vector<bool> rowDone(nRows, false); std::vector<bool> colDone(nCols, false); std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0)); std::vector<int> diff(int j, int len, bool isRow) { int min1 = INT_MAX; int min2 = INT_MAX; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) { continue; } int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) { min2 = c; } } return { min2 - min1, min1, minP }; } std::vector<int> maxPenalty(int len1, int len2, bool isRow) { int md = INT_MIN; int pc = -1; int pm = -1; int mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) { continue; } std::vector<int> res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; // max diff pm = i; // pos of max diff mc = res[1]; // min cost pc = res[2]; // pos of min cost } } return isRow ? std::vector<int> { pm, pc, mc, md } : std::vector<int>{ pc, pm, mc, md }; } std::vector<int> nextCell() { auto res1 = maxPenalty(nRows, nCols, true); auto res2 = maxPenalty(nCols, nRows, false); if (res1[3] == res2[3]) { return res1[2] < res2[2] ? res1 : res2; } return res1[3] > res2[3] ? res2 : res1; } int main() { int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; }); int totalCost = 0; while (supplyLeft > 0) { auto cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = std::min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) { colDone[c] = true; } supply[r] -= quantity; if (supply[r] == 0) { rowDone[r] = true; } result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } for (auto &a : result) { std::cout << a << '\n'; } std::cout << "Total cost: " << totalCost; return 0; }
Voronoi diagram
C++
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''. ;Task: Demonstrate how to generate and display a Voroni diagram. See algo [[K-means++ clustering]].
#include <windows.h> #include <vector> #include <string> using namespace std; ////////////////////////////////////////////////////// struct Point { int x, y; }; ////////////////////////////////////////////////////// class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); 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; void *bits_ptr = nullptr; HDC dc = GetDC(GetConsoleWindow()); bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0); if (!bmp_) return false; hdc_ = CreateCompatibleDC(dc); SelectObject(hdc_, bmp_); ReleaseDC(GetConsoleWindow(), dc); width_ = w; height_ = h; return true; } void SetPenColor(DWORD clr) { if (pen_) DeleteObject(pen_); pen_ = CreatePen(PS_SOLID, 1, clr); SelectObject(hdc_, pen_); } bool SaveBitmap(const char* path) { HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return false; } BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; GetObject(bmp_, sizeof(bitmap), &bitmap); DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory(dwp_bits, 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)dwp_bits, &infoheader, DIB_RGB_COLORS); DWORD wb; WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr); WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr); WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr); CloseHandle(file); delete[] dwp_bits; return true; } HDC hdc() { return hdc_; } int width() { return width_; } int height() { return height_; } private: HBITMAP bmp_; HDC hdc_; HPEN pen_; int width_, height_; }; static int DistanceSqrd(const Point& point, int x, int y) { int xd = x - point.x; int yd = y - point.y; return (xd * xd) + (yd * yd); } ////////////////////////////////////////////////////// class Voronoi { public: void Make(MyBitmap* bmp, int count) { bmp_ = bmp; CreatePoints(count); CreateColors(); CreateSites(); SetSitesPoints(); } private: void CreateSites() { int w = bmp_->width(), h = bmp_->height(), d; for (int hh = 0; hh < h; hh++) { for (int ww = 0; ww < w; ww++) { int ind = -1, dist = INT_MAX; for (size_t it = 0; it < points_.size(); it++) { const Point& p = points_[it]; d = DistanceSqrd(p, ww, hh); if (d < dist) { dist = d; ind = it; } } if (ind > -1) SetPixel(bmp_->hdc(), ww, hh, colors_[ind]); else __asm nop // should never happen! } } } void SetSitesPoints() { for (const auto& point : points_) { int x = point.x, y = point.y; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) SetPixel(bmp_->hdc(), x + i, y + j, 0); } } void CreatePoints(int count) { const int w = bmp_->width() - 20, h = bmp_->height() - 20; for (int i = 0; i < count; i++) { points_.push_back({ rand() % w + 10, rand() % h + 10 }); } } void CreateColors() { for (size_t i = 0; i < points_.size(); i++) { DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50); colors_.push_back(c); } } vector<Point> points_; vector<DWORD> colors_; MyBitmap* bmp_; }; ////////////////////////////////////////////////////// int main(int argc, char* argv[]) { ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); srand(GetTickCount()); MyBitmap bmp; bmp.Create(512, 512); bmp.SetPenColor(0); Voronoi v; v.Make(&bmp, 50); BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY); bmp.SaveBitmap("v.bmp"); system("pause"); return 0; }