title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
K-d tree
C++
{{wikipedia|K-d tree}} A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). k-d trees are a special case of binary space partitioning trees. k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead. '''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets: # The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)]. # 1000 3-d points uniformly distributed in a 3-d cube. For the Wikipedia example, find the nearest neighbor to point (9, 2) For the random data, pick a random location and find the nearest neighbor. In addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed. Output should show the point searched for, the point found, the distance to the point, and the number of nodes visited. There are variant algorithms for constructing the tree. You can use a simple median strategy or implement something more efficient. Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. You do not have to implement these. The requirement for this task is specifically the nearest single neighbor. Also there are algorithms for inserting, deleting, and balancing k-d trees. These are also not required for the task.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> /** * Class for representing a point. coordinate_type must be a numeric type. */ template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } /** * Returns the coordinate in the given dimension. * * @param index dimension index (zero based) * @return coordinate in the given dimension */ coordinate_type get(size_t index) const { return coords_[index]; } /** * Returns the distance squared from this point to another * point. * * @param pt another point * @return distance squared from this point to the other point */ double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } /** * C++ k-d tree implementation, based on the C version at rosettacode.org. */ template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; /** * Constructor taking a pair of iterators. Adds each * point in the range [begin, end) to the tree. * * @param begin start of range * @param end end of range */ template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } /** * Constructor taking a function object that generates * points. The function object will be called n times * to populate the tree. * * @param f function that returns a point * @param n number of points to add */ template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } /** * Returns true if the tree is empty, false otherwise. */ bool empty() const { return nodes_.empty(); } /** * Returns the number of nodes visited by the last call * to nearest(). */ size_t visited() const { return visited_; } /** * Returns the distance between the input point and return value * from the last call to nearest(). */ double distance() const { return std::sqrt(best_dist_); } /** * Finds the nearest point in the tree to the given point. * It is not valid to call this function if the tree is empty. * * @param pt a point * @return the nearest point in the tree to the given point */ const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
Kaprekar numbers
C++
A positive integer is a Kaprekar number if: * It is '''1''' (unity) * The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. * The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, .... ;Example process: 10000 (1002) splitting from left to right: * The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive. * Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid. ;Task: Generate and show all Kaprekar numbers less than 10,000. ;Extra credit: Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; * Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g ;Reference: * The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version ;Related task: * [[Casting out nines]]
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; //we do not accept figures ending in a sequence of zeroes if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
Kernighans large earthquake problem
C++
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. ;Problem: You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 ;Task: * Create a program or script invocation to find all the events with magnitude greater than 6 * Assuming an appropriate name e.g. "data.txt" for the file: :# Either: Show how your program is invoked to process a data file of that name. :# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
// Randizo was here! #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream file("../include/earthquake.txt"); int count_quake = 0; int column = 1; string value; double size_quake; string row = ""; while(file >> value) { if(column == 3) { size_quake = stod(value); if(size_quake>6.0) { count_quake++; row += value + "\t"; cout << row << endl; } column = 1; row = ""; } else { column++; row+=value + "\t"; } } cout << "\nNumber of quakes greater than 6 is " << count_quake << endl; return 0; }
Keyboard input/Obtain a Y or N response
C++
Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
Knight's tour
C++11
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
#include <iostream> #include <iomanip> #include <array> #include <string> #include <tuple> #include <algorithm> using namespace std; template<int N = 8> class Board { public: array<pair<int, int>, 8> moves; array<array<int, N>, N> data; Board() { moves[0] = make_pair(2, 1); moves[1] = make_pair(1, 2); moves[2] = make_pair(-1, 2); moves[3] = make_pair(-2, 1); moves[4] = make_pair(-2, -1); moves[5] = make_pair(-1, -2); moves[6] = make_pair(1, -2); moves[7] = make_pair(2, -1); } array<int, 8> sortMoves(int x, int y) const { array<tuple<int, int>, 8> counts; for(int i = 0; i < 8; ++i) { int dx = get<0>(moves[i]); int dy = get<1>(moves[i]); int c = 0; for(int j = 0; j < 8; ++j) { int x2 = x + dx + get<0>(moves[j]); int y2 = y + dy + get<1>(moves[j]); if (x2 < 0 || x2 >= N || y2 < 0 || y2 >= N) continue; if(data[y2][x2] != 0) continue; c++; } counts[i] = make_tuple(c, i); } // Shuffle to randomly break ties random_shuffle(counts.begin(), counts.end()); // Lexicographic sort sort(counts.begin(), counts.end()); array<int, 8> out; for(int i = 0; i < 8; ++i) out[i] = get<1>(counts[i]); return out; } void solve(string start) { for(int v = 0; v < N; ++v) for(int u = 0; u < N; ++u) data[v][u] = 0; int x0 = start[0] - 'a'; int y0 = N - (start[1] - '0'); data[y0][x0] = 1; array<tuple<int, int, int, array<int, 8>>, N*N> order; order[0] = make_tuple(x0, y0, 0, sortMoves(x0, y0)); int n = 0; while(n < N*N-1) { int x = get<0>(order[n]); int y = get<1>(order[n]); bool ok = false; for(int i = get<2>(order[n]); i < 8; ++i) { int dx = moves[get<3>(order[n])[i]].first; int dy = moves[get<3>(order[n])[i]].second; if(x+dx < 0 || x+dx >= N || y+dy < 0 || y+dy >= N) continue; if(data[y + dy][x + dx] != 0) continue; get<2>(order[n]) = i + 1; ++n; data[y+dy][x+dx] = n + 1; order[n] = make_tuple(x+dx, y+dy, 0, sortMoves(x+dx, y+dy)); ok = true; break; } if(!ok) // Failed. Backtrack. { data[y][x] = 0; --n; } } } template<int N> friend ostream& operator<<(ostream &out, const Board<N> &b); }; template<int N> ostream& operator<<(ostream &out, const Board<N> &b) { for (int v = 0; v < N; ++v) { for (int u = 0; u < N; ++u) { if (u != 0) out << ","; out << setw(3) << b.data[v][u]; } out << endl; } return out; } int main() { Board<5> b1; b1.solve("c3"); cout << b1 << endl; Board<8> b2; b2.solve("b5"); cout << b2 << endl; Board<31> b3; // Max size for <1000 squares b3.solve("a1"); cout << b3 << endl; return 0; }
Knuth's algorithm S
C++11
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). ;The algorithm: :* Select the first n items as the sample as they become available; :* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. :* Repeat 2nd step for any subsequent items. ;The Task: :* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item. :* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S. :* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of: :::# Use the s_of_n_creator with n == 3 to generate an s_of_n. :::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. Note: A class taking n and generating a callable instance/function might also be used. ;Reference: * The Art of Computer Programming, Vol 2, 3.4.2 p.142 ;Related tasks: * [[One of n lines in a file]] * [[Accumulator factory]]
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime> template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (std::rand() % i < n) { sample[std::rand() % n] = item; } return sample; }; } int main() { std::srand(std::time(NULL)); int bin[10] = {0}; for (int trial = 0; trial < 100000; trial++) { auto s_of_n = s_of_n_creator<int>(3); std::vector<int> sample; for (int i = 0; i < 10; i++) sample = s_of_n(i); for (int s : sample) bin[s]++; } for (int x : bin) std::cout << x << std::endl; return 0; }
Koch curve
C++
Draw a Koch curve. See details: Koch curve
// See https://en.wikipedia.org/wiki/Koch_snowflake #include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; // sqrt(3)/2 struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dy = y1 - y0; double dx = x1 - x0; output[j++] = {x0, y0}; output[j++] = {x0 + dx/3, y0 + dy/3}; output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3}; output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3}; } output[j] = {x1, y1}; return output; } std::vector<point> koch_points(int size, int iterations) { double length = size * sqrt3_2 * 0.95; double x = (size - length)/2; double y = size/2 - length * sqrt3_2/3; std::vector<point> points{ {x, y}, {x + length/2, y + length * sqrt3_2}, {x + length, y}, {x, y} }; for (int i = 0; i < iterations; ++i) points = koch_next(points); return points; } void koch_curve_svg(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http://www.w3.org/2000/svg' width='" << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << "<path stroke-width='1' stroke='white' fill='none' d='"; auto points(koch_points(size, iterations)); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "z'/>\n</svg>\n"; } int main() { std::ofstream out("koch_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } koch_curve_svg(out, 600, 5); return EXIT_SUCCESS; }
Kolakoski sequence
C++
The natural numbers, (excluding zero); with the property that: : ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''. ;Example: This is ''not'' a Kolakoski sequence: 1,1,2,2,2,1,2,2,1,2,... Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this: : Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ... The above gives the RLE of: 2, 3, 1, 2, 1, ... The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''. ;Creating a Kolakoski sequence: Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,.... # We start the sequence s with the first item from the cycle c: 1 # An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s. We started s with 1 and therefore s[k] states that it should appear only the 1 time. Increment k Get the next item from c and append it to the end of sequence s. s will then become: 1, 2 k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2 Increment k Append the next item from the cycle to the list: 1, 2,2, 1 k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1 increment k ... '''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case. ;Task: # Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle. # Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence. # Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE). # Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 20 members of the sequence generated from (2, 1) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1) # Check the sequence againt its RLE. (There are rules on generating Kolakoski sequences from this method that are broken by the last example)
#include <iostream> #include <vector> using Sequence = std::vector<int>; std::ostream& operator<<(std::ostream& os, const Sequence& v) { os << "[ "; for (const auto& e : v) { std::cout << e << ", "; } os << "]"; return os; } int next_in_cycle(const Sequence& s, size_t i) { return s[i % s.size()]; } Sequence gen_kolakoski(const Sequence& s, int n) { Sequence seq; for (size_t i = 0; seq.size() < n; ++i) { const int next = next_in_cycle(s, i); Sequence nv(i >= seq.size() ? next : seq[i], next); seq.insert(std::end(seq), std::begin(nv), std::end(nv)); } return { std::begin(seq), std::begin(seq) + n }; } bool is_possible_kolakoski(const Sequence& s) { Sequence r; for (size_t i = 0; i < s.size();) { int count = 1; for (size_t j = i + 1; j < s.size(); ++j) { if (s[j] != s[i]) break; ++count; } r.push_back(count); i += count; } for (size_t i = 0; i < r.size(); ++i) if (r[i] != s[i]) return false; return true; } int main() { std::vector<Sequence> seqs = { { 1, 2 }, { 2, 1 }, { 1, 3, 1, 2 }, { 1, 3, 2, 1 } }; for (const auto& s : seqs) { auto kol = gen_kolakoski(s, s.size() > 2 ? 30 : 20); std::cout << "Starting with: " << s << ": " << std::endl << "Kolakoski sequence: " << kol << std::endl << "Possibly kolakoski? " << is_possible_kolakoski(kol) << std::endl; } return 0; }
Kosaraju
C++ from D
{{wikipedia|Graph}} Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph. For this task consider the directed graph with these connections: 0 -> 1 1 -> 2 2 -> 0 3 -> 1, 3 -> 2, 3 -> 4 4 -> 3, 4 -> 5 5 -> 2, 5 -> 6 6 -> 5 7 -> 4, 7 -> 6, 7 -> 7 And report the kosaraju strongly connected component for each node. ;References: * The article on Wikipedia.
#include <functional> #include <iostream> #include <ostream> #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> kosaraju(std::vector<std::vector<int>>& g) { // 1. For each vertex u of the graph, mark u as unvisited. Let l be empty. auto size = g.size(); std::vector<bool> vis(size); // all false by default std::vector<int> l(size); // all zero by default auto x = size; // index for filling l in reverse order std::vector<std::vector<int>> t(size); // transpose graph // Recursive subroutine 'visit': std::function<void(int)> visit; visit = [&](int u) { if (!vis[u]) { vis[u] = true; for (auto v : g[u]) { visit(v); t[v].push_back(u); // construct transpose } l[--x] = u; } }; // 2. For each vertex u of the graph do visit(u) for (int i = 0; i < g.size(); ++i) { visit(i); } std::vector<int> c(size); // used for component assignment // Recursive subroutine 'assign': std::function<void(int, int)> assign; assign = [&](int u, int root) { if (vis[u]) { // repurpose vis to mean 'unassigned' vis[u] = false; c[u] = root; for (auto v : t[u]) { assign(v, root); } } }; // 3: For each element u of l in order, do assign(u, u) for (auto u : l) { assign(u, u); } return c; } std::vector<std::vector<int>> g = { {1}, {2}, {0}, {1, 2, 4}, {3, 5}, {2, 6}, {5}, {4, 6, 7}, }; int main() { using namespace std; cout << kosaraju(g) << endl; return 0; }
Largest int from concatenated ints
C++
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
#include <iostream> #include <sstream> #include <algorithm> #include <vector> #include <string> std::string findLargestConcat ( std::vector< int > & mynumbers ) { std::vector<std::string> concatnumbers ; std::sort ( mynumbers.begin( ) , mynumbers.end( ) ) ; do { std::ostringstream numberstream ; for ( int i : mynumbers ) numberstream << i ; concatnumbers.push_back( numberstream.str( ) ) ; } while ( std::next_permutation( mynumbers.begin( ) , mynumbers.end( ) )) ; return *( std::max_element( concatnumbers.begin( ) , concatnumbers.end( ) ) ) ; } int main( ) { std::vector<int> mynumbers = { 98, 76 , 45 , 34, 9 , 4 , 3 , 1 } ; std::vector<int> othernumbers = { 54 , 546 , 548 , 60 } ; std::cout << "The largest concatenated int is " << findLargestConcat( mynumbers ) << " !\n" ; std::cout << "And here it is " << findLargestConcat( othernumbers ) << " !\n" ; return 0 ; }
Largest number divisible by its digits
C++ from D
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits. These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the (base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. ;Example: '''135''' is evenly divisible by '''1''', '''3''', and '''5'''. Note that the digit zero (0) can not be in the number as integer division by zero is undefined. The digits must all be unique so a base ten number will have at most '''9''' digits. Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.) ;Stretch goal: Do the same thing for hexadecimal. ;Related tasks: :* gapful numbers. :* palindromic gapful numbers. ;Also see: :* The OEIS sequence: A115569: Lynch-Bell numbers.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d != 0) return false; if (set.find(d) != set.end()) { return false; } set.insert(d); } return true; } int main() { for (int i = 98764321; i > 0; i--) { if (checkDec(i)) { std::cout << i << "\n"; break; } } return 0; }
Largest proper divisor of n
C++
a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.
#include <cassert> #include <iomanip> #include <iostream> int largest_proper_divisor(int n) { assert(n > 0); if ((n & 1) == 0) return n >> 1; for (int p = 3; p * p <= n; p += 2) { if (n % p == 0) return n / p; } return 1; } int main() { for (int n = 1; n < 101; ++n) { std::cout << std::setw(2) << largest_proper_divisor(n) << (n % 10 == 0 ? '\n' : ' '); } }
Last letter-first letter
C++
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category, Child 1: dog Child 2: goldfish Child 1: hippopotamus Child 2: snake ... ;Task: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated. audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask Extra brownie points for dealing with the full list of 646 names.
#include <iostream> #include <string> #include <vector> struct last_letter_first_letter { size_t max_path_length = 0; size_t max_path_length_count = 0; std::vector<std::string> max_path_example; void search(std::vector<std::string>& names, size_t offset) { if (offset > max_path_length) { max_path_length = offset; max_path_length_count = 1; max_path_example.assign(names.begin(), names.begin() + offset); } else if (offset == max_path_length) { ++max_path_length_count; } char last_letter = names[offset - 1].back(); for (size_t i = offset, n = names.size(); i < n; ++i) { if (names[i][0] == last_letter) { names[i].swap(names[offset]); search(names, offset + 1); names[i].swap(names[offset]); } } } void find_longest_chain(std::vector<std::string>& names) { max_path_length = 0; max_path_length_count = 0; max_path_example.clear(); for (size_t i = 0, n = names.size(); i < n; ++i) { names[i].swap(names[0]); search(names, 1); names[i].swap(names[0]); } } }; int main() { std::vector<std::string> names{"audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", "relicanth", "remoraid", "rufflet", "sableye", "scolipede", "scrafty", "seaking", "sealeo", "silcoon", "simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", "wailord", "wartortle", "whismur", "wingull", "yamask"}; last_letter_first_letter solver; solver.find_longest_chain(names); std::cout << "Maximum path length: " << solver.max_path_length << '\n'; std::cout << "Paths of that length: " << solver.max_path_length_count << '\n'; std::cout << "Example path of that length:\n "; for (size_t i = 0, n = solver.max_path_example.size(); i < n; ++i) { if (i > 0 && i % 7 == 0) std::cout << "\n "; else if (i > 0) std::cout << ' '; std::cout << solver.max_path_example[i]; } std::cout << '\n'; }
Latin Squares in reduced form
C++ from C#
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained. For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row. Demonstrate by: * displaying the four reduced Latin Squares of order 4. * for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector> typedef std::vector<std::vector<int>> matrix; matrix dList(int n, int start) { start--; // use 0 basing std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; std::sort(a.begin() + 1, a.end()); auto first = a[1]; // recursive closure permutes a[1:] matrix r; std::function<void(int)> recurse; recurse = [&](int last) { if (last == first) { // bottom of recursion you get here once for each permutation. // test if permutation is deranged. for (size_t j = 1; j < a.size(); j++) { auto v = a[j]; if (j == v) { return; //no, ignore it } } // yes, save a copy with 1 based indexing std::vector<int> b; std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; }); r.push_back(b); return; } for (int i = last; i >= 1; i--) { std::swap(a[i], a[last]); recurse(last - 1); std::swap(a[i], a[last]); } }; recurse(n - 1); return r; } void printSquare(const matrix &latin, int n) { for (auto &row : latin) { auto it = row.cbegin(); auto end = row.cend(); std::cout << '['; if (it != end) { std::cout << *it; it = std::next(it); } while (it != end) { std::cout << ", " << *it; it = std::next(it); } std::cout << "]\n"; } std::cout << '\n'; } unsigned long reducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { std::cout << "[]\n"; } return 0; } else if (n == 1) { if (echo) { std::cout << "[1]\n"; } return 1; } matrix rlatin; for (int i = 0; i < n; i++) { rlatin.push_back({}); for (int j = 0; j < n; j++) { rlatin[i].push_back(j); } } // first row for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } unsigned long count = 0; std::function<void(int)> recurse; recurse = [&](int i) { auto rows = dList(n, i); for (size_t r = 0; r < rows.size(); r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.size() - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { printSquare(rlatin, n); } } outer: {} } }; //remaining rows recurse(2); return count; } unsigned long factorial(unsigned long n) { if (n <= 0) return 1; unsigned long prod = 1; for (unsigned long i = 2; i <= n; i++) { prod *= i; } return prod; } int main() { std::cout << "The four reduced lating squares of order 4 are:\n"; reducedLatinSquares(4, true); std::cout << "The size of the set of reduced latin squares for the following orders\n"; std::cout << "and hence the total number of latin squares of these orders are:\n\n"; for (int n = 1; n < 7; n++) { auto size = reducedLatinSquares(n, false); auto f = factorial(n - 1); f *= f * n * size; std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n'; } return 0; }
Law of cosines - triples
C++
The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(g) = C2 ;Specific angles: For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation": A2 + B2 = C2 For an angle of '''60o''' this becomes the less familiar equation: A2 + B2 - AB = C2 And finally for an angle of '''120o''' this becomes the equation: A2 + B2 + AB = C2 ;Task: * Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered. * Restrain all sides to the integers '''1..13''' inclusive. * Show how many results there are for each of the three angles mentioned above. * Display results on this page. Note: Triangles with the same length sides but different order are to be treated as the same. ;Optional Extra credit: * How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''. ;Related Task * [[Pythagorean triples]] ;See also: * Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
#include <cmath> #include <iostream> #include <tuple> #include <vector> using triple = std::tuple<int, int, int>; void print_triple(std::ostream& out, const triple& t) { out << '(' << std::get<0>(t) << ',' << std::get<1>(t) << ',' << std::get<2>(t) << ')'; } void print_vector(std::ostream& out, const std::vector<triple>& vec) { if (vec.empty()) return; auto i = vec.begin(); print_triple(out, *i++); for (; i != vec.end(); ++i) { out << ' '; print_triple(out, *i); } out << "\n\n"; } int isqrt(int n) { return static_cast<int>(std::sqrt(n)); } int main() { const int min = 1, max = 13; std::vector<triple> solutions90, solutions60, solutions120; for (int a = min; a <= max; ++a) { int a2 = a * a; for (int b = a; b <= max; ++b) { int b2 = b * b, ab = a * b; int c2 = a2 + b2; int c = isqrt(c2); if (c <= max && c * c == c2) solutions90.emplace_back(a, b, c); else { c2 = a2 + b2 - ab; c = isqrt(c2); if (c <= max && c * c == c2) solutions60.emplace_back(a, b, c); else { c2 = a2 + b2 + ab; c = isqrt(c2); if (c <= max && c * c == c2) solutions120.emplace_back(a, b, c); } } } } std::cout << "There are " << solutions60.size() << " solutions for gamma = 60 degrees:\n"; print_vector(std::cout, solutions60); std::cout << "There are " << solutions90.size() << " solutions for gamma = 90 degrees:\n"; print_vector(std::cout, solutions90); std::cout << "There are " << solutions120.size() << " solutions for gamma = 120 degrees:\n"; print_vector(std::cout, solutions120); const int max2 = 10000; int count = 0; for (int a = min; a <= max2; ++a) { for (int b = a + 1; b <= max2; ++b) { int c2 = a * a + b * b - a * b; int c = isqrt(c2); if (c <= max2 && c * c == c2) ++count; } } std::cout << "There are " << count << " solutions for gamma = 60 degrees in the range " << min << " to " << max2 << " where the sides are not all of the same length.\n"; return 0; }
Least common multiple
C++11
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
#include <cstdlib> #include <iostream> #include <tuple> int gcd(int a, int b) { a = abs(a); b = abs(b); while (b != 0) { std::tie(a, b) = std::make_tuple(b, a % b); } return a; } int lcm(int a, int b) { int c = gcd(a, b); return c == 0 ? 0 : a / c * b; } int main() { std::cout << "The least common multiple of 12 and 18 is " << lcm(12, 18) << ",\n" << "and their greatest common divisor is " << gcd(12, 18) << "!" << std::endl; return 0; }
Left factorials
C++
'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; the same notation can be confusingly seen being used for the two different definitions. Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: :::::::* !''n''` :::::::* !''n'' :::::::* ''n''! (It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''': ::::: !n = \sum_{k=0}^{n-1} k! :::: where ::::: !0 = 0 ;Task Display the left factorials for: * zero through ten (inclusive) * 20 through 110 (inclusive) by tens Display the length (in decimal digits) of the left factorials for: * 1,000 through 10,000 (inclusive), by thousands. ;Also see: * The OEIS entry: A003422 left factorials * The MathWorld entry: left factorial * The MathWorld entry: factorial sums * The MathWorld entry: subfactorial ;Related task: * permutations/derangements (subfactorials)
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 // optimized for 64-bit architecture typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else // optimized for 32-bit architecture typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif class bignum { private: // rep_.size() == 0 if and only if the value is zero. // Otherwise, the word rep_[0] keeps the least significant bits. vector<usingle> rep_; public: explicit bignum(usingle n = 0) { if (n > 0) rep_.push_back(n); } bool equals(usingle n) const { if (n == 0) return rep_.empty(); if (rep_.size() > 1) return false; return rep_[0] == n; } bignum add(usingle addend) const { bignum result(0); udouble sum = addend; for (size_t i = 0; i < rep_.size(); ++i) { sum += rep_[i]; result.rep_.push_back(sum & (((udouble)1 << word_len) - 1)); sum >>= word_len; } if (sum > 0) result.rep_.push_back((usingle)sum); return result; } bignum add(const bignum& addend) const { bignum result(0); udouble sum = 0; size_t sz1 = rep_.size(); size_t sz2 = addend.rep_.size(); for (size_t i = 0; i < max(sz1, sz2); ++i) { if (i < sz1) sum += rep_[i]; if (i < sz2) sum += addend.rep_[i]; result.rep_.push_back(sum & (((udouble)1 << word_len) - 1)); sum >>= word_len; } if (sum > 0) result.rep_.push_back((usingle)sum); return result; } bignum multiply(usingle factor) const { bignum result(0); udouble product = 0; for (size_t i = 0; i < rep_.size(); ++i) { product += (udouble)rep_[i] * factor; result.rep_.push_back(product & (((udouble)1 << word_len) - 1)); product >>= word_len; } if (product > 0) result.rep_.push_back((usingle)product); return result; } void divide(usingle divisor, bignum& quotient, usingle& remainder) const { quotient.rep_.resize(0); udouble dividend = 0; remainder = 0; for (size_t i = rep_.size(); i > 0; --i) { dividend = ((udouble)remainder << word_len) + rep_[i - 1]; usingle quo = (usingle)(dividend / divisor); remainder = (usingle)(dividend % divisor); if (quo > 0 || i < rep_.size()) quotient.rep_.push_back(quo); } reverse(quotient.rep_.begin(), quotient.rep_.end()); } }; ostream& operator<<(ostream& os, const bignum& x); ostream& operator<<(ostream& os, const bignum& x) { string rep; bignum dividend = x; bignum quotient; usingle remainder; while (true) { dividend.divide(10, quotient, remainder); rep += (char)('0' + remainder); if (quotient.equals(0)) break; dividend = quotient; } reverse(rep.begin(), rep.end()); os << rep; return os; } bignum lfact(usingle n); bignum lfact(usingle n) { bignum result(0); bignum f(1); for (usingle k = 1; k <= n; ++k) { result = result.add(f); f = f.multiply(k); } return result; } int main() { for (usingle i = 0; i <= 10; ++i) { cout << "!" << i << " = " << lfact(i) << endl; } for (usingle i = 20; i <= 110; i += 10) { cout << "!" << i << " = " << lfact(i) << endl; } for (usingle i = 1000; i <= 10000; i += 1000) { stringstream ss; ss << lfact(i); cout << "!" << i << " has " << ss.str().size() << " digits." << endl; } }
Levenshtein distance
C++
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
#include <string> #include <iostream> using namespace std; // Compute Levenshtein Distance // Martin Ettl, 2012-10-05 size_t uiLevenshteinDistance(const string &s1, const string &s2) { const size_t m(s1.size()), n(s2.size()); if( m==0 ) return n; if( n==0 ) return m; // allocation below is not ISO-compliant, // it won't work with -pedantic-errors. size_t costs[n + 1]; for( size_t k=0; k<=n; k++ ) costs[k] = k; size_t i { 0 }; for (char const &c1 : s1) { costs[0] = i+1; size_t corner { i }, j { 0 }; for (char const &c2 : s2) { size_t upper { costs[j+1] }; if( c1 == c2 ) costs[j+1] = corner; else { size_t t(upper<corner? upper: corner); costs[j+1] = (costs[j]<t?costs[j]:t)+1; } corner = upper; j++; } i++; } return costs[n]; } int main() { string s0 { "rosettacode" }, s1 { "raisethysword" }; cout << "distance between " << s0 << " and " << s1 << " : " << uiLevenshteinDistance(s0,s1) << endl; return 0; }
List rooted trees
C++ from Java
You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical. If we use a matching pair of parentheses to represent a bag, the ways are: For 1 bag, there's one way: () <- a bag for 2 bags, there's one way: (()) <- one bag in another for 3 bags, there are two: ((())) <- 3 bags nested Russian doll style (()()) <- 2 bags side by side, inside the third for 4 bags, four: (()()()) ((())()) ((()())) (((()))) Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration. It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81. ;Task: Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive. This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size. As an example output, run 5 bags. There should be 9 ways.
#include <iostream> #include <vector> std::vector<long> TREE_LIST; std::vector<int> OFFSET; void init() { for (size_t i = 0; i < 32; i++) { if (i == 1) { OFFSET.push_back(1); } else { OFFSET.push_back(0); } } } void append(long t) { TREE_LIST.push_back(1 | (t << 1)); } void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { std::cout << '('; } else { std::cout << ')'; } t = t >> 1; } } void listTrees(int n) { for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) { show(TREE_LIST[i], 2 * n); std::cout << '\n'; } } void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } auto pp = pos; auto ss = sl; if (sl > rem) { ss = rem; pp = OFFSET[ss]; } else if (pp >= OFFSET[ss + 1]) { ss--; if (ss == 0) { return; } pp = OFFSET[ss]; } assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } void makeTrees(int n) { if (OFFSET[n + 1] != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET[n - 1], n - 1); OFFSET[n + 1] = TREE_LIST.size(); } void test(int n) { if (n < 1 || n > 12) { throw std::runtime_error("Argument must be between 1 and 12"); } append(0); makeTrees(n); std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n'; listTrees(n); } int main() { init(); test(5); return 0; }
Long year
C++
Most years have 52 weeks, some have 53, according to ISO8601. ;Task: Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
// Reference: // https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year #include <iostream> inline int p(int year) { return (year + (year/4) - (year/100) + (year/400)) % 7; } bool is_long_year(int year) { return p(year) == 4 || p(year - 1) == 3; } void print_long_years(int from, int to) { for (int year = from, count = 0; year <= to; ++year) { if (is_long_year(year)) { if (count > 0) std::cout << ((count % 10 == 0) ? '\n' : ' '); std::cout << year; ++count; } } } int main() { std::cout << "Long years between 1800 and 2100:\n"; print_long_years(1800, 2100); std::cout << '\n'; return 0; }
Longest common subsequence
C++
'''Introduction''' Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string. The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings. Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n. The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''. Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly. We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''. Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly. A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable. A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j]. Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''. According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. '''Background''' Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n''). '''Note''' [Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)''). '''Legend''' A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of matches (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet S of distinct symbols in A + B '''References''' [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, ''pp.'' 275-281] '''Examples''' The sequences "1234" and "1224533324" have an LCS of "1234": '''1234''' '''12'''245'''3'''332'''4''' For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": '''t'''hi'''si'''sa'''test''' '''t'''e'''s'''t'''i'''ng123'''test'''ing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia.
#include <stdint.h> #include <string> #include <memory> // for shared_ptr<> #include <iostream> #include <deque> #include <unordered_map> //[C++11] #include <algorithm> // for lower_bound() #include <iterator> // for next() and prev() using namespace std; class LCS { protected: // Instances of the Pair linked list class are used to recover the LCS: class Pair { public: uint32_t index1; uint32_t index2; shared_ptr<Pair> next; Pair(uint32_t index1, uint32_t index2, shared_ptr<Pair> next = nullptr) : index1(index1), index2(index2), next(next) { } static shared_ptr<Pair> Reverse(const shared_ptr<Pair> pairs) { shared_ptr<Pair> head = nullptr; for (auto next = pairs; next != nullptr; next = next->next) head = make_shared<Pair>(next->index1, next->index2, head); return head; } }; typedef deque<shared_ptr<Pair>> PAIRS; typedef deque<uint32_t> INDEXES; typedef unordered_map<char, INDEXES> CHAR_TO_INDEXES_MAP; typedef deque<INDEXES*> MATCHES; static uint32_t FindLCS( MATCHES& indexesOf2MatchedByIndex1, shared_ptr<Pair>* pairs) { auto traceLCS = pairs != nullptr; PAIRS chains; INDEXES prefixEnd; // //[Assert]After each index1 iteration prefixEnd[index3] is the least index2 // such that the LCS of s1[0:index1] and s2[0:index2] has length index3 + 1 // uint32_t index1 = 0; for (const auto& it1 : indexesOf2MatchedByIndex1) { auto dq2 = *it1; auto limit = prefixEnd.end(); for (auto it2 = dq2.rbegin(); it2 != dq2.rend(); it2++) { // Each index1, index2 pair corresponds to a match auto index2 = *it2; // // Note: The reverse iterator it2 visits index2 values in descending order, // allowing in-place update of prefixEnd[]. std::lower_bound() is used to // perform a binary search. // limit = lower_bound(prefixEnd.begin(), limit, index2); // // Look ahead to the next index2 value to optimize Pairs used by the Hunt // and Szymanski algorithm. If the next index2 is also an improvement on // the value currently held in prefixEnd[index3], a new Pair will only be // superseded on the next index2 iteration. // // Verify that a next index2 value exists; and that this value is greater // than the final index2 value of the LCS prefix at prev(limit): // auto preferNextIndex2 = next(it2) != dq2.rend() && (limit == prefixEnd.begin() || *prev(limit) < *next(it2)); // // Depending on match redundancy, this optimization may reduce the number // of Pair allocations by factors ranging from 2 up to 10 or more. // if (preferNextIndex2) continue; auto index3 = distance(prefixEnd.begin(), limit); if (limit == prefixEnd.end()) { // Insert Case prefixEnd.push_back(index2); // Refresh limit iterator: limit = prev(prefixEnd.end()); if (traceLCS) { chains.push_back(pushPair(chains, index3, index1, index2)); } } else if (index2 < *limit) { // Update Case // Update limit value: *limit = index2; if (traceLCS) { chains[index3] = pushPair(chains, index3, index1, index2); } } } // next index2 index1++; } // next index1 if (traceLCS) { // Return the LCS as a linked list of matched index pairs: auto last = chains.empty() ? nullptr : chains.back(); // Reverse longest chain *pairs = Pair::Reverse(last); } auto length = prefixEnd.size(); return length; } private: static shared_ptr<Pair> pushPair( PAIRS& chains, const ptrdiff_t& index3, uint32_t& index1, uint32_t& index2) { auto prefix = index3 > 0 ? chains[index3 - 1] : nullptr; return make_shared<Pair>(index1, index2, prefix); } protected: // // Match() avoids m*n comparisons by using CHAR_TO_INDEXES_MAP to // achieve O(m+n) performance, where m and n are the input lengths. // // The lookup time can be assumed constant in the case of characters. // The symbol space is larger in the case of records; but the lookup // time will be O(log(m+n)), at most. // static void Match( CHAR_TO_INDEXES_MAP& indexesOf2MatchedByChar, MATCHES& indexesOf2MatchedByIndex1, const string& s1, const string& s2) { uint32_t index = 0; for (const auto& it : s2) indexesOf2MatchedByChar[it].push_back(index++); for (const auto& it : s1) { auto& dq2 = indexesOf2MatchedByChar[it]; indexesOf2MatchedByIndex1.push_back(&dq2); } } static string Select(shared_ptr<Pair> pairs, uint32_t length, bool right, const string& s1, const string& s2) { string buffer; buffer.reserve(length); for (auto next = pairs; next != nullptr; next = next->next) { auto c = right ? s2[next->index2] : s1[next->index1]; buffer.push_back(c); } return buffer; } public: static string Correspondence(const string& s1, const string& s2) { CHAR_TO_INDEXES_MAP indexesOf2MatchedByChar; MATCHES indexesOf2MatchedByIndex1; // holds references into indexesOf2MatchedByChar Match(indexesOf2MatchedByChar, indexesOf2MatchedByIndex1, s1, s2); shared_ptr<Pair> pairs; // obtain the LCS as index pairs auto length = FindLCS(indexesOf2MatchedByIndex1, &pairs); return Select(pairs, length, false, s1, s2); } };
Longest common substring
C++14
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
#include <string> #include <algorithm> #include <iostream> #include <set> #include <vector> auto collectSubStrings( const std::string& s, int maxSubLength ) { int l = s.length(); auto res = std::set<std::string>(); for ( int start = 0; start < l; start++ ) { int m = std::min( maxSubLength, l - start + 1 ); for ( int length = 1; length < m; length++ ) { res.insert( s.substr( start, length ) ); } } return res; } std::string lcs( const std::string& s0, const std::string& s1 ) { // collect substring set auto maxSubLength = std::min( s0.length(), s1.length() ); auto set0 = collectSubStrings( s0, maxSubLength ); auto set1 = collectSubStrings( s1, maxSubLength ); // get commons into a vector auto common = std::vector<std::string>(); std::set_intersection( set0.begin(), set0.end(), set1.begin(), set1.end(), std::back_inserter( common ) ); // get the longest one std::nth_element( common.begin(), common.begin(), common.end(), []( const std::string& s1, const std::string& s2 ) { return s1.length() > s2.length(); } ); return *common.begin(); } int main( int argc, char* argv[] ) { auto s1 = std::string( "thisisatest" ); auto s2 = std::string( "testing123testing" ); std::cout << "The longest common substring of " << s1 << " and " << s2 << " is:\n"; std::cout << "\"" << lcs( s1, s2 ) << "\" !\n"; return 0; }
Longest increasing subsequence
C++
Calculate and show here a longest increasing subsequence of the list: :\{3, 2, 6, 4, 5, 1\} And of the list: :\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} Note that a list may have more than one subsequence that is of the maximum length. ;Ref: # Dynamic Programming #1: Longest Increasing Subsequence on YouTube # An efficient solution can be based on Patience sorting.
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename T> bool compare (const T& node1, const T& node2) { return node1->value < node2->value; } template <typename Container> Container lis(const Container& values) { typedef typename Container::value_type E; typedef typename Container::const_iterator ValueConstIter; typedef typename Container::iterator ValueIter; typedef Node<E>* NodePtr; typedef const NodePtr ConstNodePtr; typedef std::vector<Node<E> > NodeVector; typedef std::vector<NodePtr> NodePtrVector; typedef typename NodeVector::iterator NodeVectorIter; typedef typename NodePtrVector::iterator NodePtrVectorIter; std::vector<NodePtr> pileTops; std::vector<Node<E> > nodes(values.size()); // sort into piles NodeVectorIter cur_node = nodes.begin(); for (ValueConstIter cur_value = values.begin(); cur_value != values.end(); ++cur_value, ++cur_node) { NodePtr node = &*cur_node; node->value = *cur_value; // lower_bound returns the first element that is not less than 'node->value' NodePtrVectorIter lb = std::lower_bound(pileTops.begin(), pileTops.end(), node, compare<NodePtr>); if (lb != pileTops.begin()) node->prev_node = *(lb - 1); if (lb == pileTops.end()) pileTops.push_back(node); else *lb = node; } // extract LIS from piles // note that LIS length is equal to the number of piles Container result(pileTops.size()); std::reverse_iterator<ValueIter> r = std::reverse_iterator<ValueIter>(result.rbegin()); for (NodePtr node = pileTops.back(); node; node = node->prev_node, ++r) *r = node->value; return result; } template <typename Container> void show_lis(const Container& values) { const Container& result = lis(values); for (typename Container::const_iterator it = result.begin(); it != result.end(); ++it) { std::cout << *it << ' '; } std::cout << std::endl; } int main() { const int arr1[] = { 3, 2, 6, 4, 5, 1 }; const int arr2[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; std::vector<int> vec1(arr1, arr1 + sizeof(arr1) / sizeof(arr1[0])); std::vector<int> vec2(arr2, arr2 + sizeof(arr2) / sizeof(arr2[0])); show_lis(vec1); show_lis(vec2); }
Lucky and even lucky numbers
C++ from Go
Note that in the following explanation list indices are assumed to start at ''one''. ;Definition of lucky numbers ''Lucky numbers'' are positive integers that are formed by: # Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ... # Return the first number from the list (which is '''1'''). # (Loop begins here) #* Note then return the second number from the list (which is '''3'''). #* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''7'''). #* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ... #* Note then return the 4th number from the list (which is '''9'''). #* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ... #* Take the 5th, i.e. '''13'''. Remove every 13th. #* Take the 6th, i.e. '''15'''. Remove every 15th. #* Take the 7th, i.e. '''21'''. Remove every 21th. #* Take the 8th, i.e. '''25'''. Remove every 25th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above ''except for the very first step'': # Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ... # Return the first number from the list (which is '''2'''). # (Loop begins here) #* Note then return the second number from the list (which is '''4'''). #* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''6'''). #* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ... #* Take the 4th, i.e. '''10'''. Remove every 10th. #* Take the 5th, i.e. '''12'''. Remove every 12th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Task requirements * Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' * Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: ** missing arguments ** too many arguments ** number (or numbers) aren't legal ** misspelled argument ('''lucky''' or '''evenLucky''') * The command line handling should: ** support mixed case handling of the (non-numeric) arguments ** support printing a particular number ** support printing a range of numbers by their index ** support printing a range of numbers by their values * The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) +-------------------+----------------------------------------------------+ | j | Jth lucky number | | j , lucky | Jth lucky number | | j , evenLucky | Jth even lucky number | | | | | j k | Jth through Kth (inclusive) lucky numbers | | j k lucky | Jth through Kth (inclusive) lucky numbers | | j k evenLucky | Jth through Kth (inclusive) even lucky numbers | | | | | j -k | all lucky numbers in the range j --> |k| | | j -k lucky | all lucky numbers in the range j --> |k| | | j -k evenLucky | all even lucky numbers in the range j --> |k| | +-------------------+----------------------------------------------------+ where |k| is the absolute value of k Demonstrate the program by: * showing the first twenty ''lucky'' numbers * showing the first twenty ''even lucky'' numbers * showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive) * showing all ''even lucky'' numbers in the same range as above * showing the 10,000th ''lucky'' number (extra credit) * showing the 10,000th ''even lucky'' number (extra credit) ;See also: * This task is related to the [[Sieve of Eratosthenes]] task. * OEIS Wiki Lucky numbers. * Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. * Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. * Entry lucky numbers on The Eric Weisstein's World of Mathematics.
#include <algorithm> #include <iostream> #include <iterator> #include <vector> const int luckySize = 60000; std::vector<int> luckyEven(luckySize); std::vector<int> luckyOdd(luckySize); void init() { for (int i = 0; i < luckySize; ++i) { luckyEven[i] = i * 2 + 2; luckyOdd[i] = i * 2 + 1; } } void filterLuckyEven() { for (size_t n = 2; n < luckyEven.size(); ++n) { int m = luckyEven[n - 1]; int end = (luckyEven.size() / m) * m - 1; for (int j = end; j >= m - 1; j -= m) { std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j); luckyEven.pop_back(); } } } void filterLuckyOdd() { for (size_t n = 2; n < luckyOdd.size(); ++n) { int m = luckyOdd[n - 1]; int end = (luckyOdd.size() / m) * m - 1; for (int j = end; j >= m - 1; j -= m) { std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j); luckyOdd.pop_back(); } } } void printBetween(size_t j, size_t k, bool even) { std::ostream_iterator<int> out_it{ std::cout, ", " }; if (even) { size_t max = luckyEven.back(); if (j > max || k > max) { std::cerr << "At least one are is too big\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even numbers between " << j << " and " << k << " are: "; std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) { return j <= n && n <= k; }); } else { size_t max = luckyOdd.back(); if (j > max || k > max) { std::cerr << "At least one are is too big\n"; exit(EXIT_FAILURE); } std::cout << "Lucky numbers between " << j << " and " << k << " are: "; std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) { return j <= n && n <= k; }); } std::cout << '\n'; } void printRange(size_t j, size_t k, bool even) { std::ostream_iterator<int> out_it{ std::cout, ", " }; if (even) { if (k >= luckyEven.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even numbers " << j << " to " << k << " are: "; std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it); } else { if (k >= luckyOdd.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky numbers " << j << " to " << k << " are: "; std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it); } } void printSingle(size_t j, bool even) { if (even) { if (j >= luckyEven.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even number " << j << "=" << luckyEven[j - 1] << '\n'; } else { if (j >= luckyOdd.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky number " << j << "=" << luckyOdd[j - 1] << '\n'; } } void help() { std::cout << "./lucky j [k] [--lucky|--evenLucky]\n"; std::cout << "\n"; std::cout << " argument(s) | what is displayed\n"; std::cout << "==============================================\n"; std::cout << "-j=m | mth lucky number\n"; std::cout << "-j=m --lucky | mth lucky number\n"; std::cout << "-j=m --evenLucky | mth even lucky number\n"; std::cout << "-j=m -k=n | mth through nth (inclusive) lucky numbers\n"; std::cout << "-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n"; std::cout << "-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n"; std::cout << "-j=m -k=-n | all lucky numbers in the range [m, n]\n"; std::cout << "-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n"; std::cout << "-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n"; } int main(int argc, char **argv) { bool evenLucky = false; int j = 0; int k = 0; // skip arg 0, because that is just the executable name if (argc < 2) { help(); exit(EXIT_FAILURE); } bool good = false; for (int i = 1; i < argc; ++i) { if ('-' == argv[i][0]) { if ('-' == argv[i][1]) { // long args if (0 == strcmp("--lucky", argv[i])) { evenLucky = false; } else if (0 == strcmp("--evenLucky", argv[i])) { evenLucky = true; } else { std::cerr << "Unknown long argument: [" << argv[i] << "]\n"; exit(EXIT_FAILURE); } } else { // short args if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) { good = true; j = atoi(&argv[i][3]); } else if ('k' == argv[i][1] && '=' == argv[i][2]) { k = atoi(&argv[i][3]); } else { std::cerr << "Unknown short argument: " << argv[i] << '\n'; exit(EXIT_FAILURE); } } } else { std::cerr << "Unknown argument: " << argv[i] << '\n'; exit(EXIT_FAILURE); } } if (!good) { help(); exit(EXIT_FAILURE); } init(); filterLuckyEven(); filterLuckyOdd(); if (k > 0) { printRange(j, k, evenLucky); } else if (k < 0) { printBetween(j, -k, evenLucky); } else { printSingle(j, evenLucky); } return 0; }
Mad Libs
C++
{{wikipedia}} Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. ;Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: went for a walk in the park. found a . decided to take it home. Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
#include <iostream> #include <string> using namespace std; int main() { string story, input; //Loop while(true) { //Get a line from the user getline(cin, input); //If it's blank, break this loop if(input == "\r") break; //Add the line to the story story += input; } //While there is a '<' in the story int begin; while((begin = story.find("<")) != string::npos) { //Get the category from between '<' and '>' int end = story.find(">"); string cat = story.substr(begin + 1, end - begin - 1); //Ask the user for a replacement cout << "Give me a " << cat << ": "; cin >> input; //While there's a matching category //in the story while((begin = story.find("<" + cat + ">")) != string::npos) { //Replace it with the user's replacement story.replace(begin, cat.length()+2, input); } } //Output the final story cout << endl << story; return 0; }
Magic 8-ball
C++
Create Magic 8-Ball. See details at: Magic 8-Ball.
#include <array> #include <cstdlib> #include <ctime> #include <iostream> #include <string> int main() { constexpr std::array<const char*, 20> answers = { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful." }; std::string input; std::srand(std::time(nullptr)); while (true) { std::cout << "\n? : "; std::getline(std::cin, input); if (input.empty()) { break; } std::cout << answers[std::rand() % answers.size()] << '\n'; } }
Magic squares of doubly even order
C++
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). This means that the subsquares also have an even size, which plays a role in the construction. {| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%" |- |'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8''' |- |'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16''' |- |'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41''' |- |'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33''' |- |'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25''' |- |'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17''' |- |'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56''' |- |'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64''' |} ;Task Create a magic square of '''8 x 8'''. ;Related tasks * [[Magic squares of odd order]] * [[Magic squares of singly even order]] ;See also: * Doubly Even Magic Squares (1728.org)
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; int i = 0; for( int curRow = 0; curRow < sz; curRow++ ) { for( int curCol = 0; curCol < sz; curCol++ ) { sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; i++; } } } int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s( 8 ); s.display(); return 0; }
Magic squares of odd order
C++
A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). The numbers are usually (but not always) the first '''N'''2 positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''. {| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%" |- | '''8''' || '''1''' || '''6''' |- | '''3''' || '''5''' || '''7''' |- | '''4''' || '''9''' || '''2''' |} ;Task For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. Optionally, show the ''magic number''. You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''. ; Related tasks * [[Magic squares of singly even order]] * [[Magic squares of doubly even order]] ; See also: * MathWorld(tm) entry: Magic_square * Odd Magic Squares (1728.org)
#include <iostream> #include <sstream> #include <iomanip> #include <cassert> #include <vector> using namespace std; class MagicSquare { public: MagicSquare(int d) : sqr(d*d,0), sz(d) { assert(d&1); fillSqr(); } void display() { cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) cout << setw( l + 2 ) << sqr[yy + x]; cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { int sx = sz / 2, sy = 0, c = 0; while( c < sz * sz ) { if( !sqr[sx + sy * sz] ) { sqr[sx + sy * sz]= c + 1; inc( sx ); dec( sy ); c++; } else { dec( sx ); inc( sy ); inc( sy ); } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } vector<int> sqr; int sz; }; int main() { MagicSquare s(7); s.display(); return 0; }
Magic squares of singly even order
C++
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction. ;Task Create a magic square of 6 x 6. ; Related tasks * [[Magic squares of odd order]] * [[Magic squares of doubly even order]] ; See also * Singly Even Magic Squares (1728.org)
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr() { sqr = 0; } ~magicSqr() { if( sqr ) delete [] sqr; } void create( int d ) { if( sqr ) delete [] sqr; if( d & 1 ) d++; while( d % 4 == 0 ) { d += 2; } sz = d; sqr = new int[sz * sz]; memset( sqr, 0, sz * sz * sizeof( int ) ); fillSqr(); } void display() { cout << "Singly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void siamese( int from, int to ) { int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1; while( count > 0 ) { bool done = false; while ( false == done ) { if( curCol >= oneSide ) curCol = 0; if( curRow < 0 ) curRow = oneSide - 1; done = true; if( sqr[curCol + sz * curRow] != 0 ) { curCol -= 1; curRow += 2; if( curCol < 0 ) curCol = oneSide - 1; if( curRow >= oneSide ) curRow -= oneSide; done = false; } } sqr[curCol + sz * curRow] = s; s++; count--; curCol++; curRow--; } } void fillSqr() { int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3; siamese( 0, n ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = n; c < sz; c++ ) { int m = sqr[c - n + row]; sqr[c + row] = m + add1; sqr[c + row + ns] = m + add3; sqr[c - n + row + ns] = m + add2; } } int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = co; c < sz; c++ ) { sqr[c + row] -= add3; sqr[c + row + ns] += add3; } } for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = 0; c < lc; c++ ) { int cc = c; if( r == lc ) cc++; sqr[cc + row] += add2; sqr[cc + row + ns] -= add2; } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s; s.create( 6 ); s.display(); return 0; }
Map range
C++
Given two ranges: :::* [a_1,a_2] and :::* [b_1,b_2]; :::* then a value s in range [a_1,a_2] :::* is linearly mapped to a value t in range [b_1,b_2] where: :::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)} ;Task: Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range [0, 10] to the range [-1, 0]. ;Extra credit: Show additional idiomatic ways of performing the mapping, using tools available to the language.
#include <iostream> #include <utility> template<typename tVal> tVal map_value(std::pair<tVal,tVal> a, std::pair<tVal, tVal> b, tVal inVal) { tVal inValNorm = inVal - a.first; tVal aUpperNorm = a.second - a.first; tVal normPosition = inValNorm / aUpperNorm; tVal bUpperNorm = b.second - b.first; tVal bValNorm = normPosition * bUpperNorm; tVal outVal = b.first + bValNorm; return outVal; } int main() { std::pair<float,float> a(0,10), b(-1,0); for(float value = 0.0; 10.0 >= value; ++value) std::cout << "map_value(" << value << ") = " << map_value(a, b, value) << std::endl; return 0; }
Maximum triangle path sum
C++ from Ada
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. ;Task: Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
/* Algorithm complexity: n*log(n) */ #include <iostream> int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); // size should be a triangular number // walk backward by rows, replacing each element with max attainable therefrom for (int n = tn - 1; n > 0; --n) // n is size of row, note we do not process last row for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) // from the start to the end of row triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; }
Mian-Chowla sequence
C++ from Go
The Mian-Chowla sequence is an integer sequence defined recursively. Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences. The sequence starts with: ::a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ::ai + aj is distinct, for all i and j less than or equal to n. ;The Task: :* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence. :* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence. Demonstrating working through the first few terms longhand: ::a1 = 1 ::1 + 1 = 2 Speculatively try a2 = 2 ::1 + 1 = 2 ::1 + 2 = 3 ::2 + 2 = 4 There are no repeated sums so '''2''' is the next number in the sequence. Speculatively try a3 = 3 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 3 = 4 ::2 + 2 = 4 ::2 + 3 = 5 ::3 + 3 = 6 Sum of '''4''' is repeated so '''3''' is rejected. Speculatively try a3 = 4 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 4 = 5 ::2 + 2 = 4 ::2 + 4 = 6 ::4 + 4 = 8 There are no repeated sums so '''4''' is the next number in the sequence. And so on... ;See also: :* OEIS:A005282 Mian-Chowla sequence
using namespace std; #include <iostream> #include <ctime> #define n 100 #define nn ((n * (n + 1)) >> 1) bool Contains(int lst[], int item, int size) { for (int i = 0; i < size; i++) if (item == lst[i]) return true; return false; } int * MianChowla() { static int mc[n]; mc[0] = 1; int sums[nn]; sums[0] = 2; int sum, le, ss = 1; for (int i = 1; i < n; i++) { le = ss; for (int j = mc[i - 1] + 1; ; j++) { mc[i] = j; for (int k = 0; k <= i; k++) { sum = mc[k] + j; if (Contains(sums, sum, ss)) { ss = le; goto nxtJ; } sums[ss++] = sum; } break; nxtJ:; } } return mc; } int main() { clock_t st = clock(); int * mc; mc = MianChowla(); double et = ((double)(clock() - st)) / CLOCKS_PER_SEC; cout << "The first 30 terms of the Mian-Chowla sequence are:\n"; for (int i = 0; i < 30; i++) { cout << mc[i] << ' '; } cout << "\n\nTerms 91 to 100 of the Mian-Chowla sequence are:\n"; for (int i = 90; i < 100; i++) { cout << mc[i] << ' '; } cout << "\n\nComputation time was " << et << " seconds."; }
Middle three digits
C++
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
#include <iostream> std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size(); if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } } int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}; for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }
Minimum multiple of m where digital sum equals m
C++
Generate the sequence '''a(n)''' when each element is the minimum integer multiple '''m''' such that the digit sum of '''n''' times '''m''' is equal to '''n'''. ;Task * Find the first 40 elements of the sequence. ;Stretch * Find the next 30 elements of the sequence. ;See also ;* OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' '); break; } } } }
Minimum positive multiple in base 10 using only 0 and 1
C++ from C
Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''". ;Task: Write a routine to find the B10 of a given integer. E.G. '''n''' '''B10''' '''n''' x '''multiplier''' 1 1 ( 1 x 1 ) 2 10 ( 2 x 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the '''B10''' value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find '''B10''' for: 1998, 2079, 2251, 2277 Stretch goal; find '''B10''' for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation. ;See also: :* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. :* How to find Minimum Positive Multiple in base 10 using only 0 and 1
#include <iostream> #include <vector> __int128 imax(__int128 a, __int128 b) { if (a > b) { return a; } return b; } __int128 ipow(__int128 b, __int128 n) { if (n == 0) { return 1; } if (n == 1) { return b; } __int128 res = b; while (n > 1) { res *= b; n--; } return res; } __int128 imod(__int128 m, __int128 n) { __int128 result = m % n; if (result < 0) { result += n; } return result; } bool valid(__int128 n) { if (n < 0) { return false; } while (n > 0) { int r = n % 10; if (r > 1) { return false; } n /= 10; } return true; } __int128 mpm(const __int128 n) { if (n == 1) { return 1; } std::vector<__int128> L(n * n, 0); L[0] = 1; L[1] = 1; __int128 m, k, r, j; m = 0; while (true) { m++; if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) { break; } L[m * n + 0] = 1; for (k = 1; k < n; k++) { L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]); } } r = ipow(10, m); k = imod(-r, n); for (j = m - 1; j >= 1; j--) { if (L[(j - 1) * n + k] == 0) { r = r + ipow(10, j); k = imod(k - ipow(10, j), n); } } if (k == 1) { r++; } return r / n; } std::ostream& operator<<(std::ostream& os, __int128 n) { char buffer[64]; // more then is needed, but is nice and round; int pos = (sizeof(buffer) / sizeof(char)) - 1; bool negative = false; if (n < 0) { negative = true; n = -n; } buffer[pos] = 0; while (n > 0) { int rem = n % 10; buffer[--pos] = rem + '0'; n /= 10; } if (negative) { buffer[--pos] = '-'; } return os << &buffer[pos]; } void test(__int128 n) { __int128 mult = mpm(n); if (mult > 0) { std::cout << n << " * " << mult << " = " << (n * mult) << '\n'; } else { std::cout << n << "(no solution)\n"; } } int main() { int i; // 1-10 (inclusive) for (i = 1; i <= 10; i++) { test(i); } // 95-105 (inclusive) for (i = 95; i <= 105; i++) { test(i); } test(297); test(576); test(594); // needs a larger number type (64 bits signed) test(891); test(909); test(999); // needs a larger number type (87 bits signed) // optional test(1998); test(2079); test(2251); test(2277); // stretch test(2439); test(2997); test(4878); return 0; }
Modular arithmetic
C++ from D
equivalence relation called ''congruence''. For any positive integer p called the ''congruence modulus'', two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that: :a = b + k\,p The corresponding set of multiplicative inverse for this task. Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: :f(x) = x^{100} + x + 1 You will use 13 as the congruence modulus and you will compute f(10). It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
#include <iostream> #include <ostream> template<typename T> T f(const T& x) { return (T) pow(x, 100) + x + 1; } class ModularInteger { private: int value; int modulus; void validateOp(const ModularInteger& rhs) const { if (modulus != rhs.modulus) { throw std::runtime_error("Left-hand modulus does not match right-hand modulus."); } } public: ModularInteger(int v, int m) { modulus = m; value = v % m; } int getValue() const { return value; } int getModulus() const { return modulus; } ModularInteger operator+(const ModularInteger& rhs) const { validateOp(rhs); return ModularInteger(value + rhs.value, modulus); } ModularInteger operator+(int rhs) const { return ModularInteger(value + rhs, modulus); } ModularInteger operator*(const ModularInteger& rhs) const { validateOp(rhs); return ModularInteger(value * rhs.value, modulus); } friend std::ostream& operator<<(std::ostream&, const ModularInteger&); }; std::ostream& operator<<(std::ostream& os, const ModularInteger& self) { return os << "ModularInteger(" << self.value << ", " << self.modulus << ")"; } ModularInteger pow(const ModularInteger& lhs, int pow) { if (pow < 0) { throw std::runtime_error("Power must not be negative."); } ModularInteger base(1, lhs.getModulus()); while (pow-- > 0) { base = base * lhs; } return base; } int main() { using namespace std; ModularInteger input(10, 13); auto output = f(input); cout << "f(" << input << ") = " << output << endl; return 0; }
Modular inverse
C++ from C
From Wikipedia: In modulo ''m'' is an integer ''x'' such that ::a\,x \equiv 1 \pmod{m}. Or in other words, such that: ::\exists k \in\Z,\qquad a\, x = 1 + k\,m It can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task. ;Task: Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language, compute the modular inverse of 42 modulo 2017.
#include <iostream> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { std::cout << mul_inv(42, 2017) << std::endl; return 0; }
Monads/List monad
C++
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: #Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) #Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String #Compose the two functions with bind
#include <iostream> #include <vector> using namespace std; // std::vector can be a list monad. Use the >> operator as the bind function template <typename T> auto operator>>(const vector<T>& monad, auto f) { // Declare a vector of the same type that the function f returns vector<remove_reference_t<decltype(f(monad.front()).front())>> result; for(auto& item : monad) { // Apply the function f to each item in the monad. f will return a // new list monad containing 0 or more items. const auto r = f(item); // Concatenate the results of f with previous results result.insert(result.end(), begin(r), end(r)); } return result; } // The Pure function returns a vector containing one item, t auto Pure(auto t) { return vector{t}; } // A function to double items in the list monad auto Double(int i) { return Pure(2 * i); } // A function to increment items auto Increment(int i) { return Pure(i + 1); } // A function to convert items to a string auto NiceNumber(int i) { return Pure(to_string(i) + " is a nice number\n"); } // A function to map an item to a sequence ending at max value // for example: 497 -> {497, 498, 499, 500} auto UpperSequence = [](auto startingVal) { const int MaxValue = 500; vector<decltype(startingVal)> sequence; while(startingVal <= MaxValue) sequence.push_back(startingVal++); return sequence; }; // Print contents of a vector void PrintVector(const auto& vec) { cout << " "; for(auto value : vec) { cout << value << " "; } cout << "\n"; } // Print the Pythagorean triples void PrintTriples(const auto& vec) { cout << "Pythagorean triples:\n"; for(auto it = vec.begin(); it != vec.end();) { auto x = *it++; auto y = *it++; auto z = *it++; cout << x << ", " << y << ", " << z << "\n"; } cout << "\n"; } int main() { // Apply Increment, Double, and NiceNumber to {2, 3, 4} using the monadic bind auto listMonad = vector<int> {2, 3, 4} >> Increment >> Double >> NiceNumber; PrintVector(listMonad); // Find Pythagorean triples using the list monad. The 'x' monad list goes // from 1 to the max; the 'y' goes from the current 'x' to the max; and 'z' // goes from the current 'y' to the max. The last bind returns the triplet // if it is Pythagorean, otherwise it returns an empty list monad. auto pythagoreanTriples = UpperSequence(1) >> [](int x){return UpperSequence(x) >> [x](int y){return UpperSequence(y) >> [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};}; PrintTriples(pythagoreanTriples); }
Monads/Maybe monad
C++
Demonstrate in your programming language the following: #Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) #Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String #Compose the two functions with bind A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time. A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
#include <iostream> #include <cmath> #include <optional> #include <vector> using namespace std; // std::optional can be a maybe monad. Use the >> operator as the bind function template <typename T> auto operator>>(const optional<T>& monad, auto f) { if(!monad.has_value()) { // Return an empty maybe monad of the same type as if there // was a value return optional<remove_reference_t<decltype(*f(*monad))>>(); } return f(*monad); } // The Pure function returns a maybe monad containing the value t auto Pure(auto t) { return optional{t}; } // A safe function to invert a value auto SafeInverse(double v) { if (v == 0) { return optional<decltype(v)>(); } else { return optional(1/v); } } // A safe function to calculate the arc cosine auto SafeAcos(double v) { if(v < -1 || v > 1) { // The input is out of range, return an empty monad return optional<decltype(acos(v))>(); } else { return optional(acos(v)); } } // Print the monad template<typename T> ostream& operator<<(ostream& s, optional<T> v) { s << (v ? to_string(*v) : "nothing"); return s; } int main() { // Use bind to compose SafeInverse and SafeAcos vector<double> tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5}; cout << "x -> acos(1/x) , 1/(acos(x)\n"; for(auto v : tests) { auto maybeMonad = Pure(v); auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos; auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse; cout << v << " -> " << inverseAcos << ", " << acosInverse << "\n"; } }
Monads/Writer monad
C++
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: # Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) # Write three simple functions: root, addOne, and half # Derive Writer monad versions of each of these functions # Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
#include <cmath> #include <iostream> #include <string> using namespace std; // Use a struct as the monad struct LoggingMonad { double Value; string Log; }; // Use the >> operator as the bind function auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingMonad{result.Value, monad.Log + "\n" + result.Log}; } // Define the three simple functions auto Root = [](double x){ return sqrt(x); }; auto AddOne = [](double x){ return x + 1; }; auto Half = [](double x){ return x / 2.0; }; // Define a function to create writer monads from the simple functions auto MakeWriter = [](auto f, string message) { return [=](double x){return LoggingMonad(f(x), message);}; }; // Derive writer versions of the simple functions auto writerRoot = MakeWriter(Root, "Taking square root"); auto writerAddOne = MakeWriter(AddOne, "Adding 1"); auto writerHalf = MakeWriter(Half, "Dividing by 2"); int main() { // Compose the writers to compute the golden ratio auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf; cout << result.Log << "\nResult: " << result.Value; }
Move-to-front algorithm
C++
Given a symbol table of a ''zero-indexed'' array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. ;Encoding algorithm: for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table ;Decoding algorithm: # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table ;Example: Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z''' :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''b'''roood | 1 | 'abcdefghijklmnopqrstuvwxyz' |- | b'''r'''oood | 1 17 | 'bacdefghijklmnopqrstuvwxyz' |- | br'''o'''ood | 1 17 15 | 'rbacdefghijklmnopqstuvwxyz' |- | bro'''o'''od | 1 17 15 0 | 'orbacdefghijklmnpqstuvwxyz' |- | broo'''o'''d | 1 17 15 0 0 | 'orbacdefghijklmnpqstuvwxyz' |- | brooo'''d''' | 1 17 15 0 0 5 | 'orbacdefghijklmnpqstuvwxyz' |} Decoding the indices back to the original symbol order: :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''1''' 17 15 0 0 5 | b | 'abcdefghijklmnopqrstuvwxyz' |- | 1 '''17''' 15 0 0 5 | br | 'bacdefghijklmnopqrstuvwxyz' |- | 1 17 '''15''' 0 0 5 | bro | 'rbacdefghijklmnopqstuvwxyz' |- | 1 17 15 '''0''' 0 5 | broo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 '''0''' 5 | brooo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 0 '''5''' | broood | 'orbacdefghijklmnpqstuvwxyz' |} ;Task: :* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. :* Show the strings and their encoding here. :* Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
#include <iostream> #include <iterator> #include <sstream> #include <vector> using namespace std; class MTF { public: string encode( string str ) { fillSymbolTable(); vector<int> output; for( string::iterator it = str.begin(); it != str.end(); it++ ) { for( int i = 0; i < 26; i++ ) { if( *it == symbolTable[i] ) { output.push_back( i ); moveToFront( i ); break; } } } string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { ostringstream ss; ss << *it; r += ss.str() + " "; } return r; } string decode( string str ) { fillSymbolTable(); istringstream iss( str ); vector<int> output; copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) ); string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { r.append( 1, symbolTable[*it] ); moveToFront( *it ); } return r; } private: void moveToFront( int i ) { char t = symbolTable[i]; for( int z = i - 1; z >= 0; z-- ) symbolTable[z + 1] = symbolTable[z]; symbolTable[0] = t; } void fillSymbolTable() { for( int x = 0; x < 26; x++ ) symbolTable[x] = x + 'a'; } char symbolTable[26]; }; int main() { MTF mtf; string a, str[] = { "broood", "bananaaa", "hiphophiphop" }; for( int x = 0; x < 3; x++ ) { a = str[x]; cout << a << " -> encoded = "; a = mtf.encode( a ); cout << a << "; decoded = " << mtf.decode( a ) << endl; } return 0; }
Multi-dimensional array
C++
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: # State the number and extent of each index to the array. # Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. # Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. ;Task: * State if the language supports multi-dimensional arrays in its syntax and usual implementation. * State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. * Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. :* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). * State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. * If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
#include <iostream> #include <vector> // convienince for printing the contents of a collection template<typename T> std::ostream& operator<<(std::ostream& out, const std::vector<T>& c) { auto it = c.cbegin(); auto end = c.cend(); out << '['; if (it != end) { out << *it; it = std::next(it); } while (it != end) { out << ", " << *it; it = std::next(it); } return out << ']'; } void fourDim() { using namespace std; // create a 4d jagged array, with bounds checking etc... vector<vector<vector<vector<int>>>> arr; int cnt = 0; arr.push_back(vector<vector<vector<int>>>{}); arr[0].push_back(vector<vector<int>>{}); arr[0][0].push_back(vector<int>{}); arr[0][0][0].push_back(cnt++); arr[0][0][0].push_back(cnt++); arr[0][0][0].push_back(cnt++); arr[0][0][0].push_back(cnt++); arr[0].push_back(vector<vector<int>>{}); arr[0][1].push_back(vector<int>{}); arr[0][1][0].push_back(cnt++); arr[0][1][0].push_back(cnt++); arr[0][1][0].push_back(cnt++); arr[0][1][0].push_back(cnt++); arr[0][1].push_back(vector<int>{}); arr[0][1][1].push_back(cnt++); arr[0][1][1].push_back(cnt++); arr[0][1][1].push_back(cnt++); arr[0][1][1].push_back(cnt++); arr.push_back(vector<vector<vector<int>>>{}); arr[1].push_back(vector<vector<int>>{}); arr[1][0].push_back(vector<int>{}); arr[1][0][0].push_back(cnt++); arr[1][0][0].push_back(cnt++); arr[1][0][0].push_back(cnt++); arr[1][0][0].push_back(cnt++); cout << arr << '\n'; } int main() { /* C++ does not have native support for multi-dimensional arrays, * but classes could be written to make things easier to work with. * There are standard library classes which can be used for single dimension arrays. * Also raw access is supported through pointers as in C. */ fourDim(); return 0; }
Multifactorial
C++
The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1). Multifactorials generalize factorials as follows: : n! = n(n-1)(n-2)...(2)(1) : n!! = n(n-2)(n-4)... : n!! ! = n(n-3)(n-6)... : n!! !! = n(n-4)(n-8)... : n!! !! ! = n(n-5)(n-10)... In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: # Write a function that given n and the degree, calculates the multifactorial. # Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. '''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
#include <algorithm> #include <iostream> #include <iterator> /*Generate multifactorials to 9 Nigel_Galloway November 14th., 2012. */ int main(void) { for (int g = 1; g < 10; g++) { int v[11], n=0; generate_n(std::ostream_iterator<int>(std::cout, " "), 10, [&]{n++; return v[n]=(g<n)? v[n-g]*n : n;}); std::cout << std::endl; } return 0; }
Multiple distinct objects
C++
Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: [[Closures/Value capture]]
#include <vector> #include <tr1/memory> using namespace std; using namespace std::tr1; typedef shared_ptr<T> TPtr_t; // the following is NOT correct: std::vector<TPtr_t > bvec_WRONG(n, p); // create n copies of p, which all point to the same opject p points to. // nor is this: std::vector<TPtr_t> bvec_ALSO_WRONG(n, TPtr_t(new T(*p)) ); // create n pointers to a single copy of *p // the correct solution std::vector<TPtr_t > bvec(n); for (int i = 0; i < n; ++i) bvec[i] = TPtr_t(new T(*p); //or any other call to T's constructor // another correct solution // this solution avoids uninitialized pointers at any point std::vector<TPtr_t> bvec2; for (int i = 0; i < n; ++i) bvec2.push_back(TPtr_t(new T(*p));
Multisplit
C++
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=". For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. '''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
#include <iostream> #include <boost/tokenizer.hpp> #include <string> int main( ) { std::string str( "a!===b=!=c" ) , output ; typedef boost::tokenizer<boost::char_separator<char> > tokenizer ; boost::char_separator<char> separator ( "==" , "!=" ) , sep ( "!" ) ; tokenizer mytok( str , separator ) ; tokenizer::iterator tok_iter = mytok.begin( ) ; for ( ; tok_iter != mytok.end( ) ; ++tok_iter ) output.append( *tok_iter ) ; tokenizer nexttok ( output , sep ) ; for ( tok_iter = nexttok.begin( ) ; tok_iter != nexttok.end( ) ; ++tok_iter ) std::cout << *tok_iter << " " ; std::cout << '\n' ; return 0 ; }
Munchausen numbers
C++
A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''. ('''Munchausen''' is also spelled: '''Munchhausen'''.) For instance: 3435 = 33 + 44 + 33 + 55 ;Task Find all Munchausen numbers between '''1''' and '''5000'''. ;Also see: :* The OEIS entry: A046253 :* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
#include <math.h> #include <iostream> unsigned pwr[10]; unsigned munch( unsigned i ) { unsigned sum = 0; while( i ) { sum += pwr[(i % 10)]; i /= 10; } return sum; } int main( int argc, char* argv[] ) { for( int i = 0; i < 10; i++ ) pwr[i] = (unsigned)pow( (float)i, (float)i ); std::cout << "Munchausen Numbers\n==================\n"; for( unsigned i = 1; i < 5000; i++ ) if( i == munch( i ) ) std::cout << i << "\n"; return 0; }
Musical scale
C++
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfege. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
N-queens problem
C++
right Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''. For the number of solutions for small values of '''N''', see OEIS: A000170. ;Related tasks: * [[A* search algorithm]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[Peaceful chess queen armies]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
// Much shorter than the version below; // uses C++11 threads to parallelize the computation; also uses backtracking // Outputs all solutions for any table size #include <vector> #include <iostream> #include <iomanip> #include <thread> #include <future> // Print table. 'pos' is a vector of positions – the index in pos is the row, // and the number at that index is the column where the queen is placed. static void print(const std::vector<int> &pos) { // print table header for (int i = 0; i < pos.size(); i++) { std::cout << std::setw(3) << char('a' + i); } std::cout << '\n'; for (int row = 0; row < pos.size(); row++) { int col = pos[row]; std::cout << row + 1 << std::setw(3 * col + 3) << " # "; std::cout << '\n'; } std::cout << "\n\n"; } static bool threatens(int row_a, int col_a, int row_b, int col_b) { return row_a == row_b // same row or col_a == col_b // same column or std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal } // the i-th queen is in the i-th row // we only check rows up to end_idx // so that the same function can be used for backtracking and checking the final solution static bool good(const std::vector<int> &pos, int end_idx) { for (int row_a = 0; row_a < end_idx; row_a++) { for (int row_b = row_a + 1; row_b < end_idx; row_b++) { int col_a = pos[row_a]; int col_b = pos[row_b]; if (threatens(row_a, col_a, row_b, col_b)) { return false; } } } return true; } static std::mutex print_count_mutex; // mutex protecting 'n_sols' static int n_sols = 0; // number of solutions // recursive DFS backtracking solver static void n_queens(std::vector<int> &pos, int index) { // if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return if (index >= pos.size()) { if (good(pos, index)) { std::lock_guard<std::mutex> lock(print_count_mutex); print(pos); n_sols++; } return; } // backtracking step if (not good(pos, index)) { return; } // optimization: the first level of the search tree is parallelized if (index == 0) { std::vector<std::future<void>> fts; for (int col = 0; col < pos.size(); col++) { pos[index] = col; auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); }); fts.push_back(std::move(ft)); } for (const auto &ft : fts) { ft.wait(); } } else { // deeper levels are not for (int col = 0; col < pos.size(); col++) { pos[index] = col; n_queens(pos, index + 1); } } } int main() { std::vector<int> start(12); // 12: table size n_queens(start, 0); std::cout << n_sols << " solutions found.\n"; return 0; }
Narcissistic decimal number
C++
A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. They are also known as '''Plus Perfect''' numbers. ;An example: ::::* if n is '''153''' ::::* then m, (the number of decimal digits) is '''3''' ::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' ::::* and so '''153''' is a narcissistic decimal number ;Task: Generate and show here the first '''25''' narcissistic decimal numbers. Note: 0^1 = 0, the first in the series. ;See also: * the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers. * MathWorld entry: Narcissistic Number. * Wikipedia entry: Narcissistic number.
#include <iostream> #include <vector> using namespace std; typedef unsigned int uint; class NarcissisticDecs { public: void makeList( int mx ) { uint st = 0, tl; int pwr = 0, len; while( narc.size() < mx ) { len = getDigs( st ); if( pwr != len ) { pwr = len; fillPower( pwr ); } tl = 0; for( int i = 1; i < 10; i++ ) tl += static_cast<uint>( powr[i] * digs[i] ); if( tl == st ) narc.push_back( st ); st++; } } void display() { for( vector<uint>::iterator i = narc.begin(); i != narc.end(); i++ ) cout << *i << " "; cout << "\n\n"; } private: int getDigs( uint st ) { memset( digs, 0, 10 * sizeof( int ) ); int r = 0; while( st ) { digs[st % 10]++; st /= 10; r++; } return r; } void fillPower( int z ) { for( int i = 1; i < 10; i++ ) powr[i] = pow( static_cast<float>( i ), z ); } vector<uint> narc; uint powr[10]; int digs[10]; }; int main( int argc, char* argv[] ) { NarcissisticDecs n; n.makeList( 25 ); n.display(); return system( "pause" ); }
Nautical bell
C++
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. ;Related task: * [[Sleep]]
#include <iostream> #include <string> #include <windows.h> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight"; _inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL ); } private: static DWORD WINAPI bell( LPVOID p ) { DWORD wait = _inst->waitTime(); while( true ) { Sleep( wait ); _inst->playBell(); wait = _inst->waitTime(); } return 0; } DWORD waitTime() { GetLocalTime( &st ); int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute; return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) ); } void playBell() { GetLocalTime( &st ); int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b; int w = ( 60 * st.wHour + st.wMinute ); if( w < 1 ) w = 5; else w = ( w - 1 ) / 240; char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute ); cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell"; if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl; for( int x = 0, c = 1; x < b; x++, c++ ) { cout << "\7"; Sleep( 500 ); if( !( c % 2 ) ) Sleep( 300 ); } } SYSTEMTIME st; string watch[7], count[8]; static bells* _inst; }; //-------------------------------------------------------------------------------------------------- bells* bells::_inst = 0; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { bells b; b.start(); while( 1 ); // <- runs forever! return 0; } //--------------------------------------------------------------------------------------------------
Negative base numbers
C++ from C#
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia ;Task: *Encode the decimal number 10 as negabinary (expect 11110) *Encode the decimal number 146 as negaternary (expect 21102) *Encode the decimal number 15 as negadecimal (expect 195) *In each of the above cases, convert the encoded number back to decimal. ;extra credit: * supply an integer, that when encoded to base -62 (or something "higher"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.
#include <iomanip> #include <iostream> #include <tuple> #include <vector> const std::string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; std::string encodeNegativeBase(int64_t n, int b) { if (b < -62 || b > -1) { throw std::runtime_error("Argument out of range: b"); } if (n == 0) { return "0"; } std::string output; int64_t nn = n; while (nn != 0) { int rem = nn % b; nn /= b; if (rem < 0) { nn++; rem -= b; } output += DIGITS[rem]; } std::reverse(output.begin(), output.end()); return output; } int64_t decodeNegativeBase(const std::string& ns, int b) { if (b < -62 || b > -1) { throw std::runtime_error("Argument out of range: b"); } if (ns == "0") { return 0; } int64_t total = 0; int64_t bb = 1; for (auto it = ns.crbegin(); it != ns.crend(); it = std::next(it)) { auto ptr = std::find(DIGITS.cbegin(), DIGITS.cend(), *it); if (ptr != DIGITS.cend()) { auto idx = ptr - DIGITS.cbegin(); total += idx * bb; } bb *= b; } return total; } int main() { using namespace std; vector<pair<int64_t, int>> nbl({ make_pair(10, -2), make_pair(146, -3), make_pair(15, -10), make_pair(142961, -62) }); for (auto& p : nbl) { string ns = encodeNegativeBase(p.first, p.second); cout << setw(12) << p.first << " encoded in base " << setw(3) << p.second << " = " << ns.c_str() << endl; int64_t n = decodeNegativeBase(ns, p.second); cout << setw(12) << ns.c_str() << " decoded in base " << setw(3) << p.second << " = " << n << endl; cout << endl; } return 0; }
Nested function
C++11
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. ;Task: Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. ;References: :* Nested function
#include <iostream> #include <string> #include <vector> std::vector<std::string> makeList(std::string separator) { auto counter = 0; auto makeItem = [&](std::string item) { return std::to_string(++counter) + separator + item; }; return {makeItem("first"), makeItem("second"), makeItem("third")}; } int main() { for (auto item : makeList(". ")) std::cout << item << "\n"; }
Nested templated data
C++
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. ;Task Detail: Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]] p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. ;Optional Extended tasks: 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. ''Show output on this page.''
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; // print a single payload template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) cout << ", "; // add a comma between elements } // print a tuple of playloads template<typename P, typename... Ts> void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true) { std::apply // recursively call PrintPayloads on each element of the tuple ( [&payloads, isLast](Ts const&... tupleArgs) { size_t n{0}; cout << "["; (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...); cout << "]"; cout << (isLast ? "\n" : ",\n"); }, nestedTuple ); } // find the unique index of a single index (helper for the function below) void FindUniqueIndexes(set<int> &indexes, int index) { indexes.insert(index); } // find the unique indexes in the tuples template<typename... Ts> void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple) { std::apply ( [&indexes](Ts const&... tupleArgs) { (FindUniqueIndexes(indexes, tupleArgs),...); }, nestedTuple ); } // print the payloads that were not used template<typename P> void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads) { for(size_t i = 0; i < size(payloads); i++) { if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n"; } } int main() { // define the playloads, they can be in most containers vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"}; const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; // as a C array // define the indexes as a nested tuple auto tpl = make_tuple(make_tuple( make_tuple(1, 2), make_tuple(3, 4, 1), 5)); cout << "Mapping indexes to payloads:\n"; PrintPayloads(payloads, tpl); cout << "\nFinding unused payloads:\n"; set<int> usedIndexes; FindUniqueIndexes(usedIndexes, tpl); PrintUnusedPayloads(usedIndexes, payloads); cout << "\nMapping to some out of range payloads:\n"; PrintPayloads(shortPayloads, tpl); return 0; }
Nim game
C++ from Go
Nim is a simple game where the second player-if they know the trick-will always win. The game has only 3 rules: ::* start with '''12''' tokens ::* each player takes '''1, 2, or 3''' tokens in turn ::* the player who takes the last token wins. To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. ;Task: Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
#include <iostream> #include <limits> using namespace std; void showTokens(int tokens) { cout << "Tokens remaining " << tokens << endl << endl; } int main() { int tokens = 12; while (true) { showTokens(tokens); cout << " How many tokens 1, 2 or 3? "; int t; cin >> t; if (cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl << "Invalid input, try again." << endl << endl; } else if (t < 1 || t > 3) { cout << endl << "Must be a number between 1 and 3, try again." << endl << endl; } else { int ct = 4 - t; string s = (ct > 1) ? "s" : ""; cout << " Computer takes " << ct << " token" << s << endl << endl; tokens -= 4; } if (tokens == 0) { showTokens(0); cout << " Computer wins!" << endl; return 0; } } }
Nonoblock
C++
Nonogram puzzle. ;Given: * The number of cells in a row. * The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. ;Task: * show all possible positions. * show the number of positions of the blocks for the following cases within the row. * show all output on this page. * use a "neat" diagram of the block positions. ;Enumerate the following configurations: # '''5''' cells and '''[2, 1]''' blocks # '''5''' cells and '''[]''' blocks (no blocks) # '''10''' cells and '''[8]''' blocks # '''15''' cells and '''[2, 3, 2, 3]''' blocks # '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible) ;Example: Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# ;An algorithm: * Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). * The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. * for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block. (This is the algorithm used in the [[Nonoblock#Python]] solution). ;Reference: * The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { counter = 0; std::cout << " Puzzle: " << ( *i ).first << " cells and blocks [ "; for( std::vector<int>::iterator it = ( *i ).second.begin(); it != ( *i ).second.end(); it++ ) std::cout << *it << " "; std::cout << "] "; int s = std::accumulate( ( *i ).second.begin(), ( *i ).second.end(), 0 ) + ( ( *i ).second.size() > 0 ? ( *i ).second.size() - 1 : 0 ); if( ( *i ).first - s < 0 ) { std::cout << "has no solution!\n\n\n"; continue; } std::cout << "\n Possible configurations:\n\n"; std::string b( ( *i ).first, '-' ); solve( *i, b, 0 ); std::cout << "\n\n"; } } private: void solve( puzzle p, std::string n, int start ) { if( p.second.size() < 1 ) { output( n ); return; } std::string temp_string; int offset, this_block_size = p.second[0]; int space_need_for_others = std::accumulate( p.second.begin() + 1, p.second.end(), 0 ); space_need_for_others += p.second.size() - 1; int space_for_curr_block = p.first - space_need_for_others - std::accumulate( p.second.begin(), p.second.begin(), 0 ); std::vector<int> v1( p.second.size() - 1 ); std::copy( p.second.begin() + 1, p.second.end(), v1.begin() ); puzzle p1 = std::make_pair( space_need_for_others, v1 ); for( int a = 0; a < space_for_curr_block; a++ ) { temp_string = n; if( start + this_block_size > n.length() ) return; for( offset = start; offset < start + this_block_size; offset++ ) temp_string.at( offset ) = 'o'; if( p1.first ) solve( p1, temp_string, offset + 1 ); else output( temp_string ); start++; } } void output( std::string s ) { char b = 65 - ( s.at( 0 ) == '-' ? 1 : 0 ); bool f = false; std::cout << std::setw( 3 ) << ++counter << "\t|"; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { b += ( *i ) == 'o' && f ? 1 : 0; std::cout << ( ( *i ) == 'o' ? b : '_' ) << "|"; f = ( *i ) == '-' ? true : false; } std::cout << "\n"; } unsigned counter; }; int main( int argc, char* argv[] ) { std::vector<puzzle> problems; std::vector<int> blocks; blocks.push_back( 2 ); blocks.push_back( 1 ); problems.push_back( std::make_pair( 5, blocks ) ); blocks.clear(); problems.push_back( std::make_pair( 5, blocks ) ); blocks.push_back( 8 ); problems.push_back( std::make_pair( 10, blocks ) ); blocks.clear(); blocks.push_back( 2 ); blocks.push_back( 3 ); problems.push_back( std::make_pair( 5, blocks ) ); blocks.push_back( 2 ); blocks.push_back( 3 ); problems.push_back( std::make_pair( 15, blocks ) ); nonoblock nn; nn.solve( problems ); return 0; }
Nonogram solver
C++
nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. ;Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" ;Task For this task, try to solve the 4 problems below, read from a "nonogram_problems.txt" file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM '''Extra credit''': generate nonograms with unique solutions, of desired height and width. This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples). ; Related tasks * [[Nonoblock]]. ;See also * Arc Consistency Algorithm * http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) * http://twanvl.nl/blog/haskell/Nonograms (Haskell) * http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
// A class to solve Nonogram (Hadje) Puzzles // Nigel Galloway - January 23rd., 2017 template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; // end of N std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};
Numbers which are the cube roots of the product of their proper divisors
C++
Example Consider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title. ;Task Compute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors. Also show the '''500th''' and '''5,000th''' such numbers. ;Stretch Compute and show the '''50,000th''' such number. ;Reference * OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors. ;Note OEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; 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) total *= 2; return total; } int main() { std::cout.imbue(std::locale("")); std::cout << "First 50 numbers which are the cube roots of the products of " "their proper divisors:\n"; for (unsigned int n = 1, count = 0; count < 50000; ++n) { if (n == 1 || divisor_count(n) == 8) { ++count; if (count <= 50) std::cout << std::setw(3) << n << (count % 10 == 0 ? '\n' : ' '); else if (count == 500 || count == 5000 || count == 50000) std::cout << std::setw(6) << count << "th: " << n << '\n'; } } }
Numbers with equal rises and falls
C++
When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right). ;Definition: Given the decimal digits of the number are written as a series d: :* A ''rise'' is an index i such that d(i) < d(i+1) :* A ''fall'' is an index i such that d(i) > d(i+1) ;Examples: :* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence. :* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence. ;Task: :* Print the first '''200''' numbers in the sequence :* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002''' ;See also: * OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls". ;Related tasks: * Esthetic numbers
#include <iomanip> #include <iostream> bool equal_rises_and_falls(int n) { int total = 0; for (int previous_digit = -1; n > 0; n /= 10) { int digit = n % 10; if (previous_digit > digit) ++total; else if (previous_digit >= 0 && previous_digit < digit) --total; previous_digit = digit; } return total == 0; } int main() { const int limit1 = 200; const int limit2 = 10000000; int n = 0; std::cout << "The first " << limit1 << " numbers in the sequence are:\n"; for (int count = 0; count < limit2; ) { if (equal_rises_and_falls(++n)) { ++count; if (count <= limit1) std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' '); } } std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n"; }
Numeric error propagation
C++
If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; then if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, then sf can be calculated as follows: :;Addition/Subtraction :* If f = a +- c, or f = c +- a then '''sf = sa''' :* If f = a +- b then '''sf2 = sa2 + sb2''' :;Multiplication/Division :* If f = ca or f = ac then '''sf = |csa|''' :* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)''' :;Exponentiation :* If f = ac then '''sf = |fc(sa / a)|''' Caution: ::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue. ;Task details: # Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. # Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2 # Print and display both '''d''' and its error. ;References: * A Guide to Error Propagation B. Keeney, 2005. * Propagation of uncertainty Wikipedia. ;Related task: * [[Quaternion type]]
#pragma once #include <cmath> #include <string> #include <sstream> #include <iomanip> class Approx { public: Approx(double _v, double _s = 0.0) : v(_v), s(_s) {} operator std::string() const { std::ostringstream os(""); os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends; return os.str(); } Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); } Approx operator +(double d) const { return Approx(v + d, s); } Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); } Approx operator -(double d) const { return Approx(v - d, s); } Approx operator *(const Approx& a) const { const double t = v * a.v; return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); } Approx operator /(const Approx& a) const { const double t = v / a.v; return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); } Approx pow(double d) const { const double t = ::pow(v, d); return Approx(t, fabs(t * d * s / v)); } private: double v, s; };
Old Russian measure of length
C++
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''. ;Also see: :* Old Russian measure of length
#include <iostream> #include <iomanip> //------------------------------------------------------------------------------------------- using namespace std; //------------------------------------------------------------------------------------------- class ormConverter { public: ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ), MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {} void convert( char c, float l ) { system( "cls" ); cout << endl << l; switch( c ) { case 'A': cout << " Arshin to:"; l *= AR; break; case 'C': cout << " Centimeter to:"; l *= CE; break; case 'D': cout << " Diuym to:"; l *= DI; break; case 'F': cout << " Fut to:"; l *= FU; break; case 'K': cout << " Kilometer to:"; l *= KI; break; case 'L': cout << " Liniya to:"; l *= LI; break; case 'M': cout << " Meter to:"; l *= ME; break; case 'I': cout << " Milia to:"; l *= MI; break; case 'P': cout << " Piad to:"; l *= PI; break; case 'S': cout << " Sazhen to:"; l *= SA; break; case 'T': cout << " Tochka to:"; l *= TO; break; case 'V': cout << " Vershok to:"; l *= VE; break; case 'E': cout << " Versta to:"; l *= VR; } float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME, mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR; cout << left << endl << "=================" << endl << setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl << setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl << setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl << setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl << setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl << setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl << setw( 12 ) << "Versta:" << vr << endl << endl << endl; } private: const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR; }; //------------------------------------------------------------------------------------------- int _tmain(int argc, _TCHAR* argv[]) { ormConverter c; char s; float l; while( true ) { cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n"; cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0; cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0; c.convert( s, l ); system( "pause" ); system( "cls" ); } return 0; } //-------------------------------------------------------------------------------------------
Old lady swallowed a fly
C++ from C#
Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
#include <iostream> const char *CREATURES[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" }; const char *COMMENTS[] = { "I don't know why she swallowed that fly.\nPerhaps she'll die\n", "That wiggled and jiggled and tickled inside her", "How absurd, to swallow a bird", "Imagine that. She swallowed a cat", "What a hog to swallow a dog", "She just opened her throat and swallowed that goat", "I don't know how she swallowed that cow", "She's dead of course" }; int main() { auto max = sizeof(CREATURES) / sizeof(char*); for (size_t i = 0; i < max; ++i) { std::cout << "There was an old lady who swallowed a " << CREATURES[i] << '\n'; std::cout << COMMENTS[i] << '\n'; for (int j = i; j > 0 && i < max - 1; --j) { std::cout << "She swallowed the " << CREATURES[j] << " to catch the " << CREATURES[j - 1] << '\n'; if (j == 1) std::cout << COMMENTS[j - 1] << '\n'; } } return 0; }
One of n lines in a file
C++11
A method of choosing a line randomly from a file: ::* Without reading the file more than once ::* When substantial parts of the file cannot be held in memory ::* Without knowing how many lines are in the file Is to: ::* keep the first line of the file as a possible choice, then ::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. ::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ::* ... ::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N ::* Return the computed possible choice when no further lines exist in the file. ;Task: # Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. # Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times. # Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#include <random> #include <iostream> #include <iterator> #include <algorithm> using namespace std; mt19937 engine; //mersenne twister unsigned int one_of_n(unsigned int n) { unsigned int choice; for(unsigned int i = 0; i < n; ++i) { uniform_int_distribution<unsigned int> distribution(0, i); if(!distribution(engine)) choice = i; } return choice; } int main() { engine = mt19937(random_device()()); //seed random generator from system unsigned int results[10] = {0}; for(unsigned int i = 0; i < 1000000; ++i) results[one_of_n(10)]++; ostream_iterator<unsigned int> out_it(cout, " "); copy(results, results+10, out_it); cout << '\n'; }
Operator precedence
C++
Operators in C and C++}} ;Task: Provide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
The following is a table that lists the [[wp:order of operations|precedence]] and [[wp:operator associativity|associativity]] of all the operators in the [[wp:C (programming language)|C]] and [[wp:C++|C++]] languages. An operator's precedence is unaffected by overloading. {| class="wikitable" |- ! style="text-align: left" | Precedence ! style="text-align: left" | Operator ! style="text-align: left" | Description ! style="text-align: left" | Associativity |- ! 1 <small>highest</small> | <code>::</code> | Scope resolution (C++ only) | style="vertical-align: top" rowspan="12" | Left-to-right |- ! rowspan=11| 2 | style="border-bottom-style: none" | <code>++</code> | style="border-bottom-style: none" | Suffix increment |- | style="border-bottom-style: none; border-top-style: none" | <code>--</code> | style="border-bottom-style: none; border-top-style: none" | Suffix decrement |- | style="border-bottom-style: none; border-top-style: none" | <code>()</code> | style="border-bottom-style: none; border-top-style: none" | Function call |- | style="border-bottom-style: none; border-top-style: none" | <code>[]</code> | style="border-bottom-style: none; border-top-style: none" | Array subscripting |- | style="border-bottom-style: none; border-top-style: none" | <code>.</code> | style="border-bottom-style: none; border-top-style: none" | Element selection by reference |- | style="border-bottom-style: none; border-top-style: none" | <code>-&gt;</code> | style="border-bottom-style: none; border-top-style: none" | Element selection through pointer |- | style="border-bottom-style: none; border-top-style: none" | <code>typeid()</code> | style="border-bottom-style: none; border-top-style: none" | [[wp:Run-time type information|Run-time type information]] (C++ only) (see [[wp:typeid|typeid]]) |- | style="border-bottom-style: none; border-top-style: none" | <code>const_cast</code> | style="border-bottom-style: none; border-top-style: none" | Type cast (C++ only) (see [[wp:const cast|const cast]]) |- | style="border-bottom-style: none; border-top-style: none" | <code>dynamic_cast</code> | style="border-bottom-style: none; border-top-style: none" | Type cast (C++ only) (see [[wp:dynamic_cast|dynamic cast]]) |- | style="border-bottom-style: none; border-top-style: none" | <code>reinterpret_cast</code> | style="border-bottom-style: none; border-top-style: none" | Type cast (C++ only) (see [[wp:reinterpret cast|reinterpret cast]]) |- | style="border-top-style: none" | <code>static_cast</code> | style="border-top-style: none" | Type cast (C++ only) (see [[wp:static cast|static cast]]) |- ! rowspan=12| 3 | style="border-bottom-style: none" | <code>++</code> | style="border-bottom-style: none" | Prefix increment | style="vertical-align: top" rowspan="12" | Right-to-left |- | style="border-bottom-style: none; border-top-style: none" | <code>--</code> | style="border-bottom-style: none; border-top-style: none" | Prefix decrement |- | style="border-bottom-style: none; border-top-style: none" | <code>+</code> | style="border-bottom-style: none; border-top-style: none" | Unary plus |- | style="border-bottom-style: none; border-top-style: none" | <code>-</code> | style="border-bottom-style: none; border-top-style: none" | Unary minus |- | style="border-bottom-style: none; border-top-style: none" | <code>!</code> | style="border-bottom-style: none; border-top-style: none" | Logical NOT |- | style="border-bottom-style: none; border-top-style: none" | <code>~</code> | style="border-bottom-style: none; border-top-style: none" | Bitwise NOT |- | style="border-bottom-style: none; border-top-style: none" | <code>(''type'')</code> | style="border-bottom-style: none; border-top-style: none" | Type cast |- | style="border-bottom-style: none; border-top-style: none" | <code>*</code> | style="border-bottom-style: none; border-top-style: none" | Indirection (dereference) |- | style="border-bottom-style: none; border-top-style: none" | <code>&</code> | style="border-bottom-style: none; border-top-style: none" | Address-of |- | style="border-bottom-style: none; border-top-style: none" | <code>sizeof</code> | style="border-bottom-style: none; border-top-style: none" | [[wp:sizeof|Size-of]] |- | style="border-bottom-style: none; border-top-style: none" | <code>new</code>, <code>new[]</code> | style="border-bottom-style: none; border-top-style: none" | Dynamic memory allocation (C++ only) |- | style="border-top-style: none" | <code>delete</code>, <code>delete[]</code> | style="border-top-style: none" | Dynamic memory deallocation (C++ only) |- ! rowspan=2| 4 | style="border-bottom-style: none" | <code>.*</code> | style="border-bottom-style: none" | Pointer to member (C++ only) | style="vertical-align: top" rowspan="20" | Left-to-right |- | style="border-bottom-style: none; border-top-style: none" | <code>->*</code> | style="border-bottom-style: none; border-top-style: none" | Pointer to member (C++ only) |- ! rowspan=3| 5 | style="border-bottom-style: none" | <code>*</code> | style="border-bottom-style: none" | Multiplication |- | style="border-bottom-style: none; border-top-style: none" | <code>/</code> | style="border-bottom-style: none; border-top-style: none" | Division |- | style="border-bottom-style: none; border-top-style: none" | <code>%</code> | style="border-bottom-style: none; border-top-style: none" | [[wp:Modulo operation|Modulo]] (remainder) |- ! rowspan=2| 6 | style="border-bottom-style: none" | <code>+</code> | style="border-bottom-style: none" | Addition |- | style="border-bottom-style: none; border-top-style: none" | <code>-</code> | style="border-bottom-style: none; border-top-style: none" | Subtraction |- ! rowspan=2| 7 | style="border-bottom-style: none" | <code>&lt;&lt;</code> | style="border-bottom-style: none" | [[wp:Bitwise operation|Bitwise]] left shift |- | style="border-bottom-style: none; border-top-style: none" | <code>&gt;&gt;</code> | style="border-bottom-style: none; border-top-style: none" | [[wp:Bitwise operation|Bitwise]] right shift |- ! rowspan=4| 8 | style="border-bottom-style: none" | <code>&lt;</code> | style="border-bottom-style: none" | Less than |- | style="border-bottom-style: none; border-top-style: none" | <code>&lt;=</code> | style="border-bottom-style: none; border-top-style: none" | Less than or equal to |- | style="border-bottom-style: none; border-top-style: none" | <code>&gt;</code> | style="border-bottom-style: none; border-top-style: none" | Greater than |- | style="border-bottom-style: none; border-top-style: none" | <code>&gt;=</code> | style="border-bottom-style: none; border-top-style: none" | Greater than or equal to |- ! rowspan=2| 9 | style="border-bottom-style: none" | <code>==</code> | style="border-bottom-style: none" | Equal to |- | style="border-bottom-style: none; border-top-style: none" | <code>!=</code> | style="border-bottom-style: none; border-top-style: none" | Not equal to |- ! 10 | <code>&amp;</code> | Bitwise AND |- ! 11 | <code>^</code> | Bitwise XOR (exclusive or) |- ! 12 | <code><nowiki>|</nowiki></code> | Bitwise OR (inclusive or) |- ! 13 | <code>&amp;&amp;</code> | Logical AND |- ! 14 | <code><nowiki>||</nowiki></code> | Logical OR |- ! 15 | <code>?:</code> | [[wp:Ternary operator|Ternary]] conditional (see [[wp:?:|?:]]) | style="vertical-align: top" rowspan="12" | Right-to-left |- ! rowspan=11| 16 | style="border-bottom-style: none" | <code>=</code> | style="border-bottom-style: none" | Direct assignment |- | style="border-bottom-style: none; border-top-style: none" | <code>+=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by sum |- | style="border-bottom-style: none; border-top-style: none" | <code>-=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by difference |- | style="border-bottom-style: none; border-top-style: none" | <code>*=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by product |- | style="border-bottom-style: none; border-top-style: none" | <code>/=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by quotient |- | style="border-bottom-style: none; border-top-style: none" | <code>%=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by remainder |- | style="border-bottom-style: none; border-top-style: none" | <code>&lt;&lt;=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise left shift |- | style="border-bottom-style: none; border-top-style: none" | <code>&gt;&gt;=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise right shift |- | style="border-bottom-style: none; border-top-style: none" | <code>&amp;=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise AND |- | style="border-bottom-style: none; border-top-style: none" | <code>^=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise XOR |- | style="border-bottom-style: none; border-top-style: none" | <code><nowiki>|</nowiki>=</code> | style="border-bottom-style: none; border-top-style: none" | Assignment by bitwise OR |- ! 17 | <code>throw</code> | Throw operator (exceptions throwing, C++ only) | |- ! 18 | <code>,</code> | [[wp:Comma operator|Comma]] | Left-to-right |} For quick reference, see also [http://cpp.operator-precedence.com this] equivalent, color-coded table.
Padovan sequence
C++
The Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. ::{| class="wikitable" ! Comment !! Padovan !! Fibonacci |- | || || |- | Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci |- | || || |- | Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1 |- | Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2) |- | || || |- | First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34 |- | || || |- | Ratio of successive terms... || Plastic ratio, p || Golden ratio, g |- | || 1.324717957244746025960908854... || 1.6180339887498948482... |- | Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2 |- | Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1 |- | || || |- | Spirally tiling the plane using. || Equilateral triangles || Squares |- | || || |- | Constants for ... || s= 1.0453567932525329623 || a=5**0.5 |- | ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5) |- | || || |- | L-System Variables. || A,B,C || A,B |- | L-System Start/Axiom. || A || A |- | L-System Rules. || A->B,B->C,C->AB || A->B,B->AB |} ;Task: * Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation. * Write a function/method/subroutine to compute successive members of the Padovan series using the floor function. * Show the first twenty terms of the sequence. * Confirm that the recurrence and floor based functions give the same results for 64 terms, * Write a function/method/... using the L-system to generate successive strings. * Show the first 10 strings produced from the L-system * Confirm that the length of the first 32 strings produced is the Padovan sequence. Show output here, on this page. ;Ref: * The Plastic Ratio - Numberphile video.
#include <iostream> #include <map> #include <cmath> // Generate the Padovan sequence using the recurrence // relationship. int pRec(int n) { static std::map<int,int> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n <= 2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); return memo[n]; } // Calculate the N'th Padovan sequence using the // floor function. int pFloor(int n) { long const double p = 1.324717957244746025960908854; long const double s = 1.0453567932525329623; return std::pow(p, n-1)/s + 0.5; } // Return the N'th L-system string std::string& lSystem(int n) { static std::map<int,std::string> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n == 0) memo[n] = "A"; else { memo[n] = ""; for (char ch : memo[n-1]) { switch(ch) { case 'A': memo[n].push_back('B'); break; case 'B': memo[n].push_back('C'); break; case 'C': memo[n].append("AB"); break; } } } return memo[n]; } // Compare two functions up to p_N using pFn = int(*)(int); void compare(pFn f1, pFn f2, const char* descr, int stop) { std::cout << "The " << descr << " functions "; int i; for (i=0; i<stop; i++) { int n1 = f1(i); int n2 = f2(i); if (n1 != n2) { std::cout << "do not match at " << i << ": " << n1 << " != " << n2 << ".\n"; break; } } if (i == stop) { std::cout << "match from P_0 to P_" << stop << ".\n"; } } int main() { /* Print P_0 to P_19 */ std::cout << "P_0 .. P_19: "; for (int i=0; i<20; i++) std::cout << pRec(i) << " "; std::cout << "\n"; /* Check that floor and recurrence match up to P_64 */ compare(pFloor, pRec, "floor- and recurrence-based", 64); /* Show first 10 L-system strings */ std::cout << "\nThe first 10 L-system strings are:\n"; for (int i=0; i<10; i++) std::cout << lSystem(i) << "\n"; std::cout << "\n"; /* Check lengths of strings against pFloor up to P_31 */ compare(pFloor, [](int n){return (int)lSystem(n).length();}, "floor- and L-system-based", 32); return 0; }
Palindromic gapful numbers
C++
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''1037''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''1037'''. A palindromic number is (for this task, a positive integer expressed in base ten), when the number is reversed, is the same as the original number. ;Task: :* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with: :::* the digit '''1''' :::* the digit '''2''' :::* the digit '''3''' :::* the digit '''4''' :::* the digit '''5''' :::* the digit '''6''' :::* the digit '''7''' :::* the digit '''8''' :::* the digit '''9''' :* Show (nine sets, like above) of palindromic gapful numbers: :::* the last '''15''' palindromic gapful numbers (out of '''100''') :::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional} For other ways of expressing the (above) requirements, see the ''discussion'' page. ;Note: All palindromic gapful numbers are divisible by eleven. ;Related tasks: :* palindrome detection. :* gapful numbers. ;Also see: :* The OEIS entry: A108343 gapful numbers.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } // generates base 10 palindromes greater than 100 starting // with the specified digit class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
Pancake numbers
C++
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. [[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). ;References # Bill Gates and the pancake problem # A058986
#include <iostream> #include <vector> #include <algorithm> #include <map> #include <queue> #include <numeric> #include <iomanip> std::vector<int32_t> flip_stack(std::vector<int32_t>& stack, const int32_t index) { reverse(stack.begin(), stack.begin() + index); return stack; } std::pair<std::vector<int32_t>, int32_t> pancake(const int32_t number) { std::vector<int32_t> initial_stack(number); std::iota(initial_stack.begin(), initial_stack.end(), 1); std::map<std::vector<int32_t>, int32_t> stack_flips = { std::make_pair(initial_stack, 1) }; std::queue<std::vector<int32_t>> queue; queue.push(initial_stack); while ( ! queue.empty() ) { std::vector<int32_t> stack = queue.front(); queue.pop(); const int32_t flips = stack_flips[stack] + 1; for ( int i = 2; i <= number; ++i ) { std::vector<int32_t> flipped = flip_stack(stack, i); if ( stack_flips.find(flipped) == stack_flips.end() ) { stack_flips[flipped] = flips; queue.push(flipped); } } } auto ptr = std::max_element( stack_flips.begin(), stack_flips.end(), [] ( const auto & pair1, const auto & pair2 ) { return pair1.second < pair2.second; } ); return std::make_pair(ptr->first, ptr->second); } int main() { for ( int32_t n = 1; n <= 9; ++n ) { std::pair<std::vector<int32_t>, int32_t> result = pancake(n); std::cout << "pancake(" << n << ") = " << std::setw(2) << result.second << ". Example ["; for ( uint64_t i = 0; i < result.first.size() - 1; ++i ) { std::cout << result.first[i] << ", "; } std::cout << result.first.back() << "]" << std::endl; } }
Pangram checker
C++
A pangram is a sentence that contains all the letters of the English alphabet at least once. For example: ''The quick brown fox jumps over the lazy dog''. ;Task: Write a function or method to check a sentence to see if it is a pangram (or not) and show its use. ;Related tasks: :* determine if a string has all the same characters :* determine if a string has all unique characters
#include <algorithm> #include <cctype> #include <string> #include <iostream> const std::string alphabet("abcdefghijklmnopqrstuvwxyz"); bool is_pangram(std::string s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); std::sort(s.begin(), s.end()); return std::includes(s.begin(), s.end(), alphabet.begin(), alphabet.end()); } int main() { const auto examples = {"The quick brown fox jumps over the lazy dog", "The quick white cat jumps over the lazy dog"}; std::cout.setf(std::ios::boolalpha); for (auto& text : examples) { std::cout << "Is \"" << text << "\" a pangram? - " << is_pangram(text) << std::endl; } }
Parsing/RPN calculator algorithm
C++
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''. * Assume an input of a correct, space separated, string of tokens of an RPN expression * Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: 3 4 2 * 1 5 - 2 3 ^ ^ / + * Print or display the output here ;Notes: * '''^''' means exponentiation in the expression above. * '''/''' means division. ;See also: * [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression. * Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task). * [[Parsing/RPN to infix conversion]]. * [[Arithmetic evaluation]].
#include <vector> #include <string> #include <sstream> #include <iostream> #include <cmath> #include <algorithm> #include <iterator> #include <cstdlib> double rpn(const std::string &expr){ std::istringstream iss(expr); std::vector<double> stack; std::cout << "Input\tOperation\tStack after" << std::endl; std::string token; while (iss >> token) { std::cout << token << "\t"; double tokenNum; if (std::istringstream(token) >> tokenNum) { std::cout << "Push\t\t"; stack.push_back(tokenNum); } else { std::cout << "Operate\t\t"; double secondOperand = stack.back(); stack.pop_back(); double firstOperand = stack.back(); stack.pop_back(); if (token == "*") stack.push_back(firstOperand * secondOperand); else if (token == "/") stack.push_back(firstOperand / secondOperand); else if (token == "-") stack.push_back(firstOperand - secondOperand); else if (token == "+") stack.push_back(firstOperand + secondOperand); else if (token == "^") stack.push_back(std::pow(firstOperand, secondOperand)); else { //just in case std::cerr << "Error" << std::endl; std::exit(1); } } std::copy(stack.begin(), stack.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; } return stack.back(); } int main() { std::string s = " 3 4 2 * 1 5 - 2 3 ^ ^ / + "; std::cout << "Final answer: " << rpn(s) << std::endl; return 0; }
Parsing/RPN to infix conversion
C++
Create a program that takes an infix notation. * Assume an input of a correct, space separated, string of tokens * Generate a space separated output string representing the same expression in infix notation * Show how the major datastructure of your algorithm changes with each new token parsed. * Test with the following input RPN strings then print and display the output here. :::::{| class="wikitable" ! RPN input !! sample output |- || align="center" | 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 |- || align="center" | 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) |} * Operator precedence and operator associativity is given in this table: ::::::::{| class="wikitable" ! operator !! associativity !! operation |- || align="center" | ^ || 4 || right || exponentiation |- || align="center" | * || 3 || left || multiplication |- || align="center" | / || 3 || left || division |- || align="center" | + || 2 || left || addition |- || align="center" | - || 2 || left || subtraction |} ;See also: * [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression. * [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression. * Postfix to infix from the RubyQuiz site.
#include <iostream> #include <stack> #include <string> #include <map> #include <set> using namespace std; struct Entry_ { string expr_; string op_; }; bool PrecedenceLess(const string& lhs, const string& rhs, bool assoc) { static const map<string, int> KNOWN({ { "+", 1 }, { "-", 1 }, { "*", 2 }, { "/", 2 }, { "^", 3 } }); static const set<string> ASSOCIATIVE({ "+", "*" }); return (KNOWN.count(lhs) ? KNOWN.find(lhs)->second : 0) < (KNOWN.count(rhs) ? KNOWN.find(rhs)->second : 0) + (assoc && !ASSOCIATIVE.count(rhs) ? 1 : 0); } void Parenthesize(Entry_* old, const string& token, bool assoc) { if (!old->op_.empty() && PrecedenceLess(old->op_, token, assoc)) old->expr_ = '(' + old->expr_ + ')'; } void AddToken(stack<Entry_>* stack, const string& token) { if (token.find_first_of("0123456789") != string::npos) stack->push(Entry_({ token, string() })); // it's a number, no operator else { // it's an operator if (stack->size() < 2) cout<<"Stack underflow"; auto rhs = stack->top(); Parenthesize(&rhs, token, false); stack->pop(); auto lhs = stack->top(); Parenthesize(&lhs, token, true); stack->top().expr_ = lhs.expr_ + ' ' + token + ' ' + rhs.expr_; stack->top().op_ = token; } } string ToInfix(const string& src) { stack<Entry_> stack; for (auto start = src.begin(), p = src.begin(); ; ++p) { if (p == src.end() || *p == ' ') { if (p > start) AddToken(&stack, string(start, p)); if (p == src.end()) break; start = p + 1; } } if (stack.size() != 1) cout<<"Incomplete expression"; return stack.top().expr_; } int main(void) { try { cout << ToInfix("3 4 2 * 1 5 - 2 3 ^ ^ / +") << "\n"; cout << ToInfix("1 2 + 3 4 + ^ 5 6 + ^") << "\n"; return 0; } catch (...) { cout << "Failed\n"; return -1; } }
Parsing/Shunting-yard algorithm
C++
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. * Assume an input of a correct, space separated, string of tokens representing an infix expression * Generate a space separated output string representing the RPN * Test with the input string: :::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 * print and display the output here. * Operator precedence is given in this table: :{| class="wikitable" ! operator !! associativity !! operation |- || align="center" | ^ || 4 || right || exponentiation |- || align="center" | * || 3 || left || multiplication |- || align="center" | / || 3 || left || division |- || align="center" | + || 2 || left || addition |- || align="center" | - || 2 || left || subtraction |} ;Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. ;Note The handling of functions and arguments is not required. ;See also: * [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression. * [[Parsing/RPN to infix conversion]].
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; //------------------------------------------------------------------------------------------------- // throw error( "You ", profanity, "ed up!" ); // Don't mess up, okay? //------------------------------------------------------------------------------------------------- #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return std::runtime_error( (std::ostringstream{} << ... << args).str() ); }; //------------------------------------------------------------------------------------------------- // Stack //------------------------------------------------------------------------------------------------- // Let us co-opt a vector for our stack type. // C++ pedants: no splicing possible == totally okay to do this. // // Note: C++ provides a more appropriate std::stack class, except that the task requires us to // be able to display its contents, and that kind of access is an expressly non-stack behavior. template <typename T> struct stack : public std::vector <T> { using base_type = std::vector <T> ; T push ( const T& x ) { base_type::push_back( x ); return x; } const T& top () { return base_type::back(); } T pop () { T x = std::move( top() ); base_type::pop_back(); return x; } bool empty() { return base_type::empty(); } }; //------------------------------------------------------------------------------------------------- using Number = double; //------------------------------------------------------------------------------------------------- // Numbers are already too awesome to need extra diddling. //------------------------------------------------------------------------------------------------- // Operators //------------------------------------------------------------------------------------------------- using Operator_Name = string; using Precedence = int; enum class Associates { none, left_to_right, right_to_left }; struct Operator_Info { Precedence precedence; Associates associativity; }; std::unordered_map <Operator_Name, Operator_Info> Operators = { { "^", { 4, Associates::right_to_left } }, { "*", { 3, Associates::left_to_right } }, { "/", { 3, Associates::left_to_right } }, { "+", { 2, Associates::left_to_right } }, { "-", { 2, Associates::left_to_right } }, }; Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; } Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; } //------------------------------------------------------------------------------------------------- using Token = string; //------------------------------------------------------------------------------------------------- bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); } bool is_operator ( const Token& t ) { return Operators.count( t ); } bool is_open_parenthesis ( const Token& t ) { return t == "("; } bool is_close_parenthesis( const Token& t ) { return t == ")"; } bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); } //------------------------------------------------------------------------------------------------- // std::cout << a_vector_of_something; //------------------------------------------------------------------------------------------------- // Weird C++ stream operator stuff (for I/O). // Don't worry if this doesn't look like it makes any sense. // template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs ) { std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs; } //------------------------------------------------------------------------------------------------- // Progressive_Display //------------------------------------------------------------------------------------------------- // This implements the required task: // "use the algorithm to show the changes in the operator // stack and RPN output as each individual token is processed" // #include <iomanip> struct Progressive_Display { string token_name; string token_type; Progressive_Display() // Header for the table we are going to generate { std::cout << "\n" " INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n" "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n"; } Progressive_Display& operator () ( const Token& token ) // Ready the first two columns { token_name = token; token_type = is_operator ( token ) ? "op" : is_parenthesis( token ) ? "()" : is_number ( token ) ? "num" : ""; return *this; } Progressive_Display& operator () ( // Display all columns of a row const string & description, const stack <Token> & stack, const vector <Token> & output ) { std::cout << std::right << std::setw( 7 ) << token_name << " │ " << std::left << std::setw( 4 ) << token_type << " │ " << std::setw( 16 ) << description << " │ " << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ " << output << "\n"; return operator () ( "" ); // Reset the first two columns to empty for next iteration } }; //------------------------------------------------------------------------------------------------- vector <Token> parse( const vector <Token> & tokens ) //------------------------------------------------------------------------------------------------- { vector <Token> output; stack <Token> stack; Progressive_Display display; for (auto token : tokens) // Shunting Yard takes a single linear pass through the tokens //......................................................................... if (is_number( token )) { output.push_back( token ); display( token )( "num --> output", stack, output ); } //......................................................................... else if (is_operator( token ) or is_parenthesis( token )) { display( token ); if (!is_open_parenthesis( token )) { // pop --> output // : until '(' if token is ')' // : while prec(token) > prec(top) // : while prec(token) == prec(top) AND assoc(token) is left-to-right while (!stack.empty() and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() )) or (precedence( stack.top() ) > precedence( token )) or ( (precedence( stack.top() ) == precedence( token )) and (associativity( token ) == Associates::left_to_right)))) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } // If we popped until '(' because token is ')', toss both parens if (is_close_parenthesis( token )) { stack.pop(); display( "pop", stack, output ); } } // Everything except ')' --> stack if (!is_close_parenthesis( token )) { stack.push( token ); display( "push op", stack, output ); } } //......................................................................... else throw error( "unexpected token: ", token ); // Anything left on the operator stack just gets moved to the output display( "END" ); while (!stack.empty()) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } return output; } //------------------------------------------------------------------------------------------------- int main( int argc, char** argv ) //------------------------------------------------------------------------------------------------- try { auto tokens = vector <Token> ( argv+1, argv+argc ); auto rpn_expr = parse( tokens ); std::cout << "\nInfix = " << tokens << "\nRPN = " << rpn_expr << "\n"; } catch (std::exception e) { std::cerr << "error: " << e.what() << "\n"; return 1; }
Parsing/Shunting-yard algorithm
C++ from Java
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. * Assume an input of a correct, space separated, string of tokens representing an infix expression * Generate a space separated output string representing the RPN * Test with the input string: :::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 * print and display the output here. * Operator precedence is given in this table: :{| class="wikitable" ! operator !! associativity !! operation |- || align="center" | ^ || 4 || right || exponentiation |- || align="center" | * || 3 || left || multiplication |- || align="center" | / || 3 || left || division |- || align="center" | + || 2 || left || addition |- || align="center" | - || 2 || left || subtraction |} ;Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. ;Note The handling of functions and arguments is not required. ;See also: * [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression. * [[Parsing/RPN to infix conversion]].
#include <iostream> #include <sstream> #include <stack> std::string infixToPostfix(const std::string& infix) { const std::string ops = "-+/*^"; std::stringstream ss; std::stack<int> s; std::stringstream input(infix); std::string token; while (std::getline(input, token, ' ')) { if (token.empty()) { continue; } char c = token[0]; size_t idx = ops.find(c); // check for operator if (idx != std::string::npos) { while (!s.empty()) { int prec2 = s.top() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) { ss << ops[s.top()] << ' '; s.pop(); } else break; } s.push(idx); } else if (c == '(') { s.push(-2); // -2 stands for '(' } else if (c == ')') { // until '(' on stack, pop operators. while (s.top() != -2) { ss << ops[s.top()] << ' '; s.pop(); } s.pop(); } else { ss << token << ' '; } } while (!s.empty()) { ss << ops[s.top()] << ' '; s.pop(); } return ss.str(); } int main() { std::string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; std::cout << "infix: " << infix << '\n'; std::cout << "postfix: " << infixToPostfix(infix) << '\n'; return 0; }
Particle fountain
C++ from Raku
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand. It is optional to have the individual particle interact with each other. If at all possible, link to a short video clip of your fountain in action. Off-site link to a demo video
#include <SDL2/SDL.h> #include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <memory> #include <random> #include <tuple> #include <vector> auto now() { using namespace std::chrono; auto time = system_clock::now(); return duration_cast<milliseconds>(time.time_since_epoch()).count(); } auto hsv_to_rgb(int h, double s, double v) { double hp = h / 60.0; double c = s * v; double x = c * (1 - std::abs(std::fmod(hp, 2) - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return std::make_tuple(Uint8(r * 255), Uint8(g * 255), Uint8(b * 255)); } class ParticleFountain { public: ParticleFountain(int particles, int width, int height); void run(); private: struct WindowDeleter { void operator()(SDL_Window* window) const { SDL_DestroyWindow(window); } }; struct RendererDeleter { void operator()(SDL_Renderer* renderer) const { SDL_DestroyRenderer(renderer); } }; struct PointInfo { double x = 0; double y = 0; double vx = 0; double vy = 0; double lifetime = 0; }; void update(double df); bool handle_event(); void render(); double rand() { return dist_(rng_); } double reciprocate() const { return reciprocate_ ? range_ * std::sin(now() / 1000.0) : 0.0; } std::unique_ptr<SDL_Window, WindowDeleter> window_; std::unique_ptr<SDL_Renderer, RendererDeleter> renderer_; int width_; int height_; std::vector<PointInfo> point_info_; std::vector<SDL_Point> points_; int num_points_ = 0; double saturation_ = 0.4; double spread_ = 1.5; double range_ = 1.5; bool reciprocate_ = false; std::mt19937 rng_; std::uniform_real_distribution<> dist_; }; ParticleFountain::ParticleFountain(int n, int width, int height) : width_(width), height_(height), point_info_(n), points_(n, {0, 0}), rng_(std::random_device{}()), dist_(0.0, 1.0) { window_.reset(SDL_CreateWindow( "C++ Particle System!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_RESIZABLE)); if (window_ == nullptr) throw std::runtime_error(SDL_GetError()); renderer_.reset( SDL_CreateRenderer(window_.get(), -1, SDL_RENDERER_ACCELERATED)); if (renderer_ == nullptr) throw std::runtime_error(SDL_GetError()); } void ParticleFountain::run() { for (double df = 0.0001;;) { auto start = now(); if (!handle_event()) break; update(df); render(); df = (now() - start) / 1000.0; } } void ParticleFountain::update(double df) { int pointidx = 0; for (PointInfo& point : point_info_) { bool willdraw = false; if (point.lifetime <= 0.0) { if (rand() < df) { point.lifetime = 2.5; point.x = width_ / 20.0; point.y = height_ / 10.0; point.vx = (spread_ * rand() - spread_ / 2 + reciprocate()) * 10.0; point.vy = (rand() - 2.9) * height_ / 20.5; willdraw = true; } } else { if (point.y > height_ / 10.0 && point.vy > 0) point.vy *= -0.3; point.vy += (height_ / 10.0) * df; point.x += point.vx * df; point.y += point.vy * df; point.lifetime -= df; willdraw = true; } if (willdraw) { points_[pointidx].x = std::floor(point.x * 10.0); points_[pointidx].y = std::floor(point.y * 10.0); ++pointidx; } } num_points_ = pointidx; } bool ParticleFountain::handle_event() { bool result = true; SDL_Event event; while (result && SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: result = false; break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { width_ = event.window.data1; height_ = event.window.data2; } break; case SDL_KEYDOWN: switch (event.key.keysym.scancode) { case SDL_SCANCODE_UP: saturation_ = std::min(saturation_ + 0.1, 1.0); break; case SDL_SCANCODE_DOWN: saturation_ = std::max(saturation_ - 0.1, 0.0); break; case SDL_SCANCODE_PAGEUP: spread_ = std::min(spread_ + 0.1, 5.0); break; case SDL_SCANCODE_PAGEDOWN: spread_ = std::max(spread_ - 0.1, 0.2); break; case SDL_SCANCODE_RIGHT: range_ = std::min(range_ + 0.1, 2.0); break; case SDL_SCANCODE_LEFT: range_ = std::max(range_ - 0.1, 0.1); break; case SDL_SCANCODE_SPACE: reciprocate_ = !reciprocate_; break; case SDL_SCANCODE_Q: result = false; break; default: break; } break; } } return result; } void ParticleFountain::render() { SDL_Renderer* renderer = renderer_.get(); SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xff); SDL_RenderClear(renderer); auto [red, green, blue] = hsv_to_rgb((now() % 5) * 72, saturation_, 1); SDL_SetRenderDrawColor(renderer, red, green, blue, 0x7f); SDL_RenderDrawPoints(renderer, points_.data(), num_points_); SDL_RenderPresent(renderer); } int main() { std::cout << "Use UP and DOWN arrow keys to modify the saturation of the " "particle colors.\n" "Use PAGE UP and PAGE DOWN keys to modify the \"spread\" of " "the particles.\n" "Toggle reciprocation off / on with the SPACE bar.\n" "Use LEFT and RIGHT arrow keys to modify angle range for " "reciprocation.\n" "Press the \"q\" key to quit.\n"; if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "ERROR: " << SDL_GetError() << '\n'; return EXIT_FAILURE; } try { ParticleFountain pf(3000, 800, 800); pf.run(); } catch (const std::exception& ex) { std::cerr << "ERROR: " << ex.what() << '\n'; SDL_Quit(); return EXIT_FAILURE; } SDL_Quit(); return EXIT_SUCCESS; }
Pascal's triangle/Puzzle
C++ from C
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). ;Task: Write a program to find a solution to this puzzle.
#include <iostream> #include <iomanip> inline int sign(int i) { return i < 0 ? -1 : i > 0; } inline int& E(int *x, int row, int col) { return x[row * (row + 1) / 2 + col]; } int iter(int *v, int *diff) { // enforce boundary conditions E(v, 0, 0) = 151; E(v, 2, 0) = 40; E(v, 4, 1) = 11; E(v, 4, 3) = 4; // calculate difference from equilibrium for (auto i = 1u; i < 5u; i++) for (auto j = 0u; j <= i; j++) { E(diff, i, j) = 0; if (j < i) E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j); if (j) E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j); } for (auto i = 0u; i < 4u; i++) for (auto j = 0u; j < i; j++) E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j); E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2); // do feedback, check if we are done uint sum; int e = 0; for (auto i = sum = 0u; i < 15u; i++) { sum += !!sign(e = diff[i]); // 1/5-ish feedback strength on average. These numbers are highly magical, depending on nodes' connectivities if (e >= 4 || e <= -4) v[i] += e / 5; else if (rand() < RAND_MAX / 4) v[i] += sign(e); } return sum; } void show(int *x) { for (auto i = 0u; i < 5u; i++) for (auto j = 0u; j <= i; j++) std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n'); } int main() { int v[15] = { 0 }, diff[15] = { 0 }; for (auto i = 1u, s = 1u; s; i++) { s = iter(v, diff); std::cout << "pass " << i << ": " << s << std::endl; } show(v); return 0; }
Password generator
C++
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a --> z upper-case letters: A --> Z digits: 0 --> 9 other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include ''at least one'' (of each of the four groups): lower-case letter, upper-case letter, digit (numeral), and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example: Il1 O0 5S 2Z where the characters are: ::::* capital eye, lowercase ell, the digit one ::::* capital oh, the digit zero ::::* the digit five, capital ess ::::* the digit two, capital zee
#include <iostream> #include <string> #include <algorithm> #include <ctime> const std::string CHR[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" }; const std::string UNS = "O0l1I5S2Z"; std::string createPW( int len, bool safe ) { std::string pw; char t; for( int x = 0; x < len; x += 4 ) { for( int y = x; y < x + 4 && y < len; y++ ) { do { t = CHR[y % 4].at( rand() % CHR[y % 4].size() ); } while( safe && UNS.find( t ) != UNS.npos ); pw.append( 1, t ); } } std::random_shuffle( pw.begin(), pw.end() ); return pw; } void generate( int len, int count, bool safe ) { for( int c = 0; c < count; c++ ) { std::cout << createPW( len, safe ) << "\n"; } std::cout << "\n\n"; } int main( int argc, char* argv[] ){ if( argv[1][1] == '?' || argc < 5 ) { std::cout << "Syntax: PWGEN length count safe seed /?\n" "length:\tthe length of the password(min 4)\n" "count:\thow many passwords should be generated\n" "safe:\t1 will exclude visually similar characters, 0 won't\n" "seed:\tnumber to seed the random generator or 0\n" "/?\tthis text\n\n"; } else { int l = atoi( argv[1] ), c = atoi( argv[2] ), e = atoi( argv[3] ), s = atoi( argv[4] ); if( l < 4 ) { std::cout << "Passwords must be at least 4 characters long.\n\n"; } else { if (s == 0) { std::srand( time( NULL ) ); } else { std::srand( unsigned( s ) ); } generate( l, c, e != 0 ); } } return 0; }
Peaceful chess queen armies
C++ from D
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour. \ | / = = = = / | \ / | \ | The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''. ;Task: # Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). # Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. # Display here results for the m=4, n=5 case. ;References: * Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. * A250000 OEIS
#include <iostream> #include <vector> enum class Piece { empty, black, white }; typedef std::pair<int, int> position; bool isAttacking(const position &queen, const position &pos) { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second); } bool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { auto pos = std::make_pair(i, j); for (auto queen : pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { goto inner; } } for (auto queen : pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.push_back(pos); placingBlack = false; } else { pWhiteQueens.push_back(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.pop_back(); pWhiteQueens.pop_back(); placingBlack = true; } inner: {} } } if (!placingBlack) { pBlackQueens.pop_back(); } return false; } void printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) { std::vector<Piece> board(n * n); std::fill(board.begin(), board.end(), Piece::empty); for (auto &queen : blackQueens) { board[queen.first * n + queen.second] = Piece::black; } for (auto &queen : whiteQueens) { board[queen.first * n + queen.second] = Piece::white; } for (size_t i = 0; i < board.size(); ++i) { if (i != 0 && i % n == 0) { std::cout << '\n'; } switch (board[i]) { case Piece::black: std::cout << "B "; break; case Piece::white: std::cout << "W "; break; case Piece::empty: default: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { std::cout << "x "; } else { std::cout << "* "; } break; } } std::cout << "\n\n"; } int main() { std::vector<position> nms = { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (auto nm : nms) { std::cout << nm.second << " black and " << nm.second << " white queens on a " << nm.first << " x " << nm.first << " board:\n"; std::vector<position> blackQueens, whiteQueens; if (place(nm.second, nm.first, blackQueens, whiteQueens)) { printBoard(nm.first, blackQueens, whiteQueens); } else { std::cout << "No solution exists.\n\n"; } } return 0; }
Perfect shuffle
C++
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: ::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: ::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right" |- | ''original:'' || 1 2 3 4 5 6 7 8 |- | ''after 1st shuffle:'' || 1 5 2 6 3 7 4 8 |- | ''after 2nd shuffle:'' || 1 3 5 7 2 4 6 8 |- | ''after 3rd shuffle:'' || 1 2 3 4 5 6 7 8 |} '''''The Task''''' # Write a function that can perform a perfect shuffle on an even-sized list of values. # Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. #* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. #* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. '''''Test Cases''''' ::::: {| class="wikitable" |- ! input ''(deck size)'' !! output ''(number of shuffles required)'' |- | 8 || 3 |- | 24 || 11 |- | 52 || 8 |- | 100 || 30 |- | 1020 || 1018 |- | 1024 || 10 |- | 10000 || 300 |}
#include <iostream> #include <algorithm> #include <vector> int pShuffle( int t ) { std::vector<int> v, o, r; for( int x = 0; x < t; x++ ) { o.push_back( x + 1 ); } r = o; int t2 = t / 2 - 1, c = 1; while( true ) { v = r; r.clear(); for( int x = t2; x > -1; x-- ) { r.push_back( v[x + t2 + 1] ); r.push_back( v[x] ); } std::reverse( r.begin(), r.end() ); if( std::equal( o.begin(), o.end(), r.begin() ) ) return c; c++; } } int main() { int s[] = { 8, 24, 52, 100, 1020, 1024, 10000 }; for( int x = 0; x < 7; x++ ) { std::cout << "Cards count: " << s[x] << ", shuffles required: "; std::cout << pShuffle( s[x] ) << ".\n"; } return 0; }
Perfect totient numbers
C++
Generate and show here, the first twenty Perfect totient numbers. ;Related task: ::* [[Totient function]] ;Also see: ::* the OEIS entry for perfect totient numbers. ::* mrob list of the first 54
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; bool perfect_totient_number(const totient_calculator& tc, int n) { int sum = 0; for (int m = n; m > 1; ) { int t = tc.totient(m); sum += t; m = t; } return sum == n; } int main() { totient_calculator tc(10000); int count = 0, n = 1; std::cout << "First 20 perfect totient numbers:\n"; for (; count < 20; ++n) { if (perfect_totient_number(tc, n)) { if (count > 0) std::cout << ' '; ++count; std::cout << n; } } std::cout << '\n'; return 0; }
Permutations by swapping
C++
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation ''here''. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement. ;References: * Steinhaus-Johnson-Trotter algorithm * Johnson-Trotter Algorithm Listing All Permutations * Heap's algorithm * Tintinnalogia ;Related tasks: * [[Matrix arithmetic] * [[Gray code]]
#include <iostream> #include <vector> using namespace std; vector<int> UpTo(int n, int offset = 0) { vector<int> retval(n); for (int ii = 0; ii < n; ++ii) retval[ii] = ii + offset; return retval; } struct JohnsonTrotterState_ { vector<int> values_; vector<int> positions_; // size is n+1, first element is not used vector<bool> directions_; int sign_; JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {} int LargestMobile() const // returns 0 if no mobile integer exists { for (int r = values_.size(); r > 0; --r) { const int loc = positions_[r] + (directions_[r] ? 1 : -1); if (loc >= 0 && loc < values_.size() && values_[loc] < r) return r; } return 0; } bool IsComplete() const { return LargestMobile() == 0; } void operator++() // implement Johnson-Trotter algorithm { const int r = LargestMobile(); const int rLoc = positions_[r]; const int lLoc = rLoc + (directions_[r] ? 1 : -1); const int l = values_[lLoc]; // do the swap swap(values_[lLoc], values_[rLoc]); swap(positions_[l], positions_[r]); sign_ = -sign_; // change directions for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd) *pd = !*pd; } }; int main(void) { JohnsonTrotterState_ state(4); do { for (auto v : state.values_) cout << v << " "; cout << "\n"; ++state; } while (!state.IsComplete()); }
Phrase reversals
C++
Given a string of space separated words containing the following phrase: rosetta code phrase reversal :# Reverse the characters of the string. :# Reverse the characters of each individual word in the string, maintaining original word order within the string. :# Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here.
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <iterator> #include <sstream> int main() { std::string s = "rosetta code phrase reversal"; std::cout << "Input : " << s << '\n' << "Input reversed : " << std::string(s.rbegin(), s.rend()) << '\n' ; std::istringstream is(s); std::vector<std::string> words(std::istream_iterator<std::string>(is), {}); std::cout << "Each word reversed : " ; for(auto w : words) std::cout << std::string(w.rbegin(), w.rend()) << ' '; std::cout << '\n' << "Original word order reversed : " ; reverse_copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << '\n' ; }
Pig the dice game
C++
The game of Pig is a multiplayer game played with a single six-sided die. The object of the game is to reach '''100''' points or more. Play is taken in turns. On each person's turn that person has the option of either: :# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player. :# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player. ;Task: Create a program to score for, and simulate dice throws for, a two-person game. ;Related task: * [[Pig the dice game/Player]]
#include <windows.h> #include <iostream> #include <string> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- const int PLAYERS = 2, MAX_POINTS = 100; //-------------------------------------------------------------------------------------------------- class player { public: player() { reset(); } void reset() { name = ""; current_score = round_score = 0; } string getName() { return name; } void setName( string n ) { name = n; } int getCurrScore() { return current_score; } void addCurrScore() { current_score += round_score; } int getRoundScore() { return round_score; } void addRoundScore( int rs ) { round_score += rs; } void zeroRoundScore() { round_score = 0; } private: string name; int current_score, round_score; }; //-------------------------------------------------------------------------------------------------- class pigGame { public: pigGame() { resetPlayers(); } void play() { while( true ) { system( "cls" ); int p = 0; while( true ) { if( turn( p ) ) { praise( p ); break; } ++p %= PLAYERS; } string r; cout << "Do you want to play again ( y / n )? "; cin >> r; if( r != "Y" && r != "y" ) return; resetPlayers(); } } private: void resetPlayers() { system( "cls" ); string n; for( int p = 0; p < PLAYERS; p++ ) { _players[p].reset(); cout << "Enter name player " << p + 1 << ": "; cin >> n; _players[p].setName( n ); } } void praise( int p ) { system( "cls" ); cout << "CONGRATULATIONS " << _players[p].getName() << ", you are the winner!" << endl << endl; cout << "Final Score" << endl; drawScoreboard(); cout << endl << endl; } void drawScoreboard() { for( int p = 0; p < PLAYERS; p++ ) cout << _players[p].getName() << ": " << _players[p].getCurrScore() << " points" << endl; cout << endl; } bool turn( int p ) { system( "cls" ); drawScoreboard(); _players[p].zeroRoundScore(); string r; int die; while( true ) { cout << _players[p].getName() << ", your round score is: " << _players[p].getRoundScore() << endl; cout << "What do you want to do (H)old or (R)oll? "; cin >> r; if( r == "h" || r == "H" ) { _players[p].addCurrScore(); return _players[p].getCurrScore() >= MAX_POINTS; } if( r == "r" || r == "R" ) { die = rand() % 6 + 1; if( die == 1 ) { cout << _players[p].getName() << ", your turn is over." << endl << endl; system( "pause" ); return false; } _players[p].addRoundScore( die ); } cout << endl; } return false; } player _players[PLAYERS]; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { srand( GetTickCount() ); pigGame pg; pg.play(); return 0; } //--------------------------------------------------------------------------------------------------
Pig the dice game/Player
C++
Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy. * State here the play strategies involved. * Show play during a game here. As a stretch goal: * Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger. ;Game Rules: The game of Pig is a multiplayer game played with a single six-sided die. The object of the game is to reach 100 points or more. Play is taken in turns. On each person's turn that person has the option of either # '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player. # '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player. ;References * Pig (dice) * The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
#include <windows.h> #include <iostream> #include <string> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- const int PLAYERS = 4, MAX_POINTS = 100; //-------------------------------------------------------------------------------------------------- enum Moves { ROLL, HOLD }; //-------------------------------------------------------------------------------------------------- class player { public: player() { current_score = round_score = 0; } void addCurrScore() { current_score += round_score; } int getCurrScore() { return current_score; } int getRoundScore() { return round_score; } void addRoundScore( int rs ) { round_score += rs; } void zeroRoundScore() { round_score = 0; } virtual int getMove() = 0; virtual ~player() {} protected: int current_score, round_score; }; //-------------------------------------------------------------------------------------------------- class RAND_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; if( rand() % 10 < 5 ) return ROLL; if( round_score > 0 ) return HOLD; return ROLL; } }; //-------------------------------------------------------------------------------------------------- class Q2WIN_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; int q = MAX_POINTS - current_score; if( q < 6 ) return ROLL; q /= 4; if( round_score < q ) return ROLL; return HOLD; } }; //-------------------------------------------------------------------------------------------------- class AL20_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; if( round_score < 20 ) return ROLL; return HOLD; } }; //-------------------------------------------------------------------------------------------------- class AL20T_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; int d = ( 100 * round_score ) / 20; if( round_score < 20 && d < rand() % 100 ) return ROLL; return HOLD; } }; //-------------------------------------------------------------------------------------------------- class Auto_pigGame { public: Auto_pigGame() { _players[0] = new RAND_Player(); _players[1] = new Q2WIN_Player(); _players[2] = new AL20_Player(); _players[3] = new AL20T_Player(); } ~Auto_pigGame() { delete _players[0]; delete _players[1]; delete _players[2]; delete _players[3]; } void play() { int die, p = 0; bool endGame = false; while( !endGame ) { switch( _players[p]->getMove() ) { case ROLL: die = rand() % 6 + 1; if( die == 1 ) { cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl; nextTurn( p ); continue; } _players[p]->addRoundScore( die ); cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl; break; case HOLD: _players[p]->addCurrScore(); cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl; if( _players[p]->getCurrScore() >= MAX_POINTS ) endGame = true; else nextTurn( p ); } } showScore(); } private: void nextTurn( int& p ) { _players[p]->zeroRoundScore(); ++p %= PLAYERS; } void showScore() { cout << endl; cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl; cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl; cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl; cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl; system( "pause" ); } player* _players[PLAYERS]; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { srand( GetTickCount() ); Auto_pigGame pg; pg.play(); return 0; } //--------------------------------------------------------------------------------------------------
Plasma effect
C++
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. ;Task Create a plasma effect. ;See also * Computer Graphics Tutorial (lodev.org) * Plasma (bidouille.org)
#include <windows.h> #include <math.h> #include <string> const int BMP_SIZE = 240, MY_TIMER = 987654; 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; } DWORD* bits() { return ( DWORD* )pBits; } 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 plasma { public: plasma() { currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear(); plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; int i, j, dst = 0; double temp; for( j = 0; j < BMP_SIZE * 2; j++ ) { for( i = 0; i < BMP_SIZE * 2; i++ ) { plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) ); plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 ); dst++; } } } void update() { DWORD dst; BYTE a, c1,c2, c3; currentTime += ( double )( rand() % 2 + 1 ); int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ), x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ), x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ), y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ), y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ), y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) ); int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3; DWORD* bits = _bmp.bits(); for( int j = 0; j < BMP_SIZE; j++ ) { dst = j * BMP_SIZE; for( int i= 0; i < BMP_SIZE; i++ ) { a = plasma2[src1] + plasma1[src2] + plasma2[src3]; c1 = a << 1; c2 = a << 2; c3 = a << 3; bits[dst + i] = RGB( c1, c2, c3 ); src1++; src2++; src3++; } src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE; } draw(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: void draw() { HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); } myBitmap _bmp; HWND _hwnd; float _ang; BYTE *plasma1, *plasma2; double currentTime; int _WD, _WV; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); SetTimer( _hwnd, MY_TIMER, 15, NULL ); _plasma.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_MY_PLASMA_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _plasma.update(); } void wnd::doTimer() { _plasma.update(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_PAINT: { PAINTSTRUCT ps; _inst->doPaint( BeginPaint( hWnd, &ps ) ); EndPaint( hWnd, &ps ); return 0; } case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_TIMER: _inst->doTimer(); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_PLASMA_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma; }; wnd* wnd::_inst = 0; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); }
Playfair cipher
C++
Implement a Playfair cipher for encryption and decryption. The user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet. The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces. ;Output example: HI DE TH EG OL DI NT HE TR EX ES TU MP
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ ) { if( getCharPos( *ti++, a, b ) ) if( getCharPos( *ti, c, d ) ) { if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); } else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); } else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); } } } _txt = ntxt; } void display() { cout << "\n\n OUTPUT:\n=========" << endl; string::iterator si = _txt.begin(); int cnt = 0; while( si != _txt.end() ) { cout << *si; si++; cout << *si << " "; si++; if( ++cnt >= 26 ) cout << endl, cnt = 0; } cout << endl << endl; } char getChar( int a, int b ) { return _m[ (b + 5) % 5 ][ (a + 5) % 5 ]; } bool getCharPos( char l, int &a, int &b ) { for( int y = 0; y < 5; y++ ) for( int x = 0; x < 5; x++ ) if( _m[y][x] == l ) { a = x; b = y; return true; } return false; } void getTextReady( string t, bool ij, bool e ) { for( string::iterator si = t.begin(); si != t.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( *si == 'J' && ij ) *si = 'I'; else if( *si == 'Q' && !ij ) continue; _txt += *si; } if( e ) { string ntxt = ""; size_t len = _txt.length(); for( size_t x = 0; x < len; x += 2 ) { ntxt += _txt[x]; if( x + 1 < len ) { if( _txt[x] == _txt[x + 1] ) ntxt += 'X'; ntxt += _txt[x + 1]; } } _txt = ntxt; } if( _txt.length() & 1 ) _txt += 'X'; } void createGrid( string k, bool ij ) { if( k.length() < 1 ) k = "KEYWORD"; k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = ""; for( string::iterator si = k.begin(); si != k.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue; if( nk.find( *si ) == -1 ) nk += *si; } copy( nk.begin(), nk.end(), &_m[0][0] ); } string _txt; char _m[5][5]; }; int main( int argc, char* argv[] ) { string key, i, txt; bool ij, e; cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' ); cout << "Enter a en/decryption key: "; getline( cin, key ); cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' ); cout << "Enter the text: "; getline( cin, txt ); playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" ); }
Plot coordinate pairs
C++
Plot a function represented as x, y numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
#include <windows.h> #include <string> #include <vector> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- const int HSTEP = 46, MWID = 40, MHEI = 471; const float VSTEP = 2.3f; //-------------------------------------------------------------------------------------------------- class vector2 { public: vector2() { x = y = 0; } vector2( float a, float b ) { x = a; y = b; } void set( float a, float b ) { x = a; y = b; } float x, y; }; //-------------------------------------------------------------------------------------------------- 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( 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 plot { public: plot() { bmp.create( 512, 512 ); } void draw( vector<vector2>* pairs ) { bmp.clear( 0xff ); drawGraph( pairs ); plotIt( pairs ); HDC dc = GetDC( GetConsoleWindow() ); BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( GetConsoleWindow(), dc ); //bmp.saveBitmap( "f:\\rc\\plot.bmp" ); } private: void drawGraph( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); bmp.setPenColor( RGB( 240, 240, 240 ) ); DWORD b = 11, c = 40, x; RECT rc; char txt[8]; for( x = 0; x < pairs->size(); x++ ) { MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 ); wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); wsprintf( txt, "%d", x ); SetRect( &rc, c - 8, 472, c + 8, 492 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); c += 46; b += 46; } SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); } void plotIt( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); HBRUSH br = CreateSolidBrush( 255 ); RECT rc; bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); vector<vector2>::iterator it = pairs->begin(); int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); MoveToEx( dc, a, b, NULL ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); it++; for( ; it < pairs->end(); it++ ) { a = MWID + HSTEP * static_cast<int>( ( *it ).x ); b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); LineTo( dc, a, b ); } DeleteObject( br ); } myBitmap bmp; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); plot pt; vector<vector2> pairs; pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) ); pt.draw( &pairs ); system( "pause" ); return 0; } //--------------------------------------------------------------------------------------------------
Poker hand analyser
C++
Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. ;Example: ::::'''2d''' (two of diamonds). Faces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k''' Suits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or alternatively, the unicode card-suit characters: Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid ;Examples: 2 2 2 k q: three-of-a-kind 2 5 7 8 9: high-card a 2 3 4 5: straight 2 3 2 3 3: full-house 2 7 2 3 3: two-pair 2 7 7 7 7: four-of-a-kind 10 j q k a: straight-flush 4 4 k 5 10: one-pair q 10 7 6 q: invalid The programs output for the above examples should be displayed here on this page. ;Extra credit: # use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). # allow two jokers ::* use the symbol '''joker''' ::* duplicates would be allowed (for jokers only) ::* five-of-a-kind would then be the highest hand ;More extra credit examples: joker 2 2 k q: three-of-a-kind joker 5 7 8 9: straight joker 2 3 4 5: straight joker 3 2 3 3: four-of-a-kind joker 7 2 3 3: three-of-a-kind joker 7 7 7 7: five-of-a-kind joker j q k A: straight-flush joker 4 k 5 10: one-pair joker k 7 6 4: flush joker 2 joker 4 5: straight joker Q joker A 10: straight joker Q joker A 10: straight-flush joker 2 2 joker q: four-of-a-kind ;Related tasks: * [[Playing cards]] * [[Card shuffles]] * [[Deal cards_for_FreeCell]] * [[War Card_Game]] * [[Go Fish]]
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), h.begin(), toupper ); istringstream i( h ); copy( istream_iterator<string>( i ), istream_iterator<string>(), back_inserter<vector<string> >( hand ) ); if( hand.size() != 5 ) return "invalid hand."; vector<string>::iterator it = hand.begin(); sort( it, hand.end() ); if( hand.end() != adjacent_find( it, hand.end() ) ) return "invalid hand."; while( it != hand.end() ) { if( ( *it ).length() != 2 ) return "invalid hand."; int n = face.find( ( *it ).at( 0 ) ), l = suit.find( ( *it ).at( 1 ) ); if( n < 0 || l < 0 ) return "invalid hand."; faceCnt[n]++; suitCnt[l]++; it++; } cout << h << ": "; return analyzeHand(); } private: string analyzeHand() { bool p1 = false, p2 = false, t = false, f = false, fl = false, st = false; for( int x = 0; x < 13; x++ ) switch( faceCnt[x] ) { case 2: if( p1 ) p2 = true; else p1 = true; break; case 3: t = true; break; case 4: f = true; } for( int x = 0; x < 4; x++ )if( suitCnt[x] == 5 ){ fl = true; break; } if( !p1 && !p2 && !t && !f ) { int s = 0; for( int x = 0; x < 13; x++ ) { if( faceCnt[x] ) s++; else s = 0; if( s == 5 ) break; } st = ( s == 5 ) || ( s == 4 && faceCnt[0] && !faceCnt[1] ); } if( st && fl ) return "straight-flush"; else if( f ) return "four-of-a-kind"; else if( p1 && t ) return "full-house"; else if( fl ) return "flush"; else if( st ) return "straight"; else if( t ) return "three-of-a-kind"; else if( p1 && p2 ) return "two-pair"; else if( p1 ) return "one-pair"; return "high-card"; } string face, suit; unsigned char faceCnt[13], suitCnt[4]; }; int main( int argc, char* argv[] ) { poker p; cout << p.analyze( "2h 2d 2s ks qd" ) << endl; cout << p.analyze( "2h 5h 7d 8s 9d" ) << endl; cout << p.analyze( "ah 2d 3s 4s 5s" ) << endl; cout << p.analyze( "2h 3h 2d 3s 3d" ) << endl; cout << p.analyze( "2h 7h 2d 3s 3d" ) << endl; cout << p.analyze( "2h 7h 7d 7s 7c" ) << endl; cout << p.analyze( "th jh qh kh ah" ) << endl; cout << p.analyze( "4h 4c kc 5d tc" ) << endl; cout << p.analyze( "qc tc 7c 6c 4c" ) << endl << endl; return system( "pause" ); }
Polyspiral
C++
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. ;Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. ;Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = sinf( r ), c = cosf( r ), a = _x * c - _y * s, b = _x * s + _y * c; x = a; y = b; } vector2 add( const vector2& v ) { x += v.x; y += v.y; return *this; } float x, y; }; 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; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); myBitmap bmp; bmp.create( 600, 600 ); bmp.clear(); HDC dc = bmp.getDC(); float fs = ( TWO_PI ) / 100.f; int index = 0; std::string a = "f://users//images//test", b; float ang, len; vector2 p1, p2; for( float step = 0.1f; step < 5.1f; step += .05f ) { ang = 0; len = 2; p1.set( 300, 300 ); bmp.setPenColor( RGB( rand() % 50 + 200, rand() % 300 + 220, rand() % 50 + 200 ) ); for( float xx = 0; xx < TWO_PI; xx += fs ) { MoveToEx( dc, (int)p1.x, (int)p1.y, NULL ); p2.set( 0, len ); p2.rotate( ang ); p2.add( p1 ); LineTo( dc, (int)p2.x, (int)p2.y ); p1 = p2; ang += step; len += step; } std::ostringstream ss; ss << index++; b = a + ss.str() + ".bmp"; bmp.saveBitmap( b ); bmp.clear(); } return 0; }
Population count
C++11
The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer. ''Population count'' is also known as: ::::* ''pop count'' ::::* ''popcount'' ::::* ''sideways sum'' ::::* ''bit summation'' ::::* ''Hamming weight'' For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''. ''Evil numbers'' are non-negative integers that have an ''even'' population count. ''Odious numbers'' are positive integers that have an ''odd'' population count. ;Task: * write a function (or routine) to return the population count of a non-negative integer. * all computation of the lists below should start with '''0''' (zero indexed). :* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329'''). :* display the 1st thirty ''evil'' numbers. :* display the 1st thirty ''odious'' numbers. * display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified. ;See also * The On-Line Encyclopedia of Integer Sequences: A000120 population count. * The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers. * The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
#include <iostream> #include <bitset> #include <climits> size_t popcount(unsigned long long n) { return std::bitset<CHAR_BIT * sizeof n>(n).count(); } int main() { { unsigned long long n = 1; for (int i = 0; i < 30; i++) { std::cout << popcount(n) << " "; n *= 3; } std::cout << std::endl; } int od[30]; int ne = 0, no = 0; std::cout << "evil : "; for (int n = 0; ne+no < 60; n++) { if ((popcount(n) & 1) == 0) { if (ne < 30) { std::cout << n << " "; ne++; } } else { if (no < 30) { od[no++] = n; } } } std::cout << std::endl; std::cout << "odious: "; for (int i = 0; i < 30; i++) { std::cout << od[i] << " "; } std::cout << std::endl; return 0; }
Prime triangle
C++
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements. ;See also :* OEIS:A036440
#include <cassert> #include <chrono> #include <iomanip> #include <iostream> #include <numeric> #include <vector> bool is_prime(unsigned int n) { assert(n > 0 && n < 64); return (1ULL << n) & 0x28208a20a08a28ac; } template <typename Iterator> bool prime_triangle_row(Iterator begin, Iterator end) { if (std::distance(begin, end) == 2) return is_prime(*begin + *(begin + 1)); for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); if (prime_triangle_row(begin + 1, end)) return true; std::iter_swap(i, begin + 1); } } return false; } template <typename Iterator> void prime_triangle_count(Iterator begin, Iterator end, int& count) { if (std::distance(begin, end) == 2) { if (is_prime(*begin + *(begin + 1))) ++count; return; } for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); prime_triangle_count(begin + 1, end, count); std::iter_swap(i, begin + 1); } } } template <typename Iterator> void print(Iterator begin, Iterator end) { if (begin == end) return; auto i = begin; std::cout << std::setw(2) << *i++; for (; i != end; ++i) std::cout << ' ' << std::setw(2) << *i; std::cout << '\n'; } int main() { auto start = std::chrono::high_resolution_clock::now(); for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); if (prime_triangle_row(v.begin(), v.end())) print(v.begin(), v.end()); } std::cout << '\n'; for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); int count = 0; prime_triangle_count(v.begin(), v.end(), count); if (n > 2) std::cout << ' '; std::cout << count; } std::cout << '\n'; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Priority queue
C++
A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. ;Task: Create a priority queue. The queue must support at least two operations: :# Insertion. An element is added to the queue with a priority (a numeric value). :# Top item removal. Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: '''Priority''' '''Task''' ---------- ---------------- 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
#include <iostream> #include <string> #include <queue> #include <utility> int main() { std::priority_queue<std::pair<int, std::string> > pq; pq.push(std::make_pair(3, "Clear drains")); pq.push(std::make_pair(4, "Feed cat")); pq.push(std::make_pair(5, "Make tea")); pq.push(std::make_pair(1, "Solve RC tasks")); pq.push(std::make_pair(2, "Tax return")); while (!pq.empty()) { std::cout << pq.top().first << ", " << pq.top().second << std::endl; pq.pop(); } return 0; }
Pseudo-random numbers/Combined recursive generator MRG32k3a
C++ from C
MRG32k3a Combined recursive generator (pseudo-code): /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of gen #1 */ x2 = [0, 0, 0] /* list of three last values of gen #2 */ method seed(u64 seed_state) assert seed_state in range >0 and < d x1 = [seed_state, 0, 0] x2 = [seed_state, 0, 0] end method method next_int() x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1 x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2 x1 = [x1i, x1[0], x1[1]] /* Keep last three */ x2 = [x2i, x2[0], x2[1]] /* Keep last three */ z = (x1i - x2i) % m1 answer = (z + 1) return answer end method method next_float(): return float next_int() / d end method end class :MRG32k3a Use: random_gen = instance MRG32k3a random_gen.seed(1234567) print(random_gen.next_int()) /* 1459213977 */ print(random_gen.next_int()) /* 2827710106 */ print(random_gen.next_int()) /* 4245671317 */ print(random_gen.next_int()) /* 3877608661 */ print(random_gen.next_int()) /* 2595287583 */ ;Task * Generate a class/set of functions that generates pseudo-random numbers as shown above. * Show that the first five integers generated with the seed `1234567` are as shown above * Show that for an initial seed of '987654321' the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931 * Show your output here, on this page.
#include <array> #include <iostream> int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } class RNG { private: // First generator const std::array<int64_t, 3> a1{ 0, 1403580, -810728 }; const int64_t m1 = (1LL << 32) - 209; std::array<int64_t, 3> x1; // Second generator const std::array<int64_t, 3> a2{ 527612, 0, -1370589 }; const int64_t m2 = (1LL << 32) - 22853; std::array<int64_t, 3> x2; // other const int64_t d = (1LL << 32) - 209 + 1; // m1 + 1 public: void seed(int64_t state) { x1 = { state, 0, 0 }; x2 = { state, 0, 0 }; } int64_t next_int() { int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); int64_t z = mod(x1i - x2i, m1); // keep last three values of the first generator x1 = { x1i, x1[0], x1[1] }; // keep last three values of the second generator x2 = { x2i, x2[0], x2[1] }; return z + 1; } double next_float() { return static_cast<double>(next_int()) / d; } }; int main() { RNG rng; rng.seed(1234567); std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << '\n'; std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; rng.seed(987654321); for (size_t i = 0; i < 100000; i++) { auto value = floor(rng.next_float() * 5.0); counts[value]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; } return 0; }
Pseudo-random numbers/Middle-square method
C++
{{Wikipedia|Middle-square method|en}} ; The Method: To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. ; Pseudo code: var seed = 675248 function random() var s = str(seed * seed) 'str: turn a number into string do while not len(s) = 12 s = "0" + s 'add zeroes before the string end do seed = val(mid(s, 4, 6)) 'mid: string variable, start, length 'val: turn a string into number return seed end function ; Middle-square method use: for i = 1 to 5 print random() end for ;Task: * Generate a class/set of functions that generates pseudo-random numbers (6 digits) as shown above. * Show the first five integers generated with the seed 675248 as shown above. * Show your output here, on this page.
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
Pseudo-random numbers/PCG32
C++ from C
Some definitions to help in the explanation: :Floor operation ::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions ::Greatest integer less than or equal to a real number. :Bitwise Logical shift operators (c-inspired) ::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts ::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. ::Examples are shown for 8 bit binary numbers; most significant bit to the left. :: '''<<''' Logical shift left by given number of bits. :::E.g Binary 00110101 '''<<''' 2 == Binary 11010100 :: '''>>''' Logical shift right by given number of bits. :::E.g Binary 00110101 '''>>''' 2 == Binary 00001101 :'''^''' Bitwise exclusive-or operator ::https://en.wikipedia.org/wiki/Exclusive_or ::Bitwise comparison for if bits differ :::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110 :'''|''' Bitwise or operator ::https://en.wikipedia.org/wiki/Bitwise_operation#OR ::Bitwise comparison gives 1 if any of corresponding bits are 1 :::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111 ;PCG32 Generator (pseudo-code): PCG32 has two unsigned 64-bit integers of internal state: # '''state''': All 2**64 values may be attained. # '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 ''different'' sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. ;Task: * Generate a class/set of functions that generates pseudo-random numbers using the above. * Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 * Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) :Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 * Show your output here, on this page.
#include <array> #include <iostream> class PCG32 { private: const uint64_t N = 6364136223846793005; uint64_t state = 0x853c49e6748fea9b; uint64_t inc = 0xda3e39cb94b95bdb; public: uint32_t nextInt() { uint64_t old = state; state = old * N + inc; uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27); uint32_t rot = old >> 59; return (shifted >> rot) | (shifted << ((~rot + 1) & 31)); } double nextFloat() { return ((double)nextInt()) / (1LL << 32); } void seed(uint64_t seed_state, uint64_t seed_sequence) { state = 0; inc = (seed_sequence << 1) | 1; nextInt(); state = state + seed_state; nextInt(); } }; int main() { auto r = new PCG32(); r->seed(42, 54); std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << '\n'; std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; r->seed(987654321, 1); for (size_t i = 0; i < 100000; i++) { int j = (int)floor(r->nextFloat() * 5.0); counts[j]++; } std::cout << "The counts for 100,000 repetitions are:\n"; for (size_t i = 0; i < counts.size(); i++) { std::cout << " " << i << " : " << counts[i] << '\n'; } return 0; }
Pseudo-random numbers/Xorshift star
C++ from C
Some definitions to help in the explanation: :Floor operation ::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions ::Greatest integer less than or equal to a real number. :Bitwise Logical shift operators (c-inspired) ::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts ::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. ::Examples are shown for 8 bit binary numbers; most significant bit to the left. :: '''<<''' Logical shift left by given number of bits. :::E.g Binary 00110101 '''<<''' 2 == Binary 11010100 :: '''>>''' Logical shift right by given number of bits. :::E.g Binary 00110101 '''>>''' 2 == Binary 00001101 :'''^''' Bitwise exclusive-or operator ::https://en.wikipedia.org/wiki/Exclusive_or ::Bitwise comparison for if bits differ :::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110 ;Xorshift_star Generator (pseudo-code): /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class :;Xorshift use: random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ ;Task: * Generate a class/set of functions that generates pseudo-random numbers as shown above. * Show that the first five integers genrated with the seed 1234567 are as shown above * Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) :Is as follows: 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 * Show your output here, on this page.
#include <array> #include <cstdint> #include <iostream> class XorShiftStar { private: const uint64_t MAGIC = 0x2545F4914F6CDD1D; uint64_t state; public: void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x >> 27); state = x; answer = ((x * MAGIC) >> 32); return answer; } float next_float() { return (float)next_int() / (1LL << 32); } }; int main() { auto rng = new XorShiftStar(); rng->seed(1234567); std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << '\n'; std::array<int, 5> counts = { 0, 0, 0, 0, 0 }; rng->seed(987654321); for (int i = 0; i < 100000; i++) { int j = (int)floor(rng->next_float() * 5.0); counts[j]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; } return 0; }
Pythagoras tree
C++
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. ;Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). ;Related tasks * Fractal tree
[[File:pythagoras_treeCpp.png|300px|thumb|]] Windows version
Pythagoras tree
C++ from Java
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. ;Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). ;Related tasks * Fractal tree
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100; 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 tree { public: tree() { bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear(); clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 ); clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 ); clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 ); } void draw( int it, POINT a, POINT b ) { if( !it ) return; bmp.setPenColor( clr[it % 6] ); POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x }; POINT d = { a.x - df.y, a.y - df.x }; POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )}; drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c ); } void save( std::string p ) { bmp.saveBitmap( p ); } private: void drawSqr( POINT a, POINT b, POINT c, POINT d ) { HDC dc = bmp.getDC(); MoveToEx( dc, a.x, a.y, NULL ); LineTo( dc, b.x, b.y ); LineTo( dc, c.x, c.y ); LineTo( dc, d.x, d.y ); LineTo( dc, a.x, a.y ); } myBitmap bmp; DWORD clr[6]; }; int main( int argc, char* argv[] ) { POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER }, ptB = { ptA.x + LINE_LEN, ptA.y }; tree t; t.draw( 12, ptA, ptB ); // change this path t.save( "?:/pt.bmp" ); return 0; }
Pythagorean quadruples
C++ from D
One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): :::::::: a2 + b2 + c2 = d2 An example: :::::::: 22 + 32 + 62 = 72 ::::: which is: :::::::: 4 + 9 + 36 = 49 ;Task: For positive integers up '''2,200''' (inclusive), for all values of '''a''', '''b''', '''c''', and '''d''', find (and show here) those values of '''d''' that ''can't'' be represented. Show the values of '''d''' on one line of output (optionally with a title). ;Related tasks: * [[Euler's sum of powers conjecture]]. * [[Pythagorean triples]]. ;Reference: :* the Wikipedia article: Pythagorean quadruple.
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { aabb[aa + b * b] = true; } } for (int c = 1; c <= N; ++c) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } } cout << "The values of d <= " << N << " which can't be represented:" << endl; for (int d = 1; d <= N; ++d) { if (!found[d]) { cout << d << " "; } } cout << endl; return 0; }
Pythagorean triples
C++
A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2. They are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\rm gcd}(a, b) = {\rm gcd}(a, c) = {\rm gcd}(b, c) = 1. Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\rm gcd}(a, b) = 1). Each triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c. ;Task: The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. ;Extra credit: Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner. ;Related tasks: * [[Euler's sum of powers conjecture]] * [[List comprehensions]] * [[Pythagorean quadruples]]
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } // The formulas below will generate primitive triples if: // 0 < n < m // m and n are relatively prime (gcd == 1) // m + n is odd auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; // This last one takes almost a minute for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
Quaternion type
C++
complex numbers. A complex number has a real and complex part, sometimes written as a + bi, where a and b stand for real numbers, and i stands for the square root of minus 1. An example of a complex number might be -3 + 2i, where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. A quaternion has one real part and ''three'' imaginary parts, i, j, and k. A quaternion might be written as a + bi + cj + dk. In the quaternion numbering system: :::* ii = jj = kk = ijk = -1, or more simply, :::* ii = jj = kk = ijk = -1. The order of multiplication is important, as, in general, for two quaternions: :::: q1 and q2: q1q2 q2q1. An example of a quaternion might be 1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. So the example above would be written as (1, 2, 3, 4) ;Task: Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number r = 7. Create functions (or classes) to perform simple maths with quaternions including computing: # The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2} # The negative of a quaternion: = (-a, -b, -c, -d) # The conjugate of a quaternion: = ( a, -b, -c, -d) # Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) # Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) # Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) # Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) # Show that, for the two quaternions q1 and q2: q1q2 q2q1 If a language has built-in support for quaternions, then use it. ;C.f.: * [[Vector products]] * On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#include <iostream> using namespace std; template<class T = double> class Quaternion { public: T w, x, y, z; // Numerical constructor Quaternion(const T &w, const T &x, const T &y, const T &z): w(w), x(x), y(y), z(z) {}; Quaternion(const T &x, const T &y, const T &z): w(T()), x(x), y(y), z(z) {}; // For 3-rotations Quaternion(const T &r): w(r), x(T()), y(T()), z(T()) {}; Quaternion(): w(T()), x(T()), y(T()), z(T()) {}; // Copy constructor and assignment Quaternion(const Quaternion &q): w(q.w), x(q.x), y(q.y), z(q.z) {}; Quaternion& operator=(const Quaternion &q) { w=q.w; x=q.x; y=q.y; z=q.z; return *this; } // Unary operators Quaternion operator-() const { return Quaternion(-w, -x, -y, -z); } Quaternion operator~() const { return Quaternion(w, -x, -y, -z); } // Conjugate // Norm-squared. SQRT would have to be made generic to be used here T normSquared() const { return w*w + x*x + y*y + z*z; } // In-place operators Quaternion& operator+=(const T &r) { w += r; return *this; } Quaternion& operator+=(const Quaternion &q) { w += q.w; x += q.x; y += q.y; z += q.z; return *this; } Quaternion& operator-=(const T &r) { w -= r; return *this; } Quaternion& operator-=(const Quaternion &q) { w -= q.w; x -= q.x; y -= q.y; z -= q.z; return *this; } Quaternion& operator*=(const T &r) { w *= r; x *= r; y *= r; z *= r; return *this; } Quaternion& operator*=(const Quaternion &q) { T oldW(w), oldX(x), oldY(y), oldZ(z); w = oldW*q.w - oldX*q.x - oldY*q.y - oldZ*q.z; x = oldW*q.x + oldX*q.w + oldY*q.z - oldZ*q.y; y = oldW*q.y + oldY*q.w + oldZ*q.x - oldX*q.z; z = oldW*q.z + oldZ*q.w + oldX*q.y - oldY*q.x; return *this; } Quaternion& operator/=(const T &r) { w /= r; x /= r; y /= r; z /= r; return *this; } Quaternion& operator/=(const Quaternion &q) { T oldW(w), oldX(x), oldY(y), oldZ(z), n(q.normSquared()); w = (oldW*q.w + oldX*q.x + oldY*q.y + oldZ*q.z) / n; x = (oldX*q.w - oldW*q.x + oldY*q.z - oldZ*q.y) / n; y = (oldY*q.w - oldW*q.y + oldZ*q.x - oldX*q.z) / n; z = (oldZ*q.w - oldW*q.z + oldX*q.y - oldY*q.x) / n; return *this; } // Binary operators based on in-place operators Quaternion operator+(const T &r) const { return Quaternion(*this) += r; } Quaternion operator+(const Quaternion &q) const { return Quaternion(*this) += q; } Quaternion operator-(const T &r) const { return Quaternion(*this) -= r; } Quaternion operator-(const Quaternion &q) const { return Quaternion(*this) -= q; } Quaternion operator*(const T &r) const { return Quaternion(*this) *= r; } Quaternion operator*(const Quaternion &q) const { return Quaternion(*this) *= q; } Quaternion operator/(const T &r) const { return Quaternion(*this) /= r; } Quaternion operator/(const Quaternion &q) const { return Quaternion(*this) /= q; } // Comparison operators, as much as they make sense bool operator==(const Quaternion &q) const { return (w == q.w) && (x == q.x) && (y == q.y) && (z == q.z); } bool operator!=(const Quaternion &q) const { return !operator==(q); } // The operators above allow quaternion op real. These allow real op quaternion. // Uses the above where appropriate. template<class T> friend Quaternion<T> operator+(const T &r, const Quaternion<T> &q); template<class T> friend Quaternion<T> operator-(const T &r, const Quaternion<T> &q); template<class T> friend Quaternion<T> operator*(const T &r, const Quaternion<T> &q); template<class T> friend Quaternion<T> operator/(const T &r, const Quaternion<T> &q); // Allows cout << q template<class T> friend ostream& operator<<(ostream &io, const Quaternion<T> &q); }; // Friend functions need to be outside the actual class definition template<class T> Quaternion<T> operator+(const T &r, const Quaternion<T> &q) { return q+r; } template<class T> Quaternion<T> operator-(const T &r, const Quaternion<T> &q) { return Quaternion<T>(r-q.w, q.x, q.y, q.z); } template<class T> Quaternion<T> operator*(const T &r, const Quaternion<T> &q) { return q*r; } template<class T> Quaternion<T> operator/(const T &r, const Quaternion<T> &q) { T n(q.normSquared()); return Quaternion(r*q.w/n, -r*q.x/n, -r*q.y/n, -r*q.z/n); } template<class T> ostream& operator<<(ostream &io, const Quaternion<T> &q) { io << q.w; (q.x < T()) ? (io << " - " << (-q.x) << "i") : (io << " + " << q.x << "i"); (q.y < T()) ? (io << " - " << (-q.y) << "j") : (io << " + " << q.y << "j"); (q.z < T()) ? (io << " - " << (-q.z) << "k") : (io << " + " << q.z << "k"); return io; }
Quine
C++
A quine is a self-referential program that can, without any external access, output its own source. A '''quine''' (named after Willard Van Orman Quine) is also known as: ::* ''self-reproducing automata'' (1972) ::* ''self-replicating program'' or ''self-replicating computer program'' ::* ''self-reproducing program'' or ''self-reproducing computer program'' ::* ''self-copying program'' or ''self-copying computer program'' It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. ;Task: Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: * Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. ** Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. ** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. * Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. ** If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. ** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. ** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. '''Next to the Quines presented here, many other versions can be found on the Quine page.''' ;Related task: :* print itself.
#include<cstdio> int main(){char n[]=R"(#include<cstdio> int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);}
RPG attributes generator
C++
'''RPG''' = Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: * The total of all character attributes must be at least 75. * At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. ;Task: Write a program that: # Generates 4 random, whole values between 1 and 6. # Saves the sum of the 3 largest values. # Generates a total of 6 values this way. # Displays the total, and all 6 values once finished. * The order in which each value was generated must be preserved. * The total of all 6 values must be at least 75. * At least 2 of the values must be 15 or more.
#include <algorithm> #include <ctime> #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { srand(time(0)); unsigned int attributes_total = 0; unsigned int count = 0; int attributes[6] = {}; int rolls[4] = {}; while(attributes_total < 75 || count < 2) { attributes_total = 0; count = 0; for(int attrib = 0; attrib < 6; attrib++) { for(int roll = 0; roll < 4; roll++) { rolls[roll] = 1 + (rand() % 6); } sort(rolls, rolls + 4); int roll_total = rolls[1] + rolls[2] + rolls[3]; attributes[attrib] = roll_total; attributes_total += roll_total; if(roll_total >= 15) count++; } } cout << "Attributes generated : ["; cout << attributes[0] << ", "; cout << attributes[1] << ", "; cout << attributes[2] << ", "; cout << attributes[3] << ", "; cout << attributes[4] << ", "; cout << attributes[5]; cout << "]\nTotal: " << attributes_total; cout << ", Values above 15 : " << count; return 0; }