Dataset Viewer
Auto-converted to Parquet Duplicate
title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
100 prisoners
C++
The Problem: * 100 prisoners are individually numbered 1 to 100 * A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. * Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. * Prisoners start outside the room :* They can d...
#include <cstdlib> // for rand #include <algorithm> // for random_shuffle #include <iostream> // for output using namespace std; class cupboard { public: cupboard() { for (int i = 0; i < 100; i++) drawers[i] = i; random_shuffle(drawers, drawers + 100); } bool playRandom(); ...
15 puzzle game
C++
Implement the Fifteen Puzzle Game. The '''15-puzzle''' is also known as: :::* '''Fifteen Puzzle''' :::* '''Gem Puzzle''' :::* '''Boss Puzzle''' :::* '''Game of Fifteen''' :::* '''Mystic Square''' :::* '''14-15 Puzzle''' :::* and some others. ;Related Tasks: :* 15 Puzzle Solver :* [[16 Puzzle ...
#include <time.h> #include <stdlib.h> #include <vector> #include <string> #include <iostream> class p15 { public : void play() { bool p = true; std::string a; while( p ) { createBrd(); while( !isDone() ) { drawBrd();getMove(); } drawBrd(); std:...
21 game
C++
'''21''' is a two player game, the game is played by choosing a number ('''1''', '''2''', or '''3''') to be added to the ''running total''. The game is won by the player whose chosen number causes the ''running total'' to reach ''exactly'' '''21'''. The ''running total'' starts at zero. One player will be the comp...
/** * Game 21 - an example in C++ language for Rosseta Code. * * This version is an example of MVP architecture. The user input, as well as * the AI opponent, is handled by separate passive subclasses of abstract class * named Controller. It can be noticed that the architecture support OCP, * for an example ...
24 game
C++11
The 24 Game tests one's mental arithmetic. ;Task Write a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The progr...
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; ...
4-rings or 4-squares puzzle
C++
Replace '''a, b, c, d, e, f,''' and '''g ''' with the decimal digits LOW ---> HIGH such that the sum of the letters inside of each of the four large squares add up to the same sum. +--------------+ +--------------+ | | | | |...
//C++14/17 #include <algorithm>//std::for_each #include <iostream> //std::cout #include <numeric> //std::iota #include <vector> //std::vector, save solutions #include <list> //std::list, for fast erase using std::begin, std::end, std::for_each; //Generates all the valid solutions for the problem in the specifi...
9 billion names of God the integer
C++
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a "name": :The integer 1 has 1 name "1". :The integer 2 has 2 names "1+1", and "2". :The integer 3 has 3 names "1+1+1", "2+1...
// Calculate hypotenuse n of OTT assuming only nothingness, unity, and hyp[n-1] if n>1 // Nigel Galloway, May 6th., 2013 #include <gmpxx.h> int N{123456}; mpz_class hyp[N-3]; const mpz_class G(const int n,const int g){return g>n?0:(g==1 or n-g<2)?1:hyp[n-g-2];}; void G_hyp(const int n){for(int i=0;i<N-2*n-1;i++) n==1?h...
A+B
C++
'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used. ;Task: Given two integers, '''A''' and '''B'''. Their sum needs to be calculated. ;Input data: Two integers are written in the input stream, separated by space(s...
// Input file: input.txt // Output file: output.txt #include <fstream> using namespace std; int main() { ifstream in("input.txt"); ofstream out("output.txt"); int a, b; in >> a >> b; out << a + b << endl; return 0; }
ABC problem
C++11
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks: (B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G...
#include <iostream> #include <vector> #include <string> #include <set> #include <cctype> typedef std::pair<char,char> item_t; typedef std::vector<item_t> list_t; bool can_make_word(const std::string& w, const list_t& vals) { std::set<uint32_t> used; while (used.size() < w.size()) { const char c = toup...
ASCII art diagram converter
C++
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | ...
#include <array> #include <bitset> #include <iostream> using namespace std; struct FieldDetails {string_view Name; int NumBits;}; // parses the ASCII diagram and returns the field name, bit sizes, and the // total byte size template <const char *T> consteval auto ParseDiagram() { // trim the ASCII diagram text...
AVL tree
C++ from D
{{wikipedia|AVL tree}} In computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletio...
#include <algorithm> #include <iostream> /* AVL node */ template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; ...
Abbreviations, automatic
C++ from C#
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an easy way to add flexibility when specifying or using commands, sub-commands, options, etc. It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if the minimum abbrevi...
#include <iomanip> #include <iostream> #include <fstream> #include <map> #include <sstream> #include <string> #include <vector> std::vector<std::string> split(const std::string& str, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(str); while (std::g...
Abbreviations, easy
C++
This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]]. For this task, the following ''command table'' will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTra...
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NF...
Abbreviations, simple
C++
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an easy way to add flexibility when specifying or using commands, sub-commands, options, etc. For this task, the following ''command table'' will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 chan...
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate...
Abelian sandpile model/Identity
C++
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addition on sandpiles is done ...
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostrea...
Abundant odd numbers
C++ from Go
An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''', or, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''. ;E.G.: '''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or ''...
#include <algorithm> #include <iostream> #include <numeric> #include <sstream> #include <vector> std::vector<int> divisors(int n) { std::vector<int> divs{ 1 }; std::vector<int> divs2; for (int i = 2; i*i <= n; i++) { if (n%i == 0) { int j = n / i; divs.push_back(i); ...
Accumulator factory
C++
{{requires|Mutable State}} A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed...
#include <iostream> class Acc { public: Acc(int init) : _type(intType) , _intVal(init) {} Acc(float init) : _type(floatType) , _floatVal(init) {} int operator()(int x) { if( _type == intType ) { _intVal += x; return _intV...
Accumulator factory
C++11
{{requires|Mutable State}} A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed...
// still inside struct Accumulator_ // various operator() implementations provide a de facto multimethod Accumulator_& operator()(int more) { if (auto i = CoerceInt(*val_)) Set(+i + more); else if (auto d = CoerceDouble(*val_)) Set(+d + more); else THROW("Accumulate(int) failed"); return *this; } ...
Aliquot sequence classifications
C++
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the [[Proper divisors]] of the previous term. :* If the terms eventually reach 0 then the series for K is said to '''terminate'''. :There are several classifications for non terminati...
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; // See https://en.wikipedia.org/wiki/Divisor_function integer divisor_sum(integer n) { integer total = 1, power = 2; // Deal with powers of 2 first for (; n % 2 == 0; power *= 2, n /= 2) total += power; // Odd p...
Amb
C++
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#include <iostream> #include <string_view> #include <boost/hana.hpp> #include <boost/hana/experimental/printable.hpp> using namespace std; namespace hana = boost::hana; // Define the Amb function. The first parameter is the constraint to be // enforced followed by the potential values. constexpr auto Amb(auto constr...
Anagrams/Deranged anagrams
C++
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words. ;Task Use the word list ...
#include <algorithm> #include <fstream> #include <functional> #include <iostream> #include <map> #include <numeric> #include <set> #include <string> bool is_deranged(const std::string& left, const std::string& right) { return (left.size() == right.size()) && (std::inner_product(left.begin(), left.end(), ri...
Angle difference between two bearings
C++
Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings] ;Task: Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. Input bearings are expressed in the range '''-180''...
#include <cmath> #include <iostream> using namespace std; double getDifference(double b1, double b2) { double r = fmod(b2 - b1, 360.0); if (r < -180.0) r += 360.0; if (r >= 180.0) r -= 360.0; return r; } int main() { cout << "Input in -180 to +180 range" << endl; cout << getDifference(20.0, 45.0) << endl; ...
Anti-primes
C++ from C
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. ;Task: Generate and show here, the first twenty anti-primes. ;Related tasks: :* [[Factors of an integer]] :* [[Sieve of Eratosthenes]]
#include <iostream> int countDivisors(int n) { if (n < 2) return 1; int count = 2; // 1 and n for (int i = 2; i <= n/2; ++i) { if (n%i == 0) ++count; } return count; } int main() { int maxDiv = 0, count = 0; std::cout << "The first 20 anti-primes are:" << std::endl; for (int n ...
Apply a digital filter (direct form II transposed)
C++
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma....
#include <vector> #include <iostream> using namespace std; void Filter(const vector<float> &b, const vector<float> &a, const vector<float> &in, vector<float> &out) { out.resize(0); out.resize(in.size()); for(int i=0; i < in.size(); i++) { float tmp = 0.; int j=0; out[i] = 0.f; for(j=0; j < b.size(); j++)...
Approximate equality
C++ from C
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by...
#include <iomanip> #include <iostream> #include <cmath> bool approxEquals(double a, double b, double e) { return fabs(a - b) < e; } void test(double a, double b) { constexpr double epsilon = 1e-18; std::cout << std::setprecision(21) << a; std::cout << ", "; std::cout << std::setprecision(21) << b;...
Archimedean spiral
C++
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: :\, r=a+b\theta with real numbers ''a'' and ''b''. ;Task Draw an Archimedean spiral.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
Arena storage pool
C++
Dynamically allocated objects take their memory from a [[heap]]. The memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]]. Often a call to allocator is denoted as P := new T where '''T''' is the type of an allocated object, and '''P''' is a [[referen...
#include <cstdlib> #include <cassert> #include <new> // This class basically provides a global stack of pools; it is not thread-safe, and pools must be destructed in reverse order of construction // (you definitely want something better in production use :-)) class Pool { public: Pool(std::size_type sz); ~Pool(); ...
Arithmetic-geometric mean
C++
{{wikipedia|Arithmetic-geometric mean}} ;Task: Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence: : a_0 = a; \qquad g_0 = g : a_{n+1} = \tfrac{1}{2}(a_n + g_...
#include<bits/stdc++.h> using namespace std; #define _cin ios_base::sync_with_stdio(0); cin.tie(0); #define rep(a, b) for(ll i =a;i<=b;++i) double agm(double a, double g) //ARITHMETIC GEOMETRIC MEAN { double epsilon = 1.0E-16,a1,g1; if(a*g<0.0) { cout<<"Couldn't find arithmetic-geometric mean of these numbers\n"; ...
Arithmetic numbers
C++
Definition A positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer. Clearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number...
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += ...
Array length
C++
Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'.
std::vector<std::string> fruitV({ "apples", "oranges" }); std::list<std::string> fruitL({ "apples", "oranges" }); std::deque<std::string> fruitD({ "apples", "oranges" }); std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;
Ascending primes
C++ from C
Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly is at least mildly interesting. T...
/* * Ascending primes * * Generate and show all primes with strictly ascending decimal digits. * * * Solution * * We only consider positive numbers in the range 1 to 123456789. We would * get 7027260 primes, because there are so many primes smaller than 123456789 * (see also Wolfram Alpha).On the other ...
Associative array/Merging
C++
Define two associative arrays, where one represents the following "base" data: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "name" || "Rocket Skates" |- | "price" || 12.75 |- | "color" || "yellow" |} And the other represents "update" data: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- ...
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; ...
Attractive numbers
C++ from C
A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime. ;Example: The number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime. ;Task: Show s...
#include <iostream> #include <iomanip> #define MAX 120 using namespace std; bool is_prime(int n) { if (n < 2) return false; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; int d = 5; while (d *d <= n) { if (!(n % d)) return false; d += 2; if (!(n % d)) return ...
Average loop length
C++
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 /** * Used to generate a uniform random distribution */ static std::random_device rd; //Will be used to obtain a seed for the random number engine static std::mt19937 gen(rd()); //Standard mersenne_twis...
Averages/Mean angle
C++ from C#
{{Related tasks/Statistical measures}}
#include <iomanip> #include <iostream> #include <vector> #define _USE_MATH_DEFINES #include <math.h> template<typename C> double meanAngle(const C& c) { auto it = std::cbegin(c); auto end = std::cend(c); double x = 0.0; double y = 0.0; double len = 0.0; while (it != end) { x += cos(*i...
Averages/Pythagorean means
C++
{{Related tasks/Statistical measures}}
#include <vector> #include <iostream> #include <numeric> #include <cmath> #include <algorithm> double toInverse ( int i ) { return 1.0 / i ; } int main( ) { std::vector<int> numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; double arithmetic_mean = std::accumulate( numbers.begin...
Averages/Root mean square
C++
Task Compute the Root mean square of the numbers 1..10. The ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''. The RMS is calculated as the mean of the squares of the numbers, square-rooted: ::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2}...
#include <iostream> #include <vector> #include <cmath> #include <numeric> int main( ) { std::vector<int> numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast<double>( numbers.si...
Babbage problem
C++
Charles Babbage Charles Babbage's analytical engine. Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: {{quote | What is the smallest positive integer whose square ends in the digits 269,696? | Babbage, letter to Lord Bowden, 1837; see Hollingdal...
#include <iostream> int main( ) { int current = 0 ; while ( ( current * current ) % 1000000 != 269696 ) current++ ; std::cout << "The square of " << current << " is " << (current * current) << " !\n" ; return 0 ; }
Balanced brackets
C++
'''Task''': * Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. * Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which ...
#include <algorithm> #include <iostream> #include <string> std::string generate(int n, char left = '[', char right = ']') { std::string str(std::string(n, left) + std::string(n, right)); std::random_shuffle(str.begin(), str.end()); return str; } bool balanced(const std::string &str, char left = '[', char ...
Balanced ternary
C++
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. ;Examples: Decimal 11 = 32 + 31 - 30, thus it can be written as "++-" Decimal 6 = 32 - 31 + 0 x 30, thus it can be written as "+...
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: // Store the value as a reversed string of +, 0 and - characters string value; // Helper function to change a balanced ternary character to an integer int charToInt(char c) const { if (c == '0') r...
Barnsley fern
C++
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). ;Task: Create this fractal fern, using the following transformations: * f1 (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn * f2 (chosen 85% of the time...
#include <windows.h> #include <ctime> #include <string> const int BMP_SIZE = 600, ITERATIONS = static_cast<int>( 15e5 ); class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObje...
Base64 decode data
C++14
See [[Base64 encode data]]. Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding....
#include <algorithm> #include <iostream> #include <string> #include <vector> typedef unsigned char ubyte; const auto BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::vector<ubyte> encode(const std::vector<ubyte>& source) { auto it = source.cbegin(); auto end = source.cend(); ...
Benford's law
C++
{{Wikipedia|Benford's_law}} '''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less...
//to cope with the big numbers , I used the Class Library for Numbers( CLN ) //if used prepackaged you can compile writing "g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram" #include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <s...
Best shuffle
C++ from Java
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Di...
#include <iostream> #include <sstream> #include <algorithm> using namespace std; template <class S> class BestShuffle { public: BestShuffle() : rd(), g(rd()) {} S operator()(const S& s1) { S s2 = s1; shuffle(s2.begin(), s2.end(), g); for (unsigned i = 0; i < s2.length(); i++) ...
Bin given limits
C++
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1]...
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> std::vector<int> bins(const std::vector<int>& limits, const std::vector<int>& data) { std::vector<int> result(limits.size() + 1, 0); for (int n : data) { auto i = std::upper_bound(limi...
Bioinformatics/Sequence mutation
C++
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: # Choosing a random base position in the sequence. # Mutate the sequence by doing one of either: ## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chan...
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum ...
Bioinformatics/base count
C++
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCA...
Brazilian numbers
C++ from D
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1'...
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
Break OO privacy
C++
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that ...
#include <iostream> class CWidget; // Forward-declare that we have a class named CWidget. class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); // Disallow the d...
Burrows–Wheeler transform
C++ from C#
{{Wikipedia|Burrows-Wheeler_transform}} The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as ...
#include <algorithm> #include <iostream> #include <vector> const int STX = 0x02; const int ETX = 0x03; void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; } std::string bwt(const std::string &s) { for (char c : ...
CSV data manipulation
C++
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. ;Task: Read a CSV file, change some values and save the ...
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) ...
CSV to HTML translation
C++
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be ''escaped'' when converted to HTML ;Task: Create a function that ta...
#include <string> #include <boost/regex.hpp> #include <iostream> std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the mess...
Calculating the value of e
C++ from C
Calculate the value of ''e''. (''e'' is also known as ''Euler's number'' and ''Napier's constant''.) See details: Calculating the value of e
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { const double EPSILON = 1.0e-15; unsigned long long fact = 1; double e = 2.0, e0; int n = 2; do { e0 = e; fact *= n++; e += 1.0 / fact; } while (fabs(e - e0) >= EPSILON); co...
Call a function
C++
Demonstrate the different syntax and semantics provided for calling a function. This may include: :* Calling a function that requires no arguments :* Calling a function with a fixed number of arguments :* Calling a function with optional arguments :* Calling a function with a variable number of arguments :* ...
#include <iostream> using namespace std; /* passing arguments by reference */ void f(int &y) /* variable is now passed by reference */ { y++; } int main() { int x = 0; cout<<"x = "<<x<<endl; /* should produce result "x = 0" */ f(x); /* call function f */ cout<<"x = "<<x<<endl; /* should produce result ...
Canonicalize CIDR
C++
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. ;Example: Given '''...
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> // Class representing an IPv4 address + netmask length class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t add...
Cantor set
C++ from D
Draw a Cantor set. See details at this Wikipedia webpage: Cantor set
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] =...
Cartesian product of two or more lists
C++
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: ::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: ::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using you...
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto pro...
End of preview. Expand in Data Studio

Data Origins

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

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

Data Fields

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

Languages

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

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

Total 4894 done 565 skip 4329 failed 0 rows 4263
Downloads last month
52