title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Determine if two triangles overlap
C++
Determining if two triangles in the same plane overlap is an important topic in collision detection. ;Task: Determine which of these pairs of triangles overlap in 2D: :::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6) :::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0) :::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6) :::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4) :::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2) :::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer): :::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
#include <vector> #include <iostream> #include <stdexcept> using namespace std; typedef std::pair<double, double> TriPoint; inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3) { return +p1.first*(p2.second-p3.second) +p2.first*(p3.second-p1.second) +p3.first*(p1.second-p2.second); } void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed) { double detTri = Det2D(p1, p2, p3); if(detTri < 0.0) { if (allowReversed) { TriPoint a = p3; p3 = p2; p2 = a; } else throw std::runtime_error("triangle has wrong winding direction"); } } bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) < eps; } bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps) { return Det2D(p1, p2, p3) <= eps; } bool TriTri2D(TriPoint *t1, TriPoint *t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { //Trangles must be expressed anti-clockwise CheckTriWinding(t1[0], t1[1], t1[2], allowReversed); CheckTriWinding(t2[0], t2[1], t2[2], allowReversed); bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL; if(onBoundary) //Points on the boundary are considered as colliding chkEdge = BoundaryCollideChk; else //Points on the boundary are not considered as colliding chkEdge = BoundaryDoesntCollideChk; //For edge E of trangle 1, for(int i=0; i<3; i++) { int j=(i+1)%3; //Check all points of trangle 2 lay on the external side of the edge E. If //they do, the triangles do not collide. if (chkEdge(t1[i], t1[j], t2[0], eps) && chkEdge(t1[i], t1[j], t2[1], eps) && chkEdge(t1[i], t1[j], t2[2], eps)) return false; } //For edge E of trangle 2, for(int i=0; i<3; i++) { int j=(i+1)%3; //Check all points of trangle 1 lay on the external side of the edge E. If //they do, the triangles do not collide. if (chkEdge(t2[i], t2[j], t1[0], eps) && chkEdge(t2[i], t2[j], t1[1], eps) && chkEdge(t2[i], t2[j], t1[2], eps)) return false; } //The triangles collide return true; } int main() { {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)}; cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)}; TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)}; TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)}; cout << TriTri2D(t1, t2) << "," << true << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)}; cout << TriTri2D(t1, t2) << "," << false << endl;} {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)}; TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)}; cout << TriTri2D(t1, t2) << "," << false << endl;} //Barely touching {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;} //Barely touching {TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)}; TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)}; cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;} }
Dice game probabilities
C++
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> // Returns map from sum of faces to number of ways it can happen std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; } double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; } int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
Digital root
C++
The digital root, X, of a number, n, is calculated: : find X as the sum of the digits of n : find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: :627615 has additive persistence 2 and digital root of 9; :39390 has additive persistence 2 and digital root of 6; :588225 has additive persistence 2 and digital root of 3; :393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. ;See: * [[Casting out nines]] for this wiki's use of this procedure. * [[Digital root/Multiplicative digital root]] * [[Sum digits of an integer]] * Digital root sequence on OEIS * Additive persistence sequence on OEIS * [[Iterated digits squaring]]
// Calculate the Digital Root and Additive Persistance of an Integer - Compiles with gcc4.7 // // Nigel Galloway. July 23rd., 2012 // #include <iostream> #include <cmath> #include <utility> template<class P_> P_ IncFirst(const P_& src) {return P_(src.first + 1, src.second);} std::pair<int, int> DigitalRoot(unsigned long long digits, int base = 10) { int x = SumDigits(digits, base); return x < base ? std::make_pair(1, x) : IncFirst(DigitalRoot(x, base)); // x is implicitly converted to unsigned long long; this is lossless } int main() { const unsigned long long ip[] = {961038,923594037444,670033,448944221089}; for (auto i:ip){ auto res = DigitalRoot(i); std::cout << i << " has digital root " << res.second << " and additive persistance " << res.first << "\n"; } std::cout << "\n"; const unsigned long long hip[] = {0x7e0,0x14e344,0xd60141,0x12343210}; for (auto i:hip){ auto res = DigitalRoot(i,16); std::cout << std::hex << i << " has digital root " << res.second << " and additive persistance " << res.first << "\n"; } return 0; }
Disarium numbers
C++
A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. ;E.G. '''135''' is a '''Disarium number''': 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of '''Disarium numbers'''. ;Task * Find and display the first 18 '''Disarium numbers'''. ;Stretch * Find and display all 20 '''Disarium numbers'''. ;See also ;* Geeks for Geeks - Disarium numbers ;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) ;* Related task: Narcissistic decimal number ;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
#include <vector> #include <iostream> #include <cmath> #include <algorithm> std::vector<int> decompose( int n ) { std::vector<int> digits ; while ( n != 0 ) { digits.push_back( n % 10 ) ; n /= 10 ; } std::reverse( digits.begin( ) , digits.end( ) ) ; return digits ; } bool isDisarium( int n ) { std::vector<int> digits( decompose( n ) ) ; int exposum = 0 ; for ( int i = 1 ; i < digits.size( ) + 1 ; i++ ) { exposum += static_cast<int>( std::pow( static_cast<double>(*(digits.begin( ) + i - 1 )) , static_cast<double>(i) )) ; } return exposum == n ; } int main( ) { std::vector<int> disariums ; int current = 0 ; while ( disariums.size( ) != 18 ){ if ( isDisarium( current ) ) disariums.push_back( current ) ; current++ ; } for ( int d : disariums ) std::cout << d << " " ; std::cout << std::endl ; return 0 ; }
Display a linear combination
C++ from D
Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots). Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is: :\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots where \alpha^{i_k}\neq 0 The output must comply to the following rules: * don't show null terms, unless the whole combination is null. ::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong. * don't show scalars when they are equal to one or minus one. ::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong. * don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. ::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
#include <iomanip> #include <iostream> #include <sstream> #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::ostream& operator<<(std::ostream& os, const std::string& s) { return os << s.c_str(); } std::string linearCombo(const std::vector<int>& c) { std::stringstream ss; for (size_t i = 0; i < c.size(); i++) { int n = c[i]; if (n < 0) { if (ss.tellp() == 0) { ss << '-'; } else { ss << " - "; } } else if (n > 0) { if (ss.tellp() != 0) { ss << " + "; } } else { continue; } int av = abs(n); if (av != 1) { ss << av << '*'; } ss << "e(" << i + 1 << ')'; } if (ss.tellp() == 0) { return "0"; } return ss.str(); } int main() { using namespace std; vector<vector<int>> combos{ {1, 2, 3}, {0, 1, 2, 3}, {1, 0, 3, 4}, {1, 2, 0}, {0, 0, 0}, {0}, {1, 1, 1}, {-1, -1, -1}, {-1, -2, 0, -3}, {-1}, }; for (auto& c : combos) { stringstream ss; ss << c; cout << setw(15) << ss.str() << " -> "; cout << linearCombo(c) << '\n'; } return 0; }
Diversity prediction theorem
C++
The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies. Scott E. Page introduced the diversity prediction theorem: : ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. Therefore, when the diversity in a group is large, the error of the crowd is small. ;Definitions: ::* Average Individual Error: Average of the individual squared errors ::* Collective Error: Squared error of the collective prediction ::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction ::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then :::::: Collective Error = Average Individual Error - Prediction Diversity ;Task: For a given true value and a number of number of estimates (from a crowd), show (here on this page): :::* the true value and the crowd estimates :::* the average error :::* the crowd error :::* the prediction diversity Use (at least) these two examples: :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51''' :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42''' ;Also see: :* Wikipedia entry: Wisdom of the crowd :* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
#include <iostream> #include <vector> #include <numeric> float sum(const std::vector<float> &array) { return std::accumulate(array.begin(), array.end(), 0.0); } float square(float x) { return x * x; } float mean(const std::vector<float> &array) { return sum(array) / array.size(); } float averageSquareDiff(float a, const std::vector<float> &predictions) { std::vector<float> results; for (float x : predictions) results.push_back(square(x - a)); return mean(results); } void diversityTheorem(float truth, const std::vector<float> &predictions) { float average = mean(predictions); std::cout << "average-error: " << averageSquareDiff(truth, predictions) << "\n" << "crowd-error: " << square(truth - average) << "\n" << "diversity: " << averageSquareDiff(average, predictions) << std::endl; } int main() { diversityTheorem(49, {48,47,51}); diversityTheorem(49, {48,47,51,42}); return 0; }
Doomsday rule
C++
About the task John Conway (1937-2020), was a mathematician who also invented several mathematically oriented computer pastimes, such as the famous Game of Life cellular automaton program. Dr. Conway invented a simple algorithm for finding the day of the week, given any date. The algorithm was based on calculating the distance of a given date from certain "anchor days" which follow a pattern for the day of the week upon which they fall. ; Algorithm The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7 which, for 2021, is 0 (Sunday). To calculate the day of the week, we then count days from a close doomsday, with these as charted here by month, then add the doomsday for the year, then get the remainder after dividing by 7. This should give us the number corresponding to the day of the week for that date. Month Doomsday Dates for Month -------------------------------------------- January (common years) 3, 10, 17, 24, 31 January (leap years) 4, 11, 18, 25 February (common years) 7, 14, 21, 28 February (leap years) 1, 8, 15, 22, 29 March 7, 14, 21, 28 April 4, 11, 18, 25 May 2, 9, 16, 23, 30 June 6, 13, 20, 27 July 4, 11, 18, 25 August 1, 8, 15, 22, 29 September 5, 12, 19, 26 October 3, 10, 17, 24, 31 November 7, 14, 21, 28 December 5, 12, 19, 26 ; Task Given the following dates: * 1800-01-06 (January 6, 1800) * 1875-03-29 (March 29, 1875) * 1915-12-07 (December 7, 1915) * 1970-12-23 (December 23, 1970) * 2043-05-14 (May 14, 2043) * 2077-02-12 (February 12, 2077) * 2101-04-02 (April 2, 2101) Use Conway's Doomsday rule to calculate the day of the week for each date. ; see also * Doomsday rule * Tomorrow is the Day After Doomsday (p.28)
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const std::string days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned const c = date.year/100, r = date.year%100; unsigned const s = r/12, t = r%12; unsigned const c_anchor = (5 * (c%4) + 2) % 7; unsigned const doom = (s + t + t/4 + c_anchor) % 7; unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const std::string months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; for (const Date& d : dates) { std::cout << months[d.month] << " " << (int)d.day << ", " << d.year; std::cout << (d.year > 2021 ? " will be " : " was "); std::cout << "on a " << weekday(d) << std::endl; } return 0; }
Dot product
C++
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
#include <iostream> #include <numeric> int main() { int a[] = { 1, 3, -5 }; int b[] = { 4, -2, -1 }; std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl; return 0; }
Draw a clock
C++
Draw a clock. More specific: # Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. # The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. # A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. # A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. ;Key points * animate simple object * timed event * polling system resources * code clarity
#include <windows.h> #include <string> #include <math.h> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20, MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20; const float PI = 3.1415926536f; //-------------------------------------------------------------------------------------------------- class vector2 { public: vector2() { x = y = 0; } vector2( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { float _x = static_cast<float>( x ), _y = static_cast<float>( y ), s = sinf( angle_r ), c = cosf( angle_r ), a = _x * c - _y * s, b = _x * s + _y * c; x = static_cast<int>( a ); y = static_cast<int>( b ); } int 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 clock { public: clock() { _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear( 100 ); _bmp.setPenWidth( 2 ); _ang = DegToRadian( 6 ); } void setNow() { GetLocalTime( &_sysTime ); draw(); } float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: void drawTicks( HDC dc ) { vector2 line; _bmp.setPenWidth( 1 ); for( int x = 0; x < 60; x++ ) { line.set( 0, 50 ); line.rotate( static_cast<float>( x + 30 ) * _ang ); MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL ); LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) ); } _bmp.setPenWidth( 3 ); for( int x = 0; x < 60; x += 5 ) { line.set( 0, 50 ); line.rotate( static_cast<float>( x + 30 ) * _ang ); MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL ); LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) ); } } void drawHands( HDC dc ) { float hp = DegToRadian( ( 30.0f * static_cast<float>( _sysTime.wMinute ) ) / 60.0f ); int h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5; _bmp.setPenWidth( 3 ); _bmp.setPenColor( RGB( 0, 0, 255 ) ); drawHand( dc, HOUR_LEN, ( _ang * static_cast<float>( 30 + h ) ) + hp ); _bmp.setPenColor( RGB( 0, 128, 0 ) ); drawHand( dc, MIN_LEN, _ang * static_cast<float>( 30 + _sysTime.wMinute ) ); _bmp.setPenWidth( 2 ); _bmp.setPenColor( RGB( 255, 0, 0 ) ); drawHand( dc, SEC_LEN, _ang * static_cast<float>( 30 + _sysTime.wSecond ) ); } void drawHand( HDC dc, int len, float ang ) { vector2 line; line.set( 0, len ); line.rotate( ang ); MoveToEx( dc, CENTER, CENTER, NULL ); LineTo( dc, line.x + CENTER, line.y + CENTER ); } void draw() { HDC dc = _bmp.getDC(); _bmp.setBrushColor( RGB( 250, 250, 250 ) ); Ellipse( dc, 0, 0, BMP_SIZE, BMP_SIZE ); _bmp.setBrushColor( RGB( 230, 230, 230 ) ); Ellipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 ); drawTicks( dc ); drawHands( dc ); _bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 ); Ellipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 ); _wdc = GetDC( _hwnd ); BitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, _wdc ); } myBitmap _bmp; HWND _hwnd; HDC _wdc; SYSTEMTIME _sysTime; float _ang; }; //-------------------------------------------------------------------------------------------------- class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); SetTimer( _hwnd, MY_TIMER, 1000, NULL ); _clock.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_CLOCK_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _clock.setNow(); } void wnd::doTimer() { _clock.setNow(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_PAINT: { PAINTSTRUCT ps; HDC dc = BeginPaint( hWnd, &ps ); _inst->doPaint( dc ); EndPaint( hWnd, &ps ); return 0; } 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_CLOCK_"; 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_CLOCK_", ".: Clock -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; clock _clock; }; wnd* wnd::_inst = 0; //-------------------------------------------------------------------------------------------------- int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); } //--------------------------------------------------------------------------------------------------
Duffinian numbers
C++
A '''Duffinian number''' is a composite number '''k''' that is relatively prime to its sigma sum '''s'''. ''The sigma sum of '''k''' is the sum of the divisors of '''k'''.'' ;E.G. '''161''' is a '''Duffinian number'''. * It is composite. (7 x 23) * The sigma sum '''192''' (1 + 7 + 23 + 161) is relatively prime to '''161'''. Duffinian numbers are very common. It is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc. Less common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc. Much, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045). It is not possible to have six consecutive Duffinian numbers ;Task * Find and show the first 50 Duffinian numbers. * Find and show at least the first 15 Duffinian triplets. ;See also ;* Numbers Aplenty - Duffinian numbers ;* OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)
#include <iomanip> #include <iostream> #include <numeric> #include <sstream> bool duffinian(int n) { if (n == 2) return false; int total = 1, power = 2, m = n; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (int p = 3; p * p <= n; p += 2) { int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (m == n) return false; if (n > 1) total *= n + 1; return std::gcd(total, m) == 1; } int main() { std::cout << "First 50 Duffinian numbers:\n"; for (int n = 1, count = 0; count < 50; ++n) { if (duffinian(n)) std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\n' : ' '); } std::cout << "\nFirst 50 Duffinian triplets:\n"; for (int n = 1, m = 0, count = 0; count < 50; ++n) { if (duffinian(n)) ++m; else m = 0; if (m == 3) { std::ostringstream os; os << '(' << n - 2 << ", " << n - 1 << ", " << n << ')'; std::cout << std::left << std::setw(24) << os.str() << (++count % 3 == 0 ? '\n' : ' '); } } std::cout << '\n'; }
Dutch national flag problem
C++
The Dutch national flag is composed of three coloured bands in the order: ::* red (top) ::* then white, and ::* lastly blue (at the bottom). The problem posed by Edsger Dijkstra is: :Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... ;Task # Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''. # Sort the balls in a way idiomatic to your language. # Check the sorted balls ''are'' in the order of the Dutch national flag. ;C.f.: * Dutch national flag problem * Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#include <algorithm> #include <iostream> // Dutch national flag problem template <typename BidIt, typename T> void dnf_partition(BidIt first, BidIt last, const T& low, const T& high) { for (BidIt next = first; next != last; ) { if (*next < low) { std::iter_swap(first++, next++); } else if (!(*next < high)) { std::iter_swap(next, --last); } else { ++next; } } } enum Colors { RED, WHITE, BLUE }; void print(const Colors *balls, size_t size) { static const char *label[] = { "red", "white", "blue" }; std::cout << "Balls:"; for (size_t i = 0; i < size; ++i) { std::cout << ' ' << label[balls[i]]; } std::cout << "\nSorted: " << std::boolalpha << std::is_sorted(balls, balls + size) << '\n'; } int main() { Colors balls[] = { RED, WHITE, BLUE, RED, WHITE, BLUE, RED, WHITE, BLUE }; std::random_shuffle(balls, balls + 9); print(balls, 9); dnf_partition(balls, balls + 9, WHITE, BLUE); print(balls, 9); }
Eban numbers
C++ from D
Definition: An '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English. Or more literally, spelled numbers that contain the letter '''e''' are banned. The American version of spelling numbers will be used here (as opposed to the British). '''2,000,000,000''' is two billion, ''not'' two milliard. Only numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task. This will allow optimizations to be used. ;Task: :::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count :::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count :::* show a count of all eban numbers up and including '''10,000''' :::* show a count of all eban numbers up and including '''100,000''' :::* show a count of all eban numbers up and including '''1,000,000''' :::* show a count of all eban numbers up and including '''10,000,000''' :::* show all output here. ;See also: :* The MathWorld entry: eban numbers. :* The OEIS entry: A6933, eban numbers. :* [[Number names]].
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, {2, 1000000000, false}, }; for (auto intv : intervals) { if (intv.start == 2) { std::cout << "eban numbers up to and including " << intv.end << ":\n"; } else { std::cout << "eban numbers bwteen " << intv.start << " and " << intv.end << " (inclusive):\n"; } int count = 0; for (int i = intv.start; i <= intv.end; i += 2) { int b = i / 1000000000; int r = i % 1000000000; int m = r / 1000000; r = i % 1000000; int t = r / 1000; r %= 1000; if (m >= 30 && m <= 66) m %= 10; if (t >= 30 && t <= 66) t %= 10; if (r >= 30 && r <= 66) r %= 10; if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (intv.print) std::cout << i << ' '; count++; } } } } } if (intv.print) { std::cout << '\n'; } std::cout << "count = " << count << "\n\n"; } return 0; }
Eertree
C++ from D
An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both ''tries'' and ''suffix trees''. See links below. ;Task: Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. ;See also: * Wikipedia entry: trie. * Wikipedia entry: suffix tree * Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { /* empty */ } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { /* empty */ } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
Egyptian division
C++ from C
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
#include <cassert> #include <iostream> typedef unsigned long ulong; /* * Remainder is an out paramerter. Use nullptr if the remainder is not needed. */ ulong egyptian_division(ulong dividend, ulong divisor, ulong* remainder) { constexpr int SIZE = 64; ulong powers[SIZE]; ulong doublings[SIZE]; int i = 0; for (; i < SIZE; ++i) { powers[i] = 1 << i; doublings[i] = divisor << i; if (doublings[i] > dividend) { break; } } ulong answer = 0; ulong accumulator = 0; for (i = i - 1; i >= 0; --i) { /* * If the current value of the accumulator added to the * doublings cell would be less than or equal to the * dividend then add it to the accumulator */ if (accumulator + doublings[i] <= dividend) { accumulator += doublings[i]; answer += powers[i]; } } if (remainder) { *remainder = dividend - accumulator; } return answer; } void print(ulong a, ulong b) { using namespace std; ulong x, y; x = egyptian_division(a, b, &y); cout << a << " / " << b << " = " << x << " remainder " << y << endl; assert(a == b * x + y); } int main() { print(580, 34); return 0; }
Elementary cellular automaton
C++
An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. ;Task: Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of [[one-dimensional cellular automata]]. ;See also * Cellular automata (natureofcode.com)
#include <bitset> #include <stdio.h> #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x))) void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] ); for (i = 1; i < SIZE-1; i++) t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] ); for (i = 0; i < SIZE; i++) s[i] = t[i]; } void show(std::bitset<SIZE> s) { int i; for (i = SIZE; --i; ) printf("%c", s[i] ? '#' : ' '); printf("\n"); } int main() { int i; std::bitset<SIZE> state(1); state <<= SIZE / 2; for (i=0; i<10; i++) { show(state); evolve(state); } return 0; }
Elementary cellular automaton/Infinite length
C++
The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#include <iostream> #include <iomanip> #include <string> class oo { public: void evolve( int l, int rule ) { std::string cells = "O"; std::cout << " Rule #" << rule << ":\n"; for( int x = 0; x < l; x++ ) { addNoCells( cells ); std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n"; step( cells, rule ); } } private: void step( std::string& cells, int rule ) { int bin; std::string newCells; for( size_t i = 0; i < cells.length() - 2; i++ ) { bin = 0; for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) { bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b ); } newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' ); } cells = newCells; } void addNoCells( std::string& s ) { char l = s.at( 0 ) == 'O' ? '.' : 'O', r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O'; s = l + s + r; s = l + s + r; } }; int main( int argc, char* argv[] ) { oo o; o.evolve( 35, 90 ); std::cout << "\n"; return 0; }
Elementary cellular automaton/Random number generator
C++
Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. ;Reference: * Cellular automata: Is Rule 30 random? (PDF).
#include <bitset> #include <stdio.h> #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x))) void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] ); for (i = 1; i < SIZE-1; i++) t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] ); for (i = 0; i < SIZE; i++) s[i] = t[i]; } void show(std::bitset<SIZE> s) { int i; for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' '); printf("|\n"); } unsigned char byte(std::bitset<SIZE> &s) { unsigned char b = 0; int i; for (i=8; i--; ) { b |= s[0] << i; evolve(s); } return b; } int main() { int i; std::bitset<SIZE> state(1); for (i=10; i--; ) printf("%u%c", byte(state), i ? ' ' : '\n'); return 0; }
Elliptic curve arithmetic
C++
digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve: :::: y^2 = x^3 + a x + b '''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters: :::: a=0, b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. To do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have: :::: P + Q + R = 0 Here '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. We'll also assume here that this infinity point is unique and defines the neutral element of the addition. This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such: Given any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet). '''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven. ''Hint'': You might need to define a "doubling" function, that returns '''P+P''' for any given point '''P'''. ''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).
#include <cmath> #include <iostream> using namespace std; // define a type for the points on the elliptic curve that behaves // like a built in type. class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; // the 'b' in y^2 = x^3 + a * x + b // 'a' is 0 void Double() noexcept { if(IsZero()) { // doubling zero is still zero return; } // based on the property of the curve, the line going through the // current point and the negative doubled point is tangent to the // curve at the current point. wikipedia has a nice diagram. if(m_y == 0) { // at this point the tangent to the curve is vertical. // this point doubled is 0 *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); // Create a point that is initialized to Zero constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} // Create a point based on the yCoordiante. For a curve with a = 0 and b = 7 // there is only one x for each y explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } // Check if the point is 0 bool IsZero() const noexcept { // when the elliptic point is at 0, y = +/- infinity bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } // make a negative version of the point (p = -q) EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } // add a point to this one ( p+=q ) EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { // since rhs is zero this point does not need to be // modified } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { // in this case rhs == -lhs, the result should be 0 *this = EllipticPoint(); } else { // in this case rhs == lhs. Double(); } } } return *this; } // subtract a point from this one (p -= q) EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } // multiply the point by an integer (p *= 3) EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { // change p * -rhs to -p * rhs rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; // add points (p + q) inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } // subtract points (p - q) inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } // multiply by an integer (p * 3) inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } // multiply by an integer (3 * p) inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } // print the point ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); // the point where the curve crosses the x-axis cout << "special = " << special; // this has the minimum possible value for x cout << "special *= 2 = " << (special*=2); // doubling it gives zero return 0; }
Empty string
C++
Languages may have features for dealing specifically with empty strings (those containing no characters). ;Task: ::* Demonstrate how to assign an empty string to a variable. ::* Demonstrate how to check that a string is empty. ::* Demonstrate how to check that a string is not empty.
#include <string> // ... // empty string declaration std::string str; // (default constructed) std::string str(); // (default constructor, no parameters) std::string str{}; // (default initialized) std::string str(""); // (const char[] conversion) std::string str{""}; // (const char[] initializer list) if (str.empty()) { ... } // to test if string is empty // we could also use the following if (str.length() == 0) { ... } if (str == "") { ... } // make a std::string empty str.clear(); // (builtin clear function) str = ""; // replace contents with empty string str = {}; // swap contents with temp string (empty),then destruct temp // swap with empty string std::string tmp{}; // temp empty string str.swap(tmp); // (builtin swap function) std::swap(str, tmp); // swap contents with tmp // create an array of empty strings std::string s_array[100]; // 100 initialized to "" (fixed size) std::array<std::string, 100> arr; // 100 initialized to "" (fixed size) std::vector<std::string>(100,""); // 100 initialized to "" (variable size, 100 starting size) // create empty string as default parameter void func( std::string& s = {} ); // {} generated default std:string instance
Entropy/Narcissist
C++
Write a computer program that computes and shows its own [[entropy]]. ;Related Tasks: :* [[Fibonacci_word]] :* [[Entropy]]
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
Equilibrium index
C++
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence A: ::::: A_0 = -7 ::::: A_1 = 1 ::::: A_2 = 5 ::::: A_3 = 2 ::::: A_4 = -4 ::::: A_5 = 3 ::::: A_6 = 0 3 is an equilibrium index, because: ::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6 6 is also an equilibrium index, because: ::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. ;Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#include <algorithm> #include <iostream> #include <numeric> #include <vector> template <typename T> std::vector<size_t> equilibrium(T first, T last) { typedef typename std::iterator_traits<T>::value_type value_t; value_t left = 0; value_t right = std::accumulate(first, last, value_t(0)); std::vector<size_t> result; for (size_t index = 0; first != last; ++first, ++index) { right -= *first; if (left == right) { result.push_back(index); } left += *first; } return result; } template <typename T> void print(const T& value) { std::cout << value << "\n"; } int main() { const int data[] = { -7, 1, 5, 2, -4, 3, 0 }; std::vector<size_t> indices(equilibrium(data, data + 7)); std::for_each(indices.begin(), indices.end(), print<size_t>); }
Erdős-Nicolas numbers
C++ from ALGOL 68
Definition An perfect but is equal to the sum of its first '''k''' divisors (arranged in ascending order and including one) for some value of '''k''' greater than one. ;Examples 24 is an Erdos-Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor. 6 is not an Erdos-Nicolas number because it is perfect (1 + 2 + 3 = 6). 48 is not an Erdos-Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48. ;Task Find and show here the first 8 Erdos-Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition. ;Stretch Do the same for any further Erdos-Nicolas numbers which you have the patience for. ;Note As all known Erdos-Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case. ;Reference * OEIS:A194472 - Erdos-Nicolas numbers
#include <iomanip> #include <iostream> #include <vector> int main() { const int max_number = 100000000; std::vector<int> dsum(max_number + 1, 1); std::vector<int> dcount(max_number + 1, 1); for (int i = 2; i <= max_number; ++i) { for (int j = i + i; j <= max_number; j += i) { if (dsum[j] == j) { std::cout << std::setw(8) << j << " equals the sum of its first " << dcount[j] << " divisors\n"; } dsum[j] += i; ++dcount[j]; } } }
Esthetic numbers
C++ from D
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1. ;E.G. :* '''12''' is an esthetic number. One and two differ by 1. :* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour. :* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. ;Task :* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. :* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) :* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''. :* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''. ;Related task: * numbers with equal rises and falls ;See also: :;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 :;*Numbers Aplenty - Esthetic numbers :;*Geeks for Geeks - Stepping numbers
#include <functional> #include <iostream> #include <sstream> #include <vector> std::string to(int n, int b) { static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::stringstream ss; while (n > 0) { auto rem = n % b; n = n / b; ss << BASE[rem]; } auto fwd = ss.str(); return std::string(fwd.rbegin(), fwd.rend()); } uint64_t uabs(uint64_t a, uint64_t b) { if (a < b) { return b - a; } return a - b; } bool isEsthetic(uint64_t n, uint64_t b) { if (n == 0) { return false; } auto i = n % b; n /= b; while (n > 0) { auto j = n % b; if (uabs(i, j) != 1) { return false; } n /= b; i = j; } return true; } void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) { std::vector<uint64_t> esths; const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) { auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) { if (i >= n && i <= m) { esths.push_back(i); } if (i == 0 || i > m) { return; } auto d = i % 10; auto i1 = i * 10 + d - 1; auto i2 = i1 + 2; if (d == 0) { dfs_ref(n, m, i2, dfs_ref); } else if (d == 9) { dfs_ref(n, m, i1, dfs_ref); } else { dfs_ref(n, m, i1, dfs_ref); dfs_ref(n, m, i2, dfs_ref); } }; dfs_impl(n, m, i, dfs_impl); }; for (int i = 0; i < 10; i++) { dfs(n2, m2, i); } auto le = esths.size(); printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m); if (all) { for (size_t c = 0; c < esths.size(); c++) { auto esth = esths[c]; printf("%llu ", esth); if ((c + 1) % perLine == 0) { printf("\n"); } } printf("\n"); } else { for (int c = 0; c < perLine; c++) { auto esth = esths[c]; printf("%llu ", esth); } printf("\n............\n"); for (size_t i = le - perLine; i < le; i++) { auto esth = esths[i]; printf("%llu ", esth); } printf("\n"); } printf("\n"); } int main() { for (int b = 2; b <= 16; b++) { printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b); for (int n = 1, c = 0; c < 6 * b; n++) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { std::cout << to(n, b) << ' '; } } } printf("\n"); } printf("\n"); // the following all use the obvious range limitations for the numbers in question listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true); listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false); listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false); listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false); return 0; }
Euler's identity
C++
{{Wikipedia|Euler's_identity}} In mathematics, ''Euler's identity'' is the equality: ei\pi + 1 = 0 where e is Euler's number, the base of natural logarithms, ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and \pi is pi, the ratio of the circumference of a circle to its diameter. Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants: The number 0. The number 1. The number \pi (\pi = 3.14159+), The number e (e = 2.71828+), which occurs widely in mathematical analysis. The number ''i'', the imaginary unit of the complex numbers. ;Task Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. If that is the case, or there is some other limitation, show that ei\pi + 1 is ''approximately'' equal to zero and show the amount of error in the calculation. If your language is capable of symbolic calculations, show that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
Euler's sum of powers conjecture
C++
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
#include <algorithm> #include <iostream> #include <cmath> #include <set> #include <vector> using namespace std; bool find() { const auto MAX = 250; vector<double> pow5(MAX); for (auto i = 1; i < MAX; i++) pow5[i] = (double)i * i * i * i * i; for (auto x0 = 1; x0 < MAX; x0++) { for (auto x1 = 1; x1 < x0; x1++) { for (auto x2 = 1; x2 < x1; x2++) { for (auto x3 = 1; x3 < x2; x3++) { auto sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3]; if (binary_search(pow5.begin(), pow5.end(), sum)) { cout << x0 << " " << x1 << " " << x2 << " " << x3 << " " << pow(sum, 1.0 / 5.0) << endl; return true; } } } } } // not found return false; } int main(void) { int tm = clock(); if (!find()) cout << "Nothing found!\n"; cout << "time=" << (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC) << " milliseconds\r\n"; return 0; }
Even or odd
C++
Test whether an integer is even or odd. There is more than one way to solve this task: * Use the even and odd predicates, if the language provides them. * Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd. * Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd. * Use modular congruences: ** ''i'' 0 (mod 2) iff ''i'' is even. ** ''i'' 1 (mod 2) iff ''i'' is odd.
template < typename T > constexpr inline bool isEven( const T& v ) { return isEven( int( v ) ); } template <> constexpr inline bool isEven< int >( const int& v ) { return (v & 1) == 0; } template < typename T > constexpr inline bool isOdd( const T& v ) { return !isEven(v); }
Evolutionary algorithm
C++
Starting with: * The target string: "METHINKS IT IS LIKE A WEASEL". * An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). * A fitness function that computes the 'closeness' of its argument to the target string. * A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. :* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. :* repeat until the parent converges, (hopefully), to the target. ;See also: * Wikipedia entry: Weasel algorithm. * Wikipedia entry: Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, '''changing randomly any characters which don't already match the target''': ''NOTE:'' this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#include <string> #include <cstdlib> #include <iostream> #include <cassert> #include <algorithm> #include <vector> #include <ctime> std::string allowed_chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // class selection contains the fitness function, encapsulates the // target string and allows access to it's length. The class is only // there for access control, therefore everything is static. The // string target isn't defined in the function because that way the // length couldn't be accessed outside. class selection { public: // this function returns 0 for the destination string, and a // negative fitness for a non-matching string. The fitness is // calculated as the negated sum of the circular distances of the // string letters with the destination letters. static int fitness(std::string candidate) { assert(target.length() == candidate.length()); int fitness_so_far = 0; for (int i = 0; i < target.length(); ++i) { int target_pos = allowed_chars.find(target[i]); int candidate_pos = allowed_chars.find(candidate[i]); int diff = std::abs(target_pos - candidate_pos); fitness_so_far -= std::min(diff, int(allowed_chars.length()) - diff); } return fitness_so_far; } // get the target string length static int target_length() { return target.length(); } private: static std::string target; }; std::string selection::target = "METHINKS IT IS LIKE A WEASEL"; // helper function: cyclically move a character through allowed_chars void move_char(char& c, int distance) { while (distance < 0) distance += allowed_chars.length(); int char_pos = allowed_chars.find(c); c = allowed_chars[(char_pos + distance) % allowed_chars.length()]; } // mutate the string by moving the characters by a small random // distance with the given probability std::string mutate(std::string parent, double mutation_rate) { for (int i = 0; i < parent.length(); ++i) if (std::rand()/(RAND_MAX + 1.0) < mutation_rate) { int distance = std::rand() % 3 + 1; if(std::rand()%2 == 0) move_char(parent[i], distance); else move_char(parent[i], -distance); } return parent; } // helper function: tell if the first argument is less fit than the // second bool less_fit(std::string const& s1, std::string const& s2) { return selection::fitness(s1) < selection::fitness(s2); } int main() { int const C = 100; std::srand(time(0)); std::string parent; for (int i = 0; i < selection::target_length(); ++i) { parent += allowed_chars[std::rand() % allowed_chars.length()]; } int const initial_fitness = selection::fitness(parent); for(int fitness = initial_fitness; fitness < 0; fitness = selection::fitness(parent)) { std::cout << parent << ": " << fitness << "\n"; double const mutation_rate = 0.02 + (0.9*fitness)/initial_fitness; std::vector<std::string> childs; childs.reserve(C+1); childs.push_back(parent); for (int i = 0; i < C; ++i) childs.push_back(mutate(parent, mutation_rate)); parent = *std::max_element(childs.begin(), childs.end(), less_fit); } std::cout << "final string: " << parent << "\n"; }
Execute HQ9+
C++
Implement a ''' [[HQ9+]] ''' interpreter or compiler.
void runCode(string code) { int c_len = code.length(); unsigned accumulator=0; int bottles; for(int i=0;i<c_len;i++) { switch(code[i]) { case 'Q': cout << code << endl; break; case 'H': cout << "Hello, world!" << endl; break; case '9': //Nice bottles song alg. from RC :) bottles = 99; do { cout << bottles << " bottles of beer on the wall" << endl; cout << bottles << " bottles of beer" << endl; cout << "Take one down, pass it around" << endl; cout << --bottles << " bottles of beer on the wall" << endl << endl; } while( bottles > 0 ); break; case '+': //Am I the only one finding this one weird? :o accumulator++; break; } } };
Exponentiation order
C++
This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents. (Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.) ;Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification): ::::* 5**3**2 ::::* (5**3)**2 ::::* 5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. ;See also: * MathWorld entry: exponentiation ;Related tasks: * exponentiation operator * arbitrary-precision integers (included) * [[Exponentiation with infix operators in (or operating on) the base]]
#include <iostream> #include <cmath> enum my_int {}; inline my_int operator^(my_int a, my_int b) { return static_cast<my_int>(pow(a,b)); } int main() { my_int x = 5, y = 3, z = 2; std::cout << "(5 ^ 3) ^ 2 = " << ((x^y)^z) << std::endl; std::cout << "5 ^ (3 ^ 2) = "<< (x^(y^z)); return EXIT_SUCCESS; }
FASTA format
C++
In FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. ;Task: Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED
#include <iostream> #include <fstream> int main( int argc, char **argv ){ if( argc <= 1 ){ std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl; return -1; } std::ifstream input(argv[1]); if(!input.good()){ std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl; return -1; } std::string line, name, content; while( std::getline( input, line ).good() ){ if( line.empty() || line[0] == '>' ){ // Identifier marker if( !name.empty() ){ // Print out what we read from the last entry std::cout << name << " : " << content << std::endl; name.clear(); } if( !line.empty() ){ name = line.substr(1); } content.clear(); } else if( !name.empty() ){ if( line.find(' ') != std::string::npos ){ // Invalid sequence--no spaces allowed name.clear(); content.clear(); } else { content += line; } } } if( !name.empty() ){ // Print out what we read from the last entry std::cout << name << " : " << content << std::endl; } return 0; }
Factorial primes
C++
Definition A factorial. In other words a non-negative integer '''n''' corresponds to a factorial prime if either '''n'''! - 1 or '''n'''! + 1 is prime. ;Examples 4 corresponds to the factorial prime 4! - 1 = 23. 5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime. ;Task Find and show here the first 10 factorial primes. As well as the prime itself show the factorial number '''n''' to which it corresponds and whether 1 is to be added or subtracted. As 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!. ;Stretch If your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes. As it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function. If a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has. ;Reference * OEIS:A088054 - Factorial primes ;Related task * Sequence of primorial primes
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += " ("; str += std::to_string(len); str += " digits)"; } return str; } bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } int main() { big_int f = 1; for (int i = 0, n = 1; i < 31; ++n) { f *= n; if (is_probably_prime(f - 1)) { ++i; std::cout << std::setw(2) << i << ": " << std::setw(3) << n << "! - 1 = " << to_string(f - 1, 40) << '\n'; } if (is_probably_prime(f + 1)) { ++i; std::cout << std::setw(2) << i << ": " << std::setw(3) << n << "! + 1 = " << to_string(f + 1, 40) << '\n'; } } }
Factorions
C++ from C
Definition: A factorion is a natural number that equals the sum of the factorials of its digits. ;Example: '''145''' is a factorion in base '''10''' because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''. ;Task: Write a program in your language to demonstrate, by calculating and printing out the factorions, that: :* There are '''3''' factorions in base '''9''' :* There are '''4''' factorions in base '''10''' :* There are '''5''' factorions in base '''11''' :* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''') ;See also: :* '''Wikipedia article''' :* '''OEIS:A014080 - Factorions in base 10''' :* '''OEIS:A193163 - Factorions in base n'''
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; //< cache factorials from 0 to 11 }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Fairshare between two and more
C++ from C
The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: :''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"'' ;Sharing fairly between two or more: Use this method: :''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.'' ;Task Counting from zero; using a function/method/routine to express an integer count in base '''b''', sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people. Show the first 25 terms of the fairshare sequence: :* For two people: :* For three people :* For five people :* For eleven people ;Related tasks: :* [[Non-decimal radices/Convert]] :* [[Thue-Morse]] ;See also: :* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { std::vector<int> cnt(base, 0); for (int i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } int minTurn = INT_MAX; int maxTurn = INT_MIN; int portion = 0; for (int i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
Farey sequence
C++
The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size. The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. Each Farey sequence: :::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1} :::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}. The Farey sequences of orders '''1''' to '''5''' are: :::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1} : :::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1} : :::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1} : :::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1} : :::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1} ;Task * Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive). * Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds. * Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). The length (the number of fractions) of a Farey sequence asymptotically approaches: ::::::::::: 3 x n2 / \pi2 ;See also: * OEIS sequence A006842 numerators of Farey series of order 1, 2, *** * OEIS sequence A006843 denominators of Farey series of order 1, 2, *** * OEIS sequence A005728 number of fractions in Farey series of order n * MathWorld entry Farey sequence * Wikipedia entry Farey sequence
#include <iostream> struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; }; std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; } class farey_sequence { public: explicit farey_sequence(int n) : n_(n), a_(0), b_(1), c_(1), d_(n) {} fraction next() { // See https://en.wikipedia.org/wiki/Farey_sequence#Next_term fraction result(a_, b_); int k = (n_ + b_)/d_; int next_c = k * c_ - a_; int next_d = k * d_ - b_; a_ = c_; b_ = d_; c_ = next_c; d_ = next_d; return result; } bool has_next() const { return a_ <= n_; } private: int n_, a_, b_, c_, d_; }; int main() { for (int n = 1; n <= 11; ++n) { farey_sequence seq(n); std::cout << n << ": " << seq.next(); while (seq.has_next()) std::cout << ' ' << seq.next(); std::cout << '\n'; } for (int n = 100; n <= 1000; n += 100) { int count = 0; for (farey_sequence seq(n); seq.has_next(); seq.next()) ++count; std::cout << n << ": " << count << '\n'; } return 0; }
Farey sequence
C++17
The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size. The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. Each Farey sequence: :::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1} :::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}. The Farey sequences of orders '''1''' to '''5''' are: :::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1} : :::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1} : :::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1} : :::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1} : :::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1} ;Task * Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive). * Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds. * Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). The length (the number of fractions) of a Farey sequence asymptotically approaches: ::::::::::: 3 x n2 / \pi2 ;See also: * OEIS sequence A006842 numerators of Farey series of order 1, 2, *** * OEIS sequence A006843 denominators of Farey series of order 1, 2, *** * OEIS sequence A005728 number of fractions in Farey series of order n * MathWorld entry Farey sequence * Wikipedia entry Farey sequence
#include <iostream> #include <list> #include <utility> struct farey_sequence: public std::list<std::pair<uint, uint>> { explicit farey_sequence(uint n) : order(n) { push_back(std::pair(0, 1)); uint a = 0, b = 1, c = 1, d = n; while (c <= n) { const uint k = (n + b) / d; const uint next_c = k * c - a; const uint next_d = k * d - b; a = c; b = d; c = next_c; d = next_d; push_back(std::pair(a, b)); } } const uint order; }; std::ostream& operator<<(std::ostream &out, const farey_sequence &s) { out << s.order << ":"; for (const auto &f : s) out << ' ' << f.first << '/' << f.second; return out; } int main() { for (uint i = 1u; i <= 11u; ++i) std::cout << farey_sequence(i) << std::endl; for (uint i = 100u; i <= 1000u; i += 100u) { const auto s = farey_sequence(i); std::cout << s.order << ": " << s.size() << " items" << std::endl; } return EXIT_SUCCESS; }
Fast Fourier transform
C++
Calculate the FFT (Fast Fourier Transform) of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
#include <complex> #include <iostream> #include <valarray> const double PI = 3.141592653589793238460; typedef std::complex<double> Complex; typedef std::valarray<Complex> CArray; // Cooley–Tukey FFT (in-place, divide-and-conquer) // Higher memory requirements and redundancy although more intuitive void fft(CArray& x) { const size_t N = x.size(); if (N <= 1) return; // divide CArray even = x[std::slice(0, N/2, 2)]; CArray odd = x[std::slice(1, N/2, 2)]; // conquer fft(even); fft(odd); // combine for (size_t k = 0; k < N/2; ++k) { Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k]; x[k ] = even[k] + t; x[k+N/2] = even[k] - t; } } // Cooley-Tukey FFT (in-place, breadth-first, decimation-in-frequency) // Better optimized but less intuitive // !!! Warning : in some cases this code make result different from not optimased version above (need to fix bug) // The bug is now fixed @2017/05/30 void fft(CArray &x) { // DFT unsigned int N = x.size(), k = N, n; double thetaT = 3.14159265358979323846264338328L / N; Complex phiT = Complex(cos(thetaT), -sin(thetaT)), T; while (k > 1) { n = k; k >>= 1; phiT = phiT * phiT; T = 1.0L; for (unsigned int l = 0; l < k; l++) { for (unsigned int a = l; a < N; a += n) { unsigned int b = a + k; Complex t = x[a] - x[b]; x[a] += x[b]; x[b] = t * T; } T *= phiT; } } // Decimate unsigned int m = (unsigned int)log2(N); for (unsigned int a = 0; a < N; a++) { unsigned int b = a; // Reverse bits b = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1)); b = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2)); b = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4)); b = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8)); b = ((b >> 16) | (b << 16)) >> (32 - m); if (b > a) { Complex t = x[a]; x[a] = x[b]; x[b] = t; } } //// Normalize (This section make it not working correctly) //Complex f = 1.0 / sqrt(N); //for (unsigned int i = 0; i < N; i++) // x[i] *= f; } // inverse fft (in-place) void ifft(CArray& x) { // conjugate the complex numbers x = x.apply(std::conj); // forward fft fft( x ); // conjugate the complex numbers again x = x.apply(std::conj); // scale the numbers x /= x.size(); } int main() { const Complex test[] = { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0 }; CArray data(test, 8); // forward fft fft(data); std::cout << "fft" << std::endl; for (int i = 0; i < 8; ++i) { std::cout << data[i] << std::endl; } // inverse fft ifft(data); std::cout << std::endl << "ifft" << std::endl; for (int i = 0; i < 8; ++i) { std::cout << data[i] << std::endl; } return 0; }
Feigenbaum constant calculation
C++ from C
Calculate the Feigenbaum constant. ;See: :* Details in the Wikipedia article: Feigenbaum constant.
#include <iostream> int main() { const int max_it = 13; const int max_it_j = 10; double a1 = 1.0, a2 = 0.0, d1 = 3.2; std::cout << " i d\n"; for (int i = 2; i <= max_it; ++i) { double a = a1 + (a1 - a2) / d1; for (int j = 1; j <= max_it_j; ++j) { double x = 0.0; double y = 0.0; for (int k = 1; k <= 1 << i; ++k) { y = 1.0 - 2.0*y*x; x = a - x * x; } a -= x / y; } double d = (a1 - a2) / (a - a1); printf("%2d %.8f\n", i, d); d1 = d; a2 = a1; a1 = a; } return 0; }
Fibonacci n-step number sequences
C++
These number series are an expansion of the ordinary [[Fibonacci sequence]] where: # For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2 # For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3 # For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4... # For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}} For small values of n, Greek numeric prefixes are sometimes used to individually name each series. :::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2" |+ Fibonacci n-step sequences |- style="background-color: rgb(255, 204, 255);" ! n !! Series name !! Values |- | 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |- | 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |- | 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |- | 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |- | 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |- | 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |- | 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |- | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |- | 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |} Allied sequences can be generated where the initial values are changed: : '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values. ;Task: # Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. # Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. ;Related tasks: * [[Fibonacci sequence]] * Wolfram Mathworld * [[Hofstadter Q sequence]] * [[Leonardo numbers]] ;Also see: * Lucas Numbers - Numberphile (Video) * Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video) * Wikipedia, Lucas number * MathWorld, Fibonacci Number * Some identities for r-Fibonacci numbers * OEIS Fibonacci numbers * OEIS Lucas numbers
#include <iostream> #include <vector> // This class forms a simple 'generator', where operator() returns the next // element in the series. It uses a small sliding window buffer to minimize // storage overhead. class nacci_t { std::vector< int > history; unsigned windex; // sliding window index unsigned rindex; // result index int running_sum; // sum of values in sliding window public: nacci_t( unsigned int order, int a0 = 1, int a1 = 1 ) : history( order + 1 ), windex( 0 ), rindex( order - 1 ), running_sum( a0 + a1 ) { // intialize sliding window history[order - 1] = a0; history[order - 0] = a1; } int operator()() { int result = history[ rindex ]; // get 'nacci number to return running_sum -= history[ windex ]; // old 'nacci falls out of window history[ windex ] = running_sum; // new 'nacci enters the window running_sum += running_sum; // new 'nacci added to the sum if ( ++windex == history.size() ) windex = 0; if ( ++rindex == history.size() ) rindex = 0; return result; } }; int main() { for ( unsigned int i = 2; i <= 10; ++i ) { nacci_t nacci( i ); // fibonacci sequence std::cout << "nacci( " << i << " ): "; for ( int j = 0; j < 10; ++j ) std::cout << " " << nacci(); std::cout << std::endl; } for ( unsigned int i = 2; i <= 10; ++i ) { nacci_t lucas( i, 2, 1 ); // Lucas sequence std::cout << "lucas( " << i << " ): "; for ( int j = 0; j < 10; ++j ) std::cout << " " << lucas(); std::cout << std::endl; } }
Fibonacci word
C++
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here: Define F_Word1 as '''1''' Define F_Word2 as '''0''' Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01''' Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2 ;Task: Perform the above steps for n = 37. You may display the first few but not the larger values of n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for F_Words '''1''' to '''37''' which shows: ::* The number of characters in the word ::* The word's [[Entropy]] ;Related tasks: * Fibonacci word/fractal * [[Entropy]] * [[Entropy/Narcissist]]
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
File extension is in extensions list
C++
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''. It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid. For these reasons, this task exists in addition to the [[Extract file extension]] task. ;Related tasks: * [[Extract file extension]] * [[String matching]]
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
File size distribution
C++
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant. Don't forget that empty files may exist, to serve as a marker. Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
#include <algorithm> #include <array> #include <filesystem> #include <iomanip> #include <iostream> void file_size_distribution(const std::filesystem::path& directory) { constexpr size_t n = 9; constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 }; std::array<size_t, n + 1> count = { 0 }; size_t files = 0; std::uintmax_t total_size = 0; std::filesystem::recursive_directory_iterator iter(directory); for (const auto& dir_entry : iter) { if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) { std::uintmax_t file_size = dir_entry.file_size(); total_size += file_size; auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size); size_t index = std::distance(sizes.begin(), i); ++count[index]; ++files; } } std::cout << "File size distribution for " << directory << ":\n"; for (size_t i = 0; i <= n; ++i) { if (i == n) std::cout << "> " << sizes[i - 1]; else std::cout << std::setw(16) << sizes[i]; std::cout << " bytes: " << count[i] << '\n'; } std::cout << "Number of files: " << files << '\n'; std::cout << "Total file size: " << total_size << " bytes\n"; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); try { const char* directory(argc > 1 ? argv[1] : "."); std::filesystem::path path(directory); if (!is_directory(path)) { std::cerr << directory << " is not a directory.\n"; return EXIT_FAILURE; } file_size_distribution(path); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Find duplicate files
C++
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. ;Task: Create a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size. The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data. Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements. Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem. For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
#include<iostream> #include<string> #include<boost/filesystem.hpp> #include<boost/format.hpp> #include<boost/iostreams/device/mapped_file.hpp> #include<optional> #include<algorithm> #include<iterator> #include<execution> #include"dependencies/xxhash.hpp" // https://github.com/RedSpah/xxhash_cpp /** * Find ranges (neighbouring elements) of the same value within [begin, end[ and * call callback for each such range * @param begin start of container * @param end end of container (1 beyond last element) * @param function returns value for each iterator V(*T&) * @param callback void(start, end, value) * @return number of range */ template<typename T, typename V, typename F> size_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) { size_t partitions = 0; while (begin != end) { auto const& value = getvalue(*begin); auto current = begin; while (++current != end && getvalue(*current) == value); callback(begin, current, value); ++partitions; begin = current; } return partitions; } namespace bi = boost::iostreams; namespace fs = boost::filesystem; struct file_entry { public: explicit file_entry(fs::directory_entry const & entry) : path_{entry.path()}, size_{fs::file_size(entry)} {} auto size() const { return size_; } auto const& path() const { return path_; } auto get_hash() { if (!hash_) hash_ = compute_hash(); return *hash_; } private: xxh::hash64_t compute_hash() { bi::mapped_file_source source; source.open<fs::wpath>(this->path()); if (!source.is_open()) { std::cerr << "Cannot open " << path() << std::endl; throw std::runtime_error("Cannot open file"); } xxh::hash_state64_t hash_stream; hash_stream.update(source.data(), size_); return hash_stream.digest(); } private: fs::wpath path_; uintmax_t size_; std::optional<xxh::hash64_t> hash_; }; using vector_type = std::vector<file_entry>; using iterator_type = vector_type::iterator; auto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) { size_t found = 0, ignored = 0; if (!fs::is_directory(path)) { std::cerr << path << " is not a directory!" << std::endl; } else { std::cerr << "Searching " << path << std::endl; for (auto& e : fs::recursive_directory_iterator(path)) { ++found; if (fs::is_regular_file(e) && fs::file_size(e) >= min_size) file_vector.emplace_back(e); else ++ignored; } } return std::make_tuple(found, ignored); } int main(int argn, char* argv[]) { vector_type files; for (auto i = 1; i < argn; ++i) { fs::wpath path(argv[i]); auto [found, ignored] = find_files_in_dir(path, files); std::cerr << boost::format{ " %1$6d files found\n" " %2$6d files ignored\n" " %3$6d files added\n" } % found % ignored % (found - ignored) << std::endl; } std::cerr << "Found " << files.size() << " regular files" << std::endl; // sort files in descending order by file size std::sort(std::execution::par_unseq, files.begin(), files.end() , [](auto const& a, auto const& b) { return a.size() > b.size(); } ); for_each_adjacent_range( std::begin(files) , std::end(files) , [](vector_type::value_type const& f) { return f.size(); } , [](auto start, auto end, auto file_size) { // Files with same size size_t nr_of_files = std::distance(start, end); if (nr_of_files > 1) { // sort range start-end by hash std::sort(start, end, [](auto& a, auto& b) { auto const& ha = a.get_hash(); auto const& hb = b.get_hash(); auto const& pa = a.path(); auto const& pb = b.path(); return std::tie(ha, pa) < std::tie(hb, pb); }); for_each_adjacent_range( start , end , [](vector_type::value_type& f) { return f.get_hash(); } , [file_size](auto hstart, auto hend, auto hash) { // Files with same size and same hash are assumed to be identical // could resort to compare files byte-by-byte now size_t hnr_of_files = std::distance(hstart, hend); if (hnr_of_files > 1) { std::cout << boost::format{ "%1$3d files with hash %3$016x and size %2$d\n" } % hnr_of_files % file_size % hash; std::for_each(hstart, hend, [hash, file_size](auto& e) { std::cout << '\t' << e.path() << '\n'; } ); } } ); } } ); return 0; }
Find if a point is within a triangle
C++ from C
Find if a point is within a triangle. ;Task: ::* Assume points are on a plane defined by (x, y) real number coordinates. ::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. ::* You may use any algorithm. ::* Bonus: explain why the algorithm you chose works. ;Related tasks: * [[Determine_if_two_triangles_overlap]] ;Also see: :* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]] :* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]] :* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]] :* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]
#include <iostream> const double EPS = 0.001; const double EPS_SQUARE = EPS * EPS; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = std::min(x1, std::min(x2, x3)) - EPS; double xMax = std::max(x1, std::max(x2, x3)) + EPS; double yMin = std::min(y1, std::min(y2, y3)) - EPS; double yMax = std::max(y1, std::max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { std::cout << '(' << x << ", " << y << ')'; } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { std::cout << "Triangle is ["; printPoint(x1, y1); std::cout << ", "; printPoint(x2, y2); std::cout << ", "; printPoint(x3, y3); std::cout << "]\n"; } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); std::cout << "Point "; printPoint(x, y); std::cout << " is within triangle? "; if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { std::cout << "true\n"; } else { std::cout << "false\n"; } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); std::cout << '\n'; test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); std::cout << '\n'; test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); std::cout << '\n'; return 0; }
Find limit of recursion
C++
{{selection|Short Circuit|Console Program Basics}} ;Task: Find the limit of recursion.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Find the intersection of a line with a plane
C++ from Java
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. ;Task: Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
#include <iostream> #include <sstream> class Vector3D { public: Vector3D(double x, double y, double z) { this->x = x; this->y = y; this->z = z; } double dot(const Vector3D& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; } Vector3D operator-(const Vector3D& rhs) const { return Vector3D(x - rhs.x, y - rhs.y, z - rhs.z); } Vector3D operator*(double rhs) const { return Vector3D(rhs*x, rhs*y, rhs*z); } friend std::ostream& operator<<(std::ostream&, const Vector3D&); private: double x, y, z; }; std::ostream & operator<<(std::ostream & os, const Vector3D &f) { std::stringstream ss; ss << "(" << f.x << ", " << f.y << ", " << f.z << ")"; return os << ss.str(); } Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { Vector3D diff = rayPoint - planePoint; double prod1 = diff.dot(planeNormal); double prod2 = rayVector.dot(planeNormal); double prod3 = prod1 / prod2; return rayPoint - rayVector * prod3; } int main() { Vector3D rv = Vector3D(0.0, -1.0, -1.0); Vector3D rp = Vector3D(0.0, 0.0, 10.0); Vector3D pn = Vector3D(0.0, 0.0, 1.0); Vector3D pp = Vector3D(0.0, 0.0, 5.0); Vector3D ip = intersectPoint(rv, rp, pn, pp); std::cout << "The ray intersects the plane at " << ip << std::endl; return 0; }
Find the intersection of two lines
C++
Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html] ;Task: Find the point of intersection of two lines in 2D. The 1st line passes though (4,0) and (6,10) . The 2nd line passes though (0,3) and (10,7) .
#include <iostream> #include <cmath> #include <cassert> using namespace std; /** Calculate determinant of matrix: [a b] [c d] */ inline double Det(double a, double b, double c, double d) { return a*d - b*c; } /// Calculate intersection of two lines. ///\return true if found, false if not found or error bool LineLineIntersect(double x1, double y1, // Line 1 start double x2, double y2, // Line 1 end double x3, double y3, // Line 2 start double x4, double y4, // Line 2 end double &ixOut, double &iyOut) // Output { double detL1 = Det(x1, y1, x2, y2); double detL2 = Det(x3, y3, x4, y4); double x1mx2 = x1 - x2; double x3mx4 = x3 - x4; double y1my2 = y1 - y2; double y3my4 = y3 - y4; double denom = Det(x1mx2, y1my2, x3mx4, y3my4); if(denom == 0.0) // Lines don't seem to cross { ixOut = NAN; iyOut = NAN; return false; } double xnom = Det(detL1, x1mx2, detL2, x3mx4); double ynom = Det(detL1, y1my2, detL2, y3my4); ixOut = xnom / denom; iyOut = ynom / denom; if(!isfinite(ixOut) || !isfinite(iyOut)) // Probably a numerical issue return false; return true; //All OK } int main() { // **Simple crossing diagonal lines** // Line 1 double x1=4.0, y1=0.0; double x2=6.0, y2=10.0; // Line 2 double x3=0.0, y3=3.0; double x4=10.0, y4=7.0; double ix = -1.0, iy = -1.0; bool result = LineLineIntersect(x1, y1, x2, y2, x3, y3, x4, y4, ix, iy); cout << "result " << result << "," << ix << "," << iy << endl; double eps = 1e-6; assert(result == true); assert(fabs(ix - 5.0) < eps); assert(fabs(iy - 5.0) < eps); return 0; }
Find the last Sunday of each month
C++
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 ;Related tasks * [[Day of the week]] * [[Five weekends]] * [[Last Friday of each month]]
#include <windows.h> #include <iostream> #include <string> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: "; m[8] = "SEPTEMBER: "; m[9] = "OCTOBER: "; m[10] = "NOVEMBER: "; m[11] = "DECEMBER: "; } void findLastSunday( int y ) { year = y; isleapyear(); int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, d; for( int i = 0; i < 12; i++ ) { d = days[i]; while( true ) { if( !getWeekDay( i, d ) ) break; d--; } lastDay[i] = d; } display(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } void display() { system( "cls" ); cout << " YEAR " << year << endl << "=============" << endl; for( int x = 0; x < 12; x++ ) cout << m[x] << lastDay[x] << endl; cout << endl << endl; } int getWeekDay( int m, int d ) { int y = year; int f = y + d + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } int lastDay[12], year; string m[12]; bool isleap; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { int y; lastSunday ls; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; ls.findLastSunday( y ); system( "pause" ); } return 0; } //--------------------------------------------------------------------------------------------------
Find the missing permutation
C++
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. ;Task: Find that missing permutation. ;Methods: * Obvious method: enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', and then look for the missing permutation. * alternate method: Hint: if all permutations were shown above, how many times would '''A''' appear in each position? What is the ''parity'' of this number? * another alternate method: Hint: if you add up the letter values of each column, does a missing letter '''A''', '''B''', '''C''', and '''D''' from each column cause the total value for each column to be unique? ;Related task: * [[Permutations]])
#include <algorithm> #include <vector> #include <set> #include <iterator> #include <iostream> #include <string> static const std::string GivenPermutations[] = { "ABCD","CABD","ACDB","DACB", "BCDA","ACBD","ADCB","CDAB", "DABC","BCAD","CADB","CDBA", "CBAD","ABDC","ADBC","BDCA", "DCBA","BACD","BADC","BDAC", "CBDA","DBCA","DCAB" }; static const size_t NumGivenPermutations = sizeof(GivenPermutations) / sizeof(*GivenPermutations); int main() { std::vector<std::string> permutations; std::string initial = "ABCD"; permutations.push_back(initial); while(true) { std::string p = permutations.back(); std::next_permutation(p.begin(), p.end()); if(p == permutations.front()) break; permutations.push_back(p); } std::vector<std::string> missing; std::set<std::string> given_permutations(GivenPermutations, GivenPermutations + NumGivenPermutations); std::set_difference(permutations.begin(), permutations.end(), given_permutations.begin(), given_permutations.end(), std::back_inserter(missing)); std::copy(missing.begin(), missing.end(), std::ostream_iterator<std::string>(std::cout, "\n")); return 0; }
First-class functions/Use numbers analogously
C++
In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. '''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#include <array> #include <iostream> int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y ); const std::array values{x, y, z}; const std::array inverses{xi, yi, zi}; auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; }; for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\n"; } }
First perfect square in base n with n unique digits
C++ from C#
Find the first perfect square in a given base '''N''' that has at least '''N''' digits and exactly '''N''' ''significant unique'' digits when expressed in base '''N'''. E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432'''). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. ;Task * Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated. * (optional) Do the same for bases '''13''' through '''16'''. * (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math) ;See also: ;* OEIS A260182: smallest square that is pandigital in base n. ;Related task ;* [[Casting out nines]]
#include <string> #include <iostream> #include <cstdlib> #include <math.h> #include <chrono> #include <iomanip> using namespace std; const int maxBase = 16; // maximum base tabulated int base, bmo, tc; // globals: base, base minus one, test count const string chars = "0123456789ABCDEF"; // characters to use for the different bases unsigned long long full; // for allIn() testing // converts base 10 to string representation of the current base string toStr(const unsigned long long ull) { unsigned long long u = ull; string res = ""; while (u > 0) { lldiv_t result1 = lldiv(u, base); res = chars[(int)result1.rem] + res; u = (unsigned long long)result1.quot; } return res; } // converts string to base 10 unsigned long long to10(string s) { unsigned long long res = 0; for (char i : s) res = res * base + chars.find(i); return res; } // determines whether all characters are present bool allIn(const unsigned long long ull) { unsigned long long u, found; u = ull; found = 0; while (u > 0) { lldiv_t result1 = lldiv(u, base); found |= (unsigned long long)1 << result1.rem; u = result1.quot; } return found == full; } // returns the minimum value string, optionally inserting extra digit string fixup(int n) { string res = chars.substr(0, base); if (n > 0) res = res.insert(n, chars.substr(n, 1)); return "10" + res.substr(2); } // perform the calculations for one base void doOne() { bmo = base - 1; tc = 0; unsigned long long sq, rt, dn, d; int id = 0, dr = (base & 1) == 1 ? base >> 1 : 0, inc = 1, sdr[maxBase] = { 0 }; full = ((unsigned long long)1 << base) - 1; int rc = 0; for (int i = 0; i < bmo; i++) { sdr[i] = (i * i) % bmo; if (sdr[i] == dr) rc++; if (sdr[i] == 0) sdr[i] += bmo; } if (dr > 0) { id = base; for (int i = 1; i <= dr; i++) if (sdr[i] >= dr) if (id > sdr[i]) id = sdr[i]; id -= dr; } sq = to10(fixup(id)); rt = (unsigned long long)sqrt(sq) + 1; sq = rt * rt; dn = (rt << 1) + 1; d = 1; if (base > 3 && rc > 0) { while (sq % bmo != dr) { rt += 1; sq += dn; dn += 2; } // alligns sq to dr inc = bmo / rc; if (inc > 1) { dn += rt * (inc - 2) - 1; d = inc * inc; } dn += dn + d; } d <<= 1; do { if (allIn(sq)) break; sq += dn; dn += d; tc++; } while (true); rt += tc * inc; cout << setw(4) << base << setw(3) << inc << " " << setw(2) << (id > 0 ? chars.substr(id, 1) : " ") << setw(10) << toStr(rt) << " " << setw(20) << left << toStr(sq) << right << setw(12) << tc << endl; } int main() { cout << "base inc id root sqr test count" << endl; auto st = chrono::system_clock::now(); for (base = 2; base <= maxBase; base++) doOne(); chrono::duration<double> et = chrono::system_clock::now() - st; cout << "\nComputation time was " << et.count() * 1000 << " milliseconds" << endl; return 0; }
First power of 2 that has leading decimal digits of 12
C++ from Pascal
(This task is taken from a ''Project Euler'' problem.) (All numbers herein are expressed in base ten.) '''27 = 128''' and '''7''' is the first power of '''2''' whose leading decimal digits are '''12'''. The next power of '''2''' whose leading decimal digits are '''12''' is '''80''', '''280 = 1208925819614629174706176'''. Define ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest value of ''' ''j'' ''' such that the base ten representation of '''2''j''''' begins with the digits of ''' ''L'' '''. So ''p''(12, 1) = 7 and ''p''(12, 2) = 80 You are also given that: ''p''(123, 45) = 12710 ;Task: ::* find: :::::* ''' ''p''(12, 1) ''' :::::* ''' ''p''(12, 2) ''' :::::* ''' ''p''(123, 45) ''' :::::* ''' ''p''(123, 12345) ''' :::::* ''' ''p''(123, 678910) ''' ::* display the results here, on this page.
// a mini chrestomathy solution #include <string> #include <chrono> #include <cmath> #include <locale> using namespace std; using namespace chrono; // translated from java example unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * pow(10, modf(++res * lf, &ip))) == l) n--; return res; } // translated from go integer example (a.k.a. go translation of pascal alternative example) unsigned int gi(int ld, int n) { string Ls = to_string(ld); unsigned int res = 0, count = 0; unsigned long long f = 1; for (int i = 1; i <= 18 - Ls.length(); i++) f *= 10; const unsigned long long ten18 = 1e18; unsigned long long probe = 1; do { probe <<= 1; res++; if (probe >= ten18) { do { if (probe >= ten18) probe /= 10; if (probe / f == ld) if (++count >= n) { count--; break; } probe <<= 1; res++; } while (1); } string ps = to_string(probe); if (ps.substr(0, min(Ls.length(), ps.length())) == Ls) if (++count >= n) break; } while (1); return res; } // translated from pascal alternative example unsigned int pa(int ld, int n) { const double L_float64 = pow(2, 64); const unsigned long long Log10_2_64 = (unsigned long long)(L_float64 * log(2) / log(10)); double Log10Num; unsigned long long LmtUpper, LmtLower, Frac64; int res = 0, dgts = 1, cnt; for (int i = ld; i >= 10; i /= 10) dgts *= 10; Log10Num = log((ld + 1.0) / dgts) / log(10); // '316' was a limit if (Log10Num >= 0.5) { LmtUpper = (ld + 1.0) / dgts < 10.0 ? (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2) : 0; Log10Num = log((double)ld / dgts) / log(10); LmtLower = (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2); } else { LmtUpper = (unsigned long long)(Log10Num * L_float64); LmtLower = (unsigned long long)(log((double)ld / dgts) / log(10) * L_float64); } cnt = 0; Frac64 = 0; if (LmtUpper != 0) { do { res++; Frac64 += Log10_2_64; if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper)) if (++cnt >= n) break; } while (1); } else { // '999..' do { res++; Frac64 += Log10_2_64; if (Frac64 >= LmtLower) if (++cnt >= n) break; } while (1); }; return res; } int params[] = { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 }; void doOne(string name, unsigned int (*func)(int a, int b)) { printf("%s version:\n", name.c_str()); auto start = steady_clock::now(); for (int i = 0; i < size(params); i += 2) printf("p(%3d, %6d) = %'11u\n", params[i], params[i + 1], func(params[i], params[i + 1])); printf("Took %f seconds\n\n", duration<double>(steady_clock::now() - start).count()); } int main() { setlocale(LC_ALL, ""); doOne("java simple", js); doOne("go integer", gi); doOne("pascal alternative", pa); }
Fivenum
C++ from D
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory. For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function. ;Task: Given an array of numbers, compute the five-number summary. ;Note: While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
#include <algorithm> #include <iostream> #include <ostream> #include <vector> ///////////////////////////////////////////////////////////////////////////// // The following is taken from https://cpplove.blogspot.com/2012/07/printing-tuples.html // Define a type which holds an unsigned integer value template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } ///////////////////////////////////////////////////////////////////////////// template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
Fixed length records
C++
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column. These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems). ;Task: Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat. '''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed. These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''. ;Sample data: To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size. Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input. prompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines. ;Bonus round: Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line). Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output. Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character. The COBOL example uses forth.txt and forth.blk filenames.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> void reverse(std::istream& in, std::ostream& out) { constexpr size_t record_length = 80; char record[record_length]; while (in.read(record, record_length)) { std::reverse(std::begin(record), std::end(record)); out.write(record, record_length); } out.flush(); } int main(int argc, char** argv) { std::ifstream in("infile.dat", std::ios_base::binary); if (!in) { std::cerr << "Cannot open input file\n"; return EXIT_FAILURE; } std::ofstream out("outfile.dat", std::ios_base::binary); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } try { in.exceptions(std::ios_base::badbit); out.exceptions(std::ios_base::badbit); reverse(in, out); } catch (const std::exception& ex) { std::cerr << "I/O error: " << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Flatten a list
C++
Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] ;Related task: * [[Tree traversal]]
#include <cctype> #include <iostream> // ******************* // * the list parser * // ******************* void skipwhite(char const** s) { while (**s && std::isspace((unsigned char)**s)) { ++*s; } } anylist create_anylist_i(char const** s) { anylist result; skipwhite(s); if (**s != '[') throw "Not a list"; ++*s; while (true) { skipwhite(s); if (!**s) throw "Error"; else if (**s == ']') { ++*s; return result; } else if (**s == '[') result.push_back(create_anylist_i(s)); else if (std::isdigit((unsigned char)**s)) { int i = 0; while (std::isdigit((unsigned char)**s)) { i = 10*i + (**s - '0'); ++*s; } result.push_back(i); } else throw "Error"; skipwhite(s); if (**s != ',' && **s != ']') throw "Error"; if (**s == ',') ++*s; } } anylist create_anylist(char const* i) { return create_anylist_i(&i); } // ************************* // * printing nested lists * // ************************* void print_list(anylist const& list); void print_item(boost::any const& a) { if (a.type() == typeid(int)) std::cout << boost::any_cast<int>(a); else if (a.type() == typeid(anylist)) print_list(boost::any_cast<anylist const&>(a)); else std::cout << "???"; } void print_list(anylist const& list) { std::cout << '['; anylist::const_iterator iter = list.begin(); while (iter != list.end()) { print_item(*iter); ++iter; if (iter != list.end()) std::cout << ", "; } std::cout << ']'; } // *************************** // * The actual test program * // *************************** int main() { anylist list = create_anylist("[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]"); print_list(list); std::cout << "\n"; flatten(list); print_list(list); std::cout << "\n"; }
Flipping bits game
C++
The game: Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once (as one move). In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column. ;Task: Create a program to score for the Flipping bits game. # The game should create an original random target configuration and a starting configuration. # Ensure that the starting position is ''never'' the target position. # The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position). # The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a '''3x3''' array of bits.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
Floyd's triangle
C++
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where * the first row is '''1''' (unity) * successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ;Task: :# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows). :# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#include <windows.h> #include <sstream> #include <iostream> //-------------------------------------------------------------------------------------------------- using namespace std; //-------------------------------------------------------------------------------------------------- class floyds_tri { public: floyds_tri() { lastLineLen = 0; } ~floyds_tri() { killArray(); } void create( int rows ) { _rows = rows; calculateLastLineLen(); display(); } private: void killArray() { if( lastLineLen ) delete [] lastLineLen; } void calculateLastLineLen() { killArray(); lastLineLen = new BYTE[_rows]; int s = 1 + ( _rows * ( _rows - 1 ) ) / 2; for( int x = s, ix = 0; x < s + _rows; x++, ix++ ) { ostringstream cvr; cvr << x; lastLineLen[ix] = static_cast<BYTE>( cvr.str().size() ); } } void display() { cout << endl << "Floyd\'s Triangle - " << _rows << " rows" << endl << "===============================================" << endl; int number = 1; for( int r = 0; r < _rows; r++ ) { for( int c = 0; c <= r; c++ ) { ostringstream cvr; cvr << number++; string str = cvr.str(); while( str.length() < lastLineLen[c] ) str = " " + str; cout << str << " "; } cout << endl; } } int _rows; BYTE* lastLineLen; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { floyds_tri t; int s; while( true ) { cout << "Enter the size of the triangle ( 0 to QUIT ): "; cin >> s; if( !s ) return 0; if( s > 0 ) t.create( s ); cout << endl << endl; system( "pause" ); } return 0; } //--------------------------------------------------------------------------------------------------
Four is magic
C++
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' '''Three is five, five is four, four is magic.''' For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. ;Some task guidelines: :* You may assume the input will only contain integer numbers. :* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.) :* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) :* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.) :* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''. :* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''. :* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''. :* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") :* The output can either be the return value from the function, or be displayed from within the function. :* You are encouraged, though not mandated to use proper sentence capitalization. :* You may optionally support negative numbers. '''-7''' is '''negative seven'''. :* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code. ;Related tasks: :* [[Four is the number of_letters in the ...]] :* [[Look-and-say sequence]] :* [[Number names]] :* [[Self-describing numbers]] :* [[Summarize and say sequence]] :* [[Spelling of ordinal numbers]] :* [[De Bruijn sequences]]
#include <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char* tens[] = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; struct named_number { const char* name_; integer number_; }; const named_number named_numbers[] = { { "hundred", 100 }, { "thousand", 1000 }, { "million", 1000000 }, { "billion", 1000000000 }, { "trillion", 1000000000000 }, { "quadrillion", 1000000000000000ULL }, { "quintillion", 1000000000000000000ULL } }; const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number_) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string cardinal(integer n) { std::string result; if (n < 20) result = small[n]; else if (n < 100) { result = tens[n/10 - 2]; if (n % 10 != 0) { result += "-"; result += small[n % 10]; } } else { const named_number& num = get_named_number(n); integer p = num.number_; result = cardinal(n/p); result += " "; result += num.name_; if (n % p != 0) { result += " "; result += cardinal(n % p); } } return result; } inline char uppercase(char ch) { return static_cast<char>(std::toupper(static_cast<unsigned char>(ch))); } std::string magic(integer n) { std::string result; for (unsigned int i = 0; ; ++i) { std::string text(cardinal(n)); if (i == 0) text[0] = uppercase(text[0]); result += text; if (n == 4) { result += " is magic."; break; } integer len = text.length(); result += " is "; result += cardinal(len); result += ", "; n = len; } return result; } void test_magic(integer n) { std::cout << magic(n) << '\n'; } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
Four is the number of letters in the ...
C++
The '''Four is ...''' sequence is based on the counting of the number of letters in the words of the (never-ending) sentence: Four is the number of letters in the first word of this sentence, two in the second, three in the third, six in the fourth, two in the fifth, seven in the sixth, *** ;Definitions and directives: :* English is to be used in spelling numbers. :* '''Letters''' are defined as the upper- and lowercase letters in the Latin alphabet ('''A-->Z''' and '''a-->z'''). :* Commas are not counted, nor are hyphens (dashes or minus signs). :* '''twenty-three''' has eleven letters. :* '''twenty-three''' is considered one word (which is hyphenated). :* no ''' ''and'' ''' words are to be used when spelling a (English) word for a number. :* The American version of numbers will be used here in this task (as opposed to the British version). '''2,000,000,000''' is two billion, ''not'' two milliard. ;Task: :* Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first '''N''' words in the never-ending sentence. For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble), the sequence would be: '''4 2 3 6 2 7''' :* Only construct as much as is needed for the never-ending sentence. :* Write a driver (invoking routine) to show the number of letters in the Nth word, ''as well as'' showing the Nth word itself. :* After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed. :* Show all output here. ;Test cases: Display the first 201 numbers in the sequence (and the total number of characters in the sentence). Display the number of letters (and the word itself) of the 1,000th word. Display the number of letters (and the word itself) of the 10,000th word. Display the number of letters (and the word itself) of the 100,000th word. Display the number of letters (and the word itself) of the 1,000,000th word. Display the number of letters (and the word itself) of the 10,000,000th word (optional). ;Related tasks: :* [[Four is magic]] :* [[Look-and-say sequence]] :* [[Number names]] :* [[Self-describing numbers]] :* [[Self-referential sequence]] :* [[Spelling of ordinal numbers]] ;Also see: :* See the OEIS sequence A72425 "Four is the number of letters...". :* See the OEIS sequence A72424 "Five's the number of letters..."
#include <cctype> #include <cstdint> #include <iomanip> #include <iostream> #include <string> #include <vector> struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; uint64_t number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "biliionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(uint64_t n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } size_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) { size_t count = 0; if (n < 20) { result.push_back(get_name(small[n], ordinal)); count = 1; } else if (n < 100) { if (n % 10 == 0) { result.push_back(get_name(tens[n/10 - 2], ordinal)); } else { std::string name(get_name(tens[n/10 - 2], false)); name += "-"; name += get_name(small[n % 10], ordinal); result.push_back(name); } count = 1; } else { const named_number& num = get_named_number(n); uint64_t p = num.number; count += append_number_name(result, n/p, false); if (n % p == 0) { result.push_back(get_name(num, ordinal)); ++count; } else { result.push_back(get_name(num, false)); ++count; count += append_number_name(result, n % p, ordinal); } } return count; } size_t count_letters(const std::string& str) { size_t letters = 0; for (size_t i = 0, n = str.size(); i < n; ++i) { if (isalpha(static_cast<unsigned char>(str[i]))) ++letters; } return letters; } std::vector<std::string> sentence(size_t count) { static const char* words[] = { "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence," }; std::vector<std::string> result; result.reserve(count + 10); size_t n = std::size(words); for (size_t i = 0; i < n && i < count; ++i) { result.push_back(words[i]); } for (size_t i = 1; count > n; ++i) { n += append_number_name(result, count_letters(result[i]), false); result.push_back("in"); result.push_back("the"); n += 2; n += append_number_name(result, i + 1, true); result.back() += ','; } return result; } size_t sentence_length(const std::vector<std::string>& words) { size_t n = words.size(); if (n == 0) return 0; size_t length = n - 1; for (size_t i = 0; i < n; ++i) length += words[i].size(); return length; } int main() { std::cout.imbue(std::locale("")); size_t n = 201; auto result = sentence(n); std::cout << "Number of letters in first " << n << " words in the sequence:\n"; for (size_t i = 0; i < n; ++i) { if (i != 0) std::cout << (i % 25 == 0 ? '\n' : ' '); std::cout << std::setw(2) << count_letters(result[i]); } std::cout << '\n'; std::cout << "Sentence length: " << sentence_length(result) << '\n'; for (n = 1000; n <= 10000000; n *= 10) { result = sentence(n); const std::string& word = result[n - 1]; std::cout << "The " << n << "th word is '" << word << "' and has " << count_letters(word) << " letters. "; std::cout << "Sentence length: " << sentence_length(result) << '\n'; } return 0; }
Function prototype
C++
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. ;Task: Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: * An explanation of any placement restrictions for prototype declarations * A prototype declaration for a function that does not require arguments * A prototype declaration for a function that requires two arguments * A prototype declaration for a function that utilizes varargs * A prototype declaration for a function that utilizes optional arguments * A prototype declaration for a function that utilizes named parameters * Example of prototype declarations for subroutines or procedures (if these differ from functions) * An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
int noargs(); // Declare a function with no arguments that returns an integer int twoargs(int a,int b); // Declare a function with two arguments that returns an integer int twoargs(int ,int); // Parameter names are optional in a prototype definition int anyargs(...); // An ellipsis is used to declare a function that accepts varargs int atleastoneargs(int, ...); // One mandatory integer argument followed by varargs template<typename T> T declval(T); //A function template template<typename ...T> tuple<T...> make_tuple(T...); //Function template using parameter pack (since c++11)
Fusc sequence
C++ from C#
Definitions: The '''fusc''' integer sequence is defined as: ::* fusc(0) = 0 ::* fusc(1) = 1 ::* for '''n'''>1, the '''n'''th term is defined as: ::::* if '''n''' is even; fusc(n) = fusc(n/2) ::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above). ;An observation: :::::* fusc(A) = fusc(B) where '''A''' is some non-negative integer expressed in binary, and where '''B''' is the binary value of '''A''' reversed. Fusc numbers are also known as: ::* fusc function (named by Dijkstra, 1982) ::* Stern's Diatomic series (although it starts with unity, not zero) ::* Stern-Brocot sequence (although it starts with unity, not zero) ;Task: ::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format. ::* show the fusc number (and its index) whose length is greater than any previous fusc number length. ::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.) ::* show all numbers with commas (if appropriate). ::* show all output here. ;Related task: ::* RosettaCode Stern-Brocot sequence ;Also see: ::* the MathWorld entry: Stern's Diatomic Series. ::* the OEIS entry: A2487.
#include <iomanip> #include <iostream> #include <limits> #include <sstream> #include <vector> const int n = 61; std::vector<int> l{ 0, 1 }; int fusc(int n) { if (n < l.size()) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.push_back(f); return f; } int main() { bool lst = true; int w = -1; int c = 0; int t; std::string res; std::cout << "First " << n << " numbers in the fusc sequence:\n"; for (int i = 0; i < INT32_MAX; i++) { int f = fusc(i); if (lst) { if (i < 61) { std::cout << f << ' '; } else { lst = false; std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n"; std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n"; std::cout << res << '\n'; res = ""; } } std::stringstream ss; ss << f; t = ss.str().length(); ss.str(""); ss.clear(); if (t > w) { w = t; res += (res == "" ? "" : "\n"); ss << std::setw(11) << i << " " << std::left << std::setw(9) << f; res += ss.str(); if (!lst) { std::cout << res << '\n'; res = ""; } if (++c > 5) { break; } } } return 0; }
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: '''187''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''187'''. About 7.46% of positive integers are ''gapful''. ;Task: :* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page :* Show the first '''30''' gapful numbers :* Show the first '''15''' gapful numbers >= '''1,000,000''' :* Show the first '''10''' gapful numbers >= '''1,000,000,000''' ;Related tasks: :* Harshad or Niven series. :* palindromic gapful numbers. :* largest number divisible by its digits. ;Also see: :* The OEIS entry: A108343 gapful numbers. :* numbersaplenty gapful numbers
#include <iostream> bool gapful(int n) { int m = n; while (m >= 10) m /= 10; return n % ((n % 10) + 10 * (m % 10)) == 0; } void show_gapful_numbers(int n, int count) { std::cout << "First " << count << " gapful numbers >= " << n << ":\n"; for (int i = 0; i < count; ++n) { if (gapful(n)) { if (i != 0) std::cout << ", "; std::cout << n; ++i; } } std::cout << '\n'; } int main() { show_gapful_numbers(100, 30); show_gapful_numbers(1000000, 15); show_gapful_numbers(1000000000, 10); return 0; }
Gauss-Jordan matrix inversion
C++
Invert matrix '''A''' using Gauss-Jordan method. '''A''' being an '''n''' x '''n''' matrix.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, scalar_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} matrix(size_t rows, size_t columns, std::initializer_list<scalar_type> values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_ * columns_); std::copy(values.begin(), values.end(), elements_.begin()); } size_t rows() const { return rows_; } size_t columns() const { return columns_; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> matrix<scalar_type> product(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { assert(a.columns() == b.rows()); size_t arows = a.rows(); size_t bcolumns = b.columns(); size_t n = a.columns(); matrix<scalar_type> c(arows, bcolumns); for (size_t i = 0; i < arows; ++i) { for (size_t j = 0; j < n; ++j) { for (size_t k = 0; k < bcolumns; ++k) c(i, k) += a(i, j) * b(j, k); } } return c; } template <typename scalar_type> void swap_rows(matrix<scalar_type>& m, size_t i, size_t j) { size_t columns = m.columns(); for (size_t column = 0; column < columns; ++column) std::swap(m(i, column), m(j, column)); } // Convert matrix to reduced row echelon form template <typename scalar_type> void rref(matrix<scalar_type>& m) { size_t rows = m.rows(); size_t columns = m.columns(); for (size_t row = 0, lead = 0; row < rows && lead < columns; ++row, ++lead) { size_t i = row; while (m(i, lead) == 0) { if (++i == rows) { i = row; if (++lead == columns) return; } } swap_rows(m, i, row); if (m(row, lead) != 0) { scalar_type f = m(row, lead); for (size_t column = 0; column < columns; ++column) m(row, column) /= f; } for (size_t j = 0; j < rows; ++j) { if (j == row) continue; scalar_type f = m(j, lead); for (size_t column = 0; column < columns; ++column) m(j, column) -= f * m(row, column); } } } template <typename scalar_type> matrix<scalar_type> inverse(const matrix<scalar_type>& m) { assert(m.rows() == m.columns()); size_t rows = m.rows(); matrix<scalar_type> tmp(rows, 2 * rows, 0); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < rows; ++column) tmp(row, column) = m(row, column); tmp(row, row + rows) = 1; } rref(tmp); matrix<scalar_type> inv(rows, rows); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < rows; ++column) inv(row, column) = tmp(row, column + rows); } return inv; } template <typename scalar_type> void print(std::ostream& out, const matrix<scalar_type>& m) { size_t rows = m.rows(), columns = m.columns(); out << std::fixed << std::setprecision(4); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < columns; ++column) { if (column > 0) out << ' '; out << std::setw(7) << m(row, column); } out << '\n'; } } int main() { matrix<double> m(3, 3, {2, -1, 0, -1, 2, -1, 0, -1, 2}); std::cout << "Matrix:\n"; print(std::cout, m); auto inv(inverse(m)); std::cout << "Inverse:\n"; print(std::cout, inv); std::cout << "Product of matrix and inverse:\n"; print(std::cout, product(m, inv)); std::cout << "Inverse of inverse:\n"; print(std::cout, inverse(inv)); return 0; }
Gaussian elimination
C++ from Go
Solve '''Ax=b''' using Gaussian elimination then backwards substitution. '''A''' being an '''n''' by '''n''' matrix. Also, '''x''' and '''b''' are '''n''' by '''1''' vectors. To improve accuracy, please use partial pivoting and scaling. ;See also: :* the Wikipedia entry: Gaussian elimination
#include <algorithm> #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); auto i = elements_.begin(); for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), i); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> void swap_rows(matrix<scalar_type>& m, size_t i, size_t j) { size_t columns = m.columns(); for (size_t k = 0; k < columns; ++k) std::swap(m(i, k), m(j, k)); } template <typename scalar_type> std::vector<scalar_type> gauss_partial(const matrix<scalar_type>& a0, const std::vector<scalar_type>& b0) { size_t n = a0.rows(); assert(a0.columns() == n); assert(b0.size() == n); // make augmented matrix matrix<scalar_type> a(n, n + 1); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) a(i, j) = a0(i, j); a(i, n) = b0[i]; } // WP algorithm from Gaussian elimination page // produces row echelon form for (size_t k = 0; k < n; ++k) { // Find pivot for column k size_t max_index = k; scalar_type max_value = 0; for (size_t i = k; i < n; ++i) { // compute scale factor = max abs in row scalar_type scale_factor = 0; for (size_t j = k; j < n; ++j) scale_factor = std::max(std::abs(a(i, j)), scale_factor); if (scale_factor == 0) continue; // scale the abs used to pick the pivot scalar_type abs = std::abs(a(i, k))/scale_factor; if (abs > max_value) { max_index = i; max_value = abs; } } if (a(max_index, k) == 0) throw std::runtime_error("matrix is singular"); if (k != max_index) swap_rows(a, k, max_index); for (size_t i = k + 1; i < n; ++i) { scalar_type f = a(i, k)/a(k, k); for (size_t j = k + 1; j <= n; ++j) a(i, j) -= a(k, j) * f; a(i, k) = 0; } } // now back substitute to get result std::vector<scalar_type> x(n); for (size_t i = n; i-- > 0; ) { x[i] = a(i, n); for (size_t j = i + 1; j < n; ++j) x[i] -= a(i, j) * x[j]; x[i] /= a(i, i); } return x; } int main() { matrix<double> a(6, 6, { {1.00, 0.00, 0.00, 0.00, 0.00, 0.00}, {1.00, 0.63, 0.39, 0.25, 0.16, 0.10}, {1.00, 1.26, 1.58, 1.98, 2.49, 3.13}, {1.00, 1.88, 3.55, 6.70, 12.62, 23.80}, {1.00, 2.51, 6.32, 15.88, 39.90, 100.28}, {1.00, 3.14, 9.87, 31.01, 97.41, 306.02} }); std::vector<double> b{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02}; std::vector<double> x{-0.01, 1.602790394502114, -1.6132030599055613, 1.2454941213714368, -0.4909897195846576, 0.065760696175232}; std::vector<double> y(gauss_partial(a, b)); std::cout << std::setprecision(16); const double epsilon = 1e-14; for (size_t i = 0; i < y.size(); ++i) { assert(std::abs(x[i] - y[i]) <= epsilon); std::cout << y[i] << '\n'; } return 0; }
Generate Chess960 starting position
C++
Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: ** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) ** the King must be between two rooks (with any number of other pieces between them all) * Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are '''960''' possible starting positions, thus the name of the variant. ;Task: The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.
#include <iostream> #include <string> #include <time.h> using namespace std; namespace { void placeRandomly(char* p, char c) { int loc = rand() % 8; if (!p[loc]) p[loc] = c; else placeRandomly(p, c); // try again } int placeFirst(char* p, char c, int loc = 0) { while (p[loc]) ++loc; p[loc] = c; return loc; } string startPos() { char p[8]; memset( p, 0, 8 ); // bishops on opposite color p[2 * (rand() % 4)] = 'B'; p[2 * (rand() % 4) + 1] = 'B'; // queen knight knight, anywhere for (char c : "QNN") placeRandomly(p, c); // rook king rook, in that order placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R'))); return string(p, 8); } } // leave local namespace chess960 { void generate( int c ) { for( int x = 0; x < c; x++ ) cout << startPos() << "\n"; } } int main( int argc, char* argv[] ) { srand( time( NULL ) ); chess960::generate( 10 ); cout << "\n\n"; return system( "pause" ); }
Generate random chess position
C++
Generate a random chess position in FEN format. The position does not have to be realistic or even balanced, but it must comply to the following rules: :* there is one and only one king of each color (one black king and one white king); :* the kings must not be placed on adjacent squares; :* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank); :* including the kings, up to 32 pieces of either color can be placed. :* There is no requirement for material balance between sides. :* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. :* it is white's turn. :* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
#include <ctime> #include <iostream> #include <string> #include <algorithm> class chessBoard { public: void generateRNDBoard( int brds ) { int a, b, i; char c; for( int cc = 0; cc < brds; cc++ ) { memset( brd, 0, 64 ); std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk"; random_shuffle( pieces.begin(), pieces.end() ); while( pieces.length() ) { i = rand() % pieces.length(); c = pieces.at( i ); while( true ) { a = rand() % 8; b = rand() % 8; if( brd[a][b] == 0 ) { if( c == 'P' && !b || c == 'p' && b == 7 || ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue; break; } } brd[a][b] = c; pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 ); } print(); } } private: bool search( char c, int a, int b ) { for( int y = -1; y < 2; y++ ) { for( int x = -1; x < 2; x++ ) { if( !x && !y ) continue; if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) { if( brd[a + x][b + y] == c ) return true; } } } return false; } void print() { int e = 0; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) e++; else { if( e > 0 ) { std::cout << e; e = 0; } std::cout << brd[x][y]; } } if( e > 0 ) { std::cout << e; e = 0; } if( y < 7 ) std::cout << "/"; } std::cout << " w - - 0 1\n\n"; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) std::cout << "."; else std::cout << brd[x][y]; } std::cout << "\n"; } std::cout << "\n\n"; } char brd[8][8]; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); chessBoard c; c.generateRNDBoard( 2 ); return 0; }
Generator/Exponential
C++
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
#include <iostream> using namespace std; template<class T> class Generator { public: virtual T operator()() = 0; }; // Does nothing unspecialized template<class T, T P> class PowersGenerator: Generator<T> {}; // Specialize with other types, or provide a generic version of pow template<int P> class PowersGenerator<int, P>: Generator<int> { public: int i; PowersGenerator() { i = 1; } virtual int operator()() { int o = 1; for(int j = 0; j < P; ++j) o *= i; ++i; return o; } }; // Only works with non-decreasing generators template<class T, class G, class F> class Filter: Generator<T> { public: G gen; F filter; T lastG, lastF; Filter() { lastG = gen(); lastF = filter(); } virtual T operator()() { while(lastG >= lastF) { if(lastG == lastF) lastG = gen(); lastF = filter(); } T out = lastG; lastG = gen(); return out; } }; int main() { Filter<int, PowersGenerator<int, 2>, PowersGenerator<int, 3>> gen; for(int i = 0; i < 20; ++i) gen(); for(int i = 20; i < 30; ++i) cout << i << ": " << gen() << endl; }
Get system command output
C++
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). ;Related task * Execute a system command
#include <fstream> #include <iostream> std::string execute(const std::string& command) { system((command + " > temp.txt").c_str()); std::ifstream ifs("temp.txt"); std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() }; ifs.close(); // must close the inout stream so the file can be cleaned up if (std::remove("temp.txt") != 0) { perror("Error deleting temporary file"); } return ret; } int main() { std::cout << execute("whoami") << '\n'; }
Giuga numbers
C++
Definition A '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors '''f''' divide (n/f - 1) exactly. All known Giuga numbers are even though it is not known for certain that there are no odd examples. ;Example 30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and: * 30/2 - 1 = 14 is divisible by 2 * 30/3 - 1 = 9 is divisible by 3 * 30/5 - 1 = 5 is divisible by 5 ;Task Determine and show here the first four Giuga numbers. ;Stretch Determine the fifth Giuga number and any more you have the patience for. ;References * Wikipedia: Giuga number * OEIS:A007850 - Giuga numbers
#include <iostream> // Assumes n is even with exactly one factor of 2. bool is_giuga(unsigned int n) { unsigned int m = n / 2; auto test_factor = [&m, n](unsigned int p) -> bool { if (m % p != 0) return true; m /= p; return m % p != 0 && (n / p - 1) % p == 0; }; if (!test_factor(3) || !test_factor(5)) return false; static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6}; for (unsigned int p = 7, i = 0; p * p <= m; ++i) { if (!test_factor(p)) return false; p += wheel[i & 7]; } return m == 1 || (n / m - 1) % m == 0; } int main() { std::cout << "First 5 Giuga numbers:\n"; // n can't be 2 or divisible by 4 for (unsigned int i = 0, n = 6; i < 5; n += 4) { if (is_giuga(n)) { std::cout << n << '\n'; ++i; } } }
Giuga numbers
C++ from Wren
Definition A '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors '''f''' divide (n/f - 1) exactly. All known Giuga numbers are even though it is not known for certain that there are no odd examples. ;Example 30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and: * 30/2 - 1 = 14 is divisible by 2 * 30/3 - 1 = 9 is divisible by 3 * 30/5 - 1 = 5 is divisible by 5 ;Task Determine and show here the first four Giuga numbers. ;Stretch Determine the fifth Giuga number and any more you have the patience for. ;References * Wikipedia: Giuga number * OEIS:A007850 - Giuga numbers
#include <boost/rational.hpp> #include <algorithm> #include <cstdint> #include <iostream> #include <vector> using rational = boost::rational<uint64_t>; bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } uint64_t next_prime(uint64_t n) { while (!is_prime(n)) ++n; return n; } std::vector<uint64_t> divisors(uint64_t n) { std::vector<uint64_t> div{1}; for (uint64_t i = 2; i * i <= n; ++i) { if (n % i == 0) { div.push_back(i); if (i * i != n) div.push_back(n / i); } } div.push_back(n); sort(div.begin(), div.end()); return div; } void giuga_numbers(uint64_t n) { std::cout << "n = " << n << ":"; std::vector<uint64_t> p(n, 0); std::vector<rational> s(n, 0); p[2] = 2; p[1] = 2; s[1] = rational(1, 2); for (uint64_t t = 2; t > 1;) { p[t] = next_prime(p[t] + 1); s[t] = s[t - 1] + rational(1, p[t]); if (s[t] == 1 || s[t] + rational(n - t, p[t]) <= rational(1)) { --t; } else if (t < n - 2) { ++t; uint64_t c = s[t - 1].numerator(); uint64_t d = s[t - 1].denominator(); p[t] = std::max(p[t - 1], c / (d - c)); } else { uint64_t c = s[n - 2].numerator(); uint64_t d = s[n - 2].denominator(); uint64_t k = d * d + c - d; auto div = divisors(k); uint64_t count = (div.size() + 1) / 2; for (uint64_t i = 0; i < count; ++i) { uint64_t h = div[i]; if ((h + d) % (d - c) == 0 && (k / h + d) % (d - c) == 0) { uint64_t r1 = (h + d) / (d - c); uint64_t r2 = (k / h + d) / (d - c); if (r1 > p[n - 2] && r2 > p[n - 2] && r1 != r2 && is_prime(r1) && is_prime(r2)) { std::cout << ' ' << d * r1 * r2; } } } } } std::cout << '\n'; } int main() { for (uint64_t n = 3; n < 7; ++n) giuga_numbers(n); }
Globally replace text in several files
C++
Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
#include <fstream> #include <iterator> #include <boost/regex.hpp> #include <string> #include <iostream> int main( int argc , char *argv[ ] ) { boost::regex to_be_replaced( "Goodbye London\\s*!" ) ; std::string replacement( "Hello New York!" ) ; for ( int i = 1 ; i < argc ; i++ ) { std::ifstream infile ( argv[ i ] ) ; if ( infile ) { std::string filetext( (std::istreambuf_iterator<char>( infile )) , std::istreambuf_iterator<char>( ) ) ; std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ; infile.close( ) ; std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ; if ( outfile.is_open( ) ) { outfile << changed ; outfile.close( ) ; } } else std::cout << "Can't find file " << argv[ i ] << " !\n" ; } return 0 ; }
Gray code
C++
Karnaugh maps in order from left to right or top to bottom. Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] ;Reference * Converting Between Gray and Binary Codes. It includes step-by-step animations.
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) // utility function { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
Greatest subsequential sum
C++
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
#include <utility> // for std::pair #include <iterator> // for std::iterator_traits #include <iostream> // for std::cout #include <ostream> // for output operator and std::endl #include <algorithm> // for std::copy #include <iterator> // for std::output_iterator // Function template max_subseq // // Given a sequence of integers, find a subsequence which maximizes // the sum of its elements, that is, the elements of no other single // subsequence add up to a value larger than this one. // // Requirements: // * ForwardIterator is a forward iterator // * ForwardIterator's value_type is less-than comparable and addable // * default-construction of value_type gives the neutral element // (zero) // * operator+ and operator< are compatible (i.e. if a>zero and // b>zero, then a+b>zero, and if a<zero and b<zero, then a+b<zero) // * [begin,end) is a valid range // // Returns: // a pair of iterators describing the begin and end of the // subsequence template<typename ForwardIterator> std::pair<ForwardIterator, ForwardIterator> max_subseq(ForwardIterator begin, ForwardIterator end) { typedef typename std::iterator_traits<ForwardIterator>::value_type value_type; ForwardIterator seq_begin = begin, seq_end = seq_begin; value_type seq_sum = value_type(); ForwardIterator current_begin = begin; value_type current_sum = value_type(); value_type zero = value_type(); for (ForwardIterator iter = begin; iter != end; ++iter) { value_type value = *iter; if (zero < value) { if (current_sum < zero) { current_sum = zero; current_begin = iter; } } else { if (seq_sum < current_sum) { seq_begin = current_begin; seq_end = iter; seq_sum = current_sum; } } current_sum += value; } if (seq_sum < current_sum) { seq_begin = current_begin; seq_end = end; seq_sum = current_sum; } return std::make_pair(seq_begin, seq_end); } // the test array int array[] = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 }; // function template to find the one-past-end pointer to the array template<typename T, int N> int* end(T (&arr)[N]) { return arr+N; } int main() { // find the subsequence std::pair<int*, int*> seq = max_subseq(array, end(array)); // output it std::copy(seq.first, seq.second, std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0; }
Greyscale bars/Display
C++
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
#include <QtGui> #include "greytones.h" MyWidget::MyWidget( ) { setGeometry( 0, 0 , 640 , 480 ) ; } void MyWidget::paintEvent ( QPaintEvent * ) { QBrush myBrush( Qt::SolidPattern ) ; QPainter myPaint( this ) ; int run = 0 ; //how often have we run through the loop ? int colorcomp = 0 ; for ( int columncount = 8 ; columncount < 128 ; columncount *= 2 ) { int colorgap = 255 / columncount ; int columnwidth = 640 / columncount ; // 640 being the window width int columnheight = 480 / 4 ; //we're looking at quarters if ( run % 2 == 0 ) { //we start with black columns colorcomp = 0 ; } else { //we start with white columns colorcomp = 255 ; colorgap *= -1 ; //we keep subtracting color values } int ystart = 0 + columnheight * run ; //determines the y coordinate of the first column per row int xstart = 0 ; for ( int i = 0 ; i < columncount ; i++ ) { myBrush.setColor( QColor( colorcomp, colorcomp , colorcomp ) ) ; myPaint.fillRect( xstart , ystart , columnwidth , columnheight , myBrush ) ; xstart += columnwidth ; colorcomp += colorgap ; //we choose the next color } run++ ; } }
Hailstone sequence
C++
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#include <iostream> #include <vector> #include <utility> std::vector<int> hailstone(int i) { std::vector<int> v; while(true){ v.push_back(i); if (1 == i) break; i = (i % 2) ? (3 * i + 1) : (i / 2); } return v; } std::pair<int,int> find_longest_hailstone_seq(int n) { std::pair<int, int> maxseq(0, 0); int l; for(int i = 1; i < n; ++i){ l = hailstone(i).size(); if (l > maxseq.second) maxseq = std::make_pair(i, l); } return maxseq; } int main () { // Use the routine to show that the hailstone sequence for the number 27 std::vector<int> h27; h27 = hailstone(27); // has 112 elements int l = h27.size(); std::cout << "length of hailstone(27) is " << l; // starting with 27, 82, 41, 124 and std::cout << " first four elements of hailstone(27) are "; std::cout << h27[0] << " " << h27[1] << " " << h27[2] << " " << h27[3] << std::endl; // ending with 8, 4, 2, 1 std::cout << " last four elements of hailstone(27) are " << h27[l-4] << " " << h27[l-3] << " " << h27[l-2] << " " << h27[l-1] << std::endl; std::pair<int,int> m = find_longest_hailstone_seq(100000); std::cout << "the longest hailstone sequence under 100,000 is " << m.first << " with " << m.second << " elements." <<std::endl; return 0; }
Halt and catch fire
C++
Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an internal corruption has been detected and it would be dangerous and irresponsible to continue. ;References * Wikipedia: Halt and Catch Fire ;Related Tasks * [[Program termination]]
#include <stdexcept> int main() { throw std::runtime_error("boom"); }
Harshad or Niven series
C++
The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder. Assume that the series is defined as the numbers in increasing order. ;Task: The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: ::* list the first '''20''' members of the sequence, and ::* list the first Harshad number greater than '''1000'''. Show your output here. ;Related task :* Increasing gaps between consecutive Niven numbers ;See also * OEIS: A005349
#include <vector> #include <iostream> int sumDigits ( int number ) { int sum = 0 ; while ( number != 0 ) { sum += number % 10 ; number /= 10 ; } return sum ; } bool isHarshad ( int number ) { return number % ( sumDigits ( number ) ) == 0 ; } int main( ) { std::vector<int> harshads ; int i = 0 ; while ( harshads.size( ) != 20 ) { i++ ; if ( isHarshad ( i ) ) harshads.push_back( i ) ; } std::cout << "The first 20 Harshad numbers:\n" ; for ( int number : harshads ) std::cout << number << " " ; std::cout << std::endl ; int start = 1001 ; while ( ! ( isHarshad ( start ) ) ) start++ ; std::cout << "The smallest Harshad number greater than 1000 : " << start << '\n' ; return 0 ; }
Hash join
C++
{| class="wikitable" |- ! Input ! Output |- | {| style="border:none; border-collapse:collapse;" |- | style="border:none" | ''A'' = | style="border:none" | {| class="wikitable" |- ! Age !! Name |- | 27 || Jonah |- | 18 || Alan |- | 28 || Glory |- | 18 || Popeye |- | 28 || Alan |} | style="border:none; padding-left:1.5em;" rowspan="2" | | style="border:none" | ''B'' = | style="border:none" | {| class="wikitable" |- ! Character !! Nemesis |- | Jonah || Whales |- | Jonah || Spiders |- | Alan || Ghosts |- | Alan || Zombies |- | Glory || Buffy |} |- | style="border:none" | ''jA'' = | style="border:none" | Name (i.e. column 1) | style="border:none" | ''jB'' = | style="border:none" | Character (i.e. column 0) |} | {| class="wikitable" style="margin-left:1em" |- ! A.Age !! A.Name !! B.Character !! B.Nemesis |- | 27 || Jonah || Jonah || Whales |- | 27 || Jonah || Jonah || Spiders |- | 18 || Alan || Alan || Ghosts |- | 18 || Alan || Alan || Zombies |- | 28 || Glory || Glory || Buffy |- | 28 || Alan || Alan || Ghosts |- | 28 || Alan || Alan || Zombies |} |} The order of the rows in the output table is not significant. If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { // Age Name {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { // Character Nemesis {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"} , {"Alan", "Zombies"} , {"Glory", "Buffy"} }; std::ostream& operator<<(std::ostream& o, const tab_t& t) { for(size_t i = 0; i < t.size(); ++i) { o << i << ":"; for(const auto& e : t[i]) o << '\t' << e; o << std::endl; } return o; } tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) { std::unordered_multimap<std::string, size_t> hashmap; // hash for(size_t i = 0; i < a.size(); ++i) { hashmap.insert(std::make_pair(a[i][columna], i)); } // map tab_t result; for(size_t i = 0; i < b.size(); ++i) { auto range = hashmap.equal_range(b[i][columnb]); for(auto it = range.first; it != range.second; ++it) { tab_t::value_type row; row.insert(row.end() , a[it->second].begin() , a[it->second].end()); row.insert(row.end() , b[i].begin() , b[i].end()); result.push_back(std::move(row)); } } return result; } int main(int argc, char const *argv[]) { using namespace std; int ret = 0; cout << "Table A: " << endl << tab1 << endl; cout << "Table B: " << endl << tab2 << endl; auto tab3 = Join(tab1, 1, tab2, 0); cout << "Joined tables: " << endl << tab3 << endl; return ret; }
Haversine formula
C++
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#define _USE_MATH_DEFINES #include <math.h> #include <iostream> const static double EarthRadiusKm = 6372.8; inline double DegreeToRadian(double angle) { return M_PI * angle / 180.0; } class Coordinate { public: Coordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude) {} double Latitude() const { return myLatitude; } double Longitude() const { return myLongitude; } private: double myLatitude; double myLongitude; }; double HaversineDistance(const Coordinate& p1, const Coordinate& p2) { double latRad1 = DegreeToRadian(p1.Latitude()); double latRad2 = DegreeToRadian(p2.Latitude()); double lonRad1 = DegreeToRadian(p1.Longitude()); double lonRad2 = DegreeToRadian(p2.Longitude()); double diffLa = latRad2 - latRad1; double doffLo = lonRad2 - lonRad1; double computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2))); return 2 * EarthRadiusKm * computation; } int main() { Coordinate c1(36.12, -86.67); Coordinate c2(33.94, -118.4); std::cout << "Distance = " << HaversineDistance(c1, c2) << std::endl; return 0; }
Hello world/Line printer
C++
Cause a line printer attached to the computer to print a line containing the message: Hello World! ;Note: A line printer is not the same as standard output. A line printer was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
Hello world/Newbie
C++
Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the [[Hello world/Text]] task. * Assume the language-newbie is a programmer in another language. * Assume the language-newbie is competent in installing software for the platform. * Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor). * Refer to, (and link to), already existing documentation as much as possible (but provide a summary here). * Remember to state where to view the output. * If particular IDE's or editors are required that are not standard, then point to/explain their installation too. ;Note: * If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated. * You may use sub-headings if giving instructions for multiple platforms.
#include <iostream> int main() { using namespace std; cout << "Hello, World!" << endl; return 0; }
Here document
C++11
A ''here document'' (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a ''here document'' is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block. ;Task: Demonstrate the use of ''here documents'' within the language. ;Related task: * [[Documentation]]
#include <iostream> // Only for cout to demonstrate int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either opening or closing parentheses, a backslash, a tab, a vertical tab, a form feed, or a newline. It ends with a closing parenthesis (')'), the identifer (if you used one), and a double-quote. All characters are okay in a raw string, no escape sequences are necessary or recognized, and all whitespace is preserved. )EOF"; }
Heronian triangles
C++17
Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by: :::: A = \sqrt{s(s-a)(s-b)(s-c)}, where ''s'' is half the perimeter of the triangle; that is, :::: s=\frac{a+b+c}{2}. '''Heronian triangles''' are triangles whose sides ''and area'' are all integers. : An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle. Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor of all three sides is '''1''' (unity). This will exclude, for example, triangle '''6, 8, 10.''' ;Task: # Create a named function/method/procedure/... that implements Hero's formula. # Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. # Show the count of how many triangles are found. # Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths # Show the first ten ordered triangles in a table of sides, perimeter, and area. # Show a similar ordered table for those triangles with area = 210 Show all output here. '''Note''': when generating triangles it may help to restrict a <= b <= c
#include <tuple> #include <vector> #include <numeric> #include <iostream> #include <algorithm> #include <cmath> struct Triangle { int a{}; int b{}; int c{}; [[nodiscard]] constexpr auto perimeter() const noexcept { return a + b + c; } [[nodiscard]] constexpr auto area() const noexcept { const auto p_2 = static_cast<double>(perimeter()) / 2; const auto area_sq = p_2 * (p_2 - a) * (p_2 - b) * (p_2 - c); return std::sqrt(area_sq); } }; auto generate_triangles(int side_limit = 200) { std::vector<Triangle> result; for(int a = 1; a <= side_limit; ++a) for(int b = 1; b <= a; ++b) for(int c = a + 1 - b; c <= b; ++c) // skip too-small values of c, which will violate triangle inequality { Triangle t{ a, b, c }; const auto t_area = t.area(); if (t_area == 0) continue; if (std::floor(t_area) == std::ceil(t_area) && std::gcd(a, std::gcd(b, c)) == 1) result.push_back(t); } return result; } bool compare(const Triangle& lhs, const Triangle& rhs) noexcept { return std::make_tuple(lhs.area(), lhs.perimeter(), std::max(lhs.a, std::max(lhs.b, lhs.c))) < std::make_tuple(rhs.area(), rhs.perimeter(), std::max(rhs.a, std::max(rhs.b, rhs.c))); } struct area_compare { [[nodiscard]] constexpr bool operator()(const Triangle& t, int i) const noexcept { return t.area() < i; } [[nodiscard]] constexpr bool operator()(int i, const Triangle& t) const noexcept { return i < t.area(); } }; int main() { auto tri = generate_triangles(); std::cout << "There are " << tri.size() << " primitive Heronian triangles with sides up to 200\n\n"; std::cout << "First ten when ordered by increasing area, then perimeter, then maximum sides:\n"; std::sort(tri.begin(), tri.end(), compare); std::cout << "area\tperimeter\tsides\n"; for(int i = 0; i < 10; ++i) std::cout << tri[i].area() << '\t' << tri[i].perimeter() << "\t\t" << tri[i].a << 'x' << tri[i].b << 'x' << tri[i].c << '\n'; std::cout << "\nAll with area 210 subject to the previous ordering:\n"; auto range = std::equal_range(tri.begin(), tri.end(), 210, area_compare()); std::cout << "area\tperimeter\tsides\n"; for(auto it = range.first; it != range.second; ++it) std::cout << (*it).area() << '\t' << (*it).perimeter() << "\t\t" << it->a << 'x' << it->b << 'x' << it->c << '\n'; }
Hofstadter-Conway $10,000 sequence
C++
The definition of the sequence is colloquially described as: * Starting with the list [1,1], * Take the last number in the list so far: 1, I'll call it x. * Count forward x places from the beginning of the list to find the first number to add (1) * Count backward x places from the end of the list to find the second number to add (1) * Add the two indexed numbers from the list and the result becomes the next number in the list (1+1) * This would then produce [1,1,2] where 2 is the third element of the sequence. Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''. A less wordy description of the sequence is: a(1)=a(2)=1 a(n)=a(a(n-1))+a(n-a(n-1)) The sequence begins: 1, 1, 2, 2, 3, 4, 4, 4, 5, ... Interesting features of the sequence are that: * a(n)/n tends to 0.5 as n grows towards infinity. * a(n)/n where n is a power of 2 is 0.5 * For n>4 the maximal value of a(n)/n between successive powers of 2 decreases. a(n) / n for n in 1..256 The sequence is so named because John Conway offered a prize of $10,000 to the first person who could find the first position, p in the sequence where |a(n)/n| < 0.55 for all n > p It was later found that Hofstadter had also done prior work on the sequence. The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article). ;Task: # Create a routine to generate members of the Hofstadter-Conway $10,000 sequence. # Use it to show the maxima of a(n)/n between successive powers of two up to 2**20 # As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20 ;Also see: * Conways Challenge Sequence, Mallows' own account. * Mathworld Article.
#include <deque> #include <iostream> int hcseq(int n) { static std::deque<int> seq(2, 1); while (seq.size() < n) { int x = seq.back(); seq.push_back(seq[x-1] + seq[seq.size()-x]); } return seq[n-1]; } int main() { int pow2 = 1; for (int i = 0; i < 20; ++i) { int pow2next = 2*pow2; double max = 0; for (int n = pow2; n < pow2next; ++n) { double anon = hcseq(n)/double(n); if (anon > max) max = anon; } std::cout << "maximum of a(n)/n between 2^" << i << " (" << pow2 << ") and 2^" << i+1 << " (" << pow2next << ") is " << max << "\n"; pow2 = pow2next; } }
Hofstadter Figure-Figure sequences
C++ 11, 14, 17
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
#include <iomanip> #include <iostream> #include <set> #include <vector> using namespace std; unsigned hofstadter(unsigned rlistSize, unsigned slistSize) { auto n = rlistSize > slistSize ? rlistSize : slistSize; auto rlist = new vector<unsigned> { 1, 3, 7 }; auto slist = new vector<unsigned> { 2, 4, 5, 6 }; auto list = rlistSize > 0 ? rlist : slist; auto target_size = rlistSize > 0 ? rlistSize : slistSize; while (list->size() > target_size) list->pop_back(); while (list->size() < target_size) { auto lastIndex = rlist->size() - 1; auto lastr = (*rlist)[lastIndex]; auto r = lastr + (*slist)[lastIndex]; rlist->push_back(r); for (auto s = lastr + 1; s < r && list->size() < target_size;) slist->push_back(s++); } auto v = (*list)[n - 1]; delete rlist; delete slist; return v; } ostream& operator<<(ostream& os, const set<unsigned>& s) { cout << '(' << s.size() << "):"; auto i = 0; for (auto c = s.begin(); c != s.end();) { if (i++ % 20 == 0) os << endl; os << setw(5) << *c++; } return os; } int main(int argc, const char* argv[]) { const auto v1 = atoi(argv[1]); const auto v2 = atoi(argv[2]); set<unsigned> r, s; for (auto n = 1; n <= v2; n++) { if (n <= v1) r.insert(hofstadter(n, 0)); s.insert(hofstadter(0, n)); } cout << "R" << r << endl; cout << "S" << s << endl; int m = max(*r.rbegin(), *s.rbegin()); for (auto n = 1; n <= m; n++) if (r.count(n) == s.count(n)) clog << "integer " << n << " either in both or neither set" << endl; return 0; }
Hofstadter Q sequence
C++
The Hofstadter Q sequence is defined as: :: \begin{align} Q(1)&=Q(2)=1, \\ Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2. \end{align} It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence. ;Task: * Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 * Confirm and display that the 1000th term is: 502 ;Optional extra credit * Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term. * Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large. (This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
Horner's rule for polynomial evaluation
C++
A fast scheme for evaluating a polynomial such as: : -19+7x-4x^2+6x^3\, when : x=3\;. is to arrange the computation as follows: : ((((0) x + 6) x + (-4)) x + 7) x + (-19)\; And compute the result from the innermost brackets outwards as in this pseudocode: coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order'' x ''':=''' 3 accumulator ''':=''' 0 '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do''' ''# Assumes 1-based indexing for arrays'' accumulator ''':=''' ( accumulator * x ) + coefficients[i] '''done''' ''# accumulator now has the answer'' '''Task Description''' :Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule. Cf. [[Formal power series]]
#include <iostream> #include <vector> using namespace std; double horner(vector<double> v, double x) { double s = 0; for( vector<double>::const_reverse_iterator i = v.rbegin(); i != v.rend(); i++ ) s = s*x + *i; return s; } int main() { double c[] = { -19, 7, -4, 6 }; vector<double> v(c, c + sizeof(c)/sizeof(double)); cout << horner(v, 3.0) << endl; return 0; }
ISBN13 check digit
C++ from C
Validate the check digit of an ISBN-13 code: ::* Multiply every other digit by '''3'''. ::* Add these numbers and the other digits. ::* Take the remainder of this number after division by '''10'''. ::* If it is '''0''', the ISBN-13 check digit is correct. You might use the following codes for testing: ::::* 978-0596528126 (good) ::::* 978-0596528120 (bad) ::::* 978-1788399081 (good) ::::* 978-1788399083 (bad) Show output here, on this page ;See also: :* for details: 13-digit ISBN method of validation. (installs cookies.)
#include <iostream> bool check_isbn13(std::string isbn) { int count = 0; int sum = 0; for (auto ch : isbn) { /* skip hyphens or spaces */ if (ch == ' ' || ch == '-') { continue; } if (ch < '0' || ch > '9') { return false; } if (count & 1) { sum += 3 * (ch - '0'); } else { sum += ch - '0'; } count++; } if (count != 13) { return false; } return sum % 10 == 0; } int main() { auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" }; for (auto isbn : isbns) { std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n'; } return 0; }
I before E except after C
C++
The phrase "I before E, except after C" is a widely known mnemonic which is supposed to help when spelling English words. ;Task: Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually: :::# ''"I before E when not preceded by C"'' :::# ''"E before I when preceded by C"'' If both sub-phrases are plausible then the original phrase can be said to be plausible. Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate). ;Stretch goal: As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account. ''Show your output here as well as your program.'' ;cf.: * Schools to rethink 'i before e' - BBC news, 20 June 2009 * I Before E Except After C - QI Series 8 Ep 14, (humorous) * Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string& pat) { propats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); } void add_against(const std::string& pat) { againstpats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); } bool plausible() const { return pro_ > against_*2; } void check(const char * buf, uint32_t len) { for (auto i = propats_.begin(), ii = propats_.end(); i != ii; ++i) { uint32_t pos = 0; boost::cmatch m; if (std::get<1>(*i) && pos > 0) continue; while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) { ++pro_; if (pos > 0) std::cerr << name_ << " [pro] multiple matches in: " << buf << "\n"; pos += m.position() + m.length(); } } for (auto i = againstpats_.begin(), ii = againstpats_.end(); i != ii; ++i) { uint32_t pos = 0; boost::cmatch m; if (std::get<1>(*i) && pos > 0) continue; while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) { ++against_; if (pos > 0) std::cerr << name_ << " [against] multiple matches in: " << buf << "\n"; pos += m.position() + m.length(); } } } friend std::ostream& operator<<(std::ostream& os, const Claim& c); private: std::string name_; uint32_t pro_; uint32_t against_; // tuple<regex,begin only> std::vector<std::tuple<boost::regex,bool>> propats_; std::vector<std::tuple<boost::regex,bool>> againstpats_; }; std::ostream& operator<<(std::ostream& os, const Claim& c) { os << c.name_ << ": matches: " << c.pro_ << " vs. counter matches: " << c.against_ << ". "; os << "Plausibility: " << (c.plausible() ? "yes" : "no") << "."; return os; } int main(int argc, char ** argv) { try { if (argc < 2) throw std::runtime_error("No input file."); std::ifstream is(argv[1]); if (! is) throw std::runtime_error("Input file not valid."); Claim ieclaim("[^c]ie"); ieclaim.add_pro("[^c]ie"); ieclaim.add_pro("^ie"); ieclaim.add_against("[^c]ei"); ieclaim.add_against("^ei"); Claim ceiclaim("cei"); ceiclaim.add_pro("cei"); ceiclaim.add_against("cie"); { const uint32_t MAXLEN = 32; char buf[MAXLEN]; uint32_t longest = 0; while (is) { is.getline(buf, sizeof(buf)); if (is.gcount() <= 0) break; else if (is.gcount() > longest) longest = is.gcount(); ieclaim.check(buf, is.gcount()); ceiclaim.check(buf, is.gcount()); } if (longest >= MAXLEN) throw std::runtime_error("Buffer too small."); } std::cout << ieclaim << "\n"; std::cout << ceiclaim << "\n"; std::cout << "Overall plausibility: " << (ieclaim.plausible() && ceiclaim.plausible() ? "yes" : "no") << "\n"; } catch (const std::exception& ex) { std::cerr << "*** Error: " << ex.what() << "\n"; return -1; } return 0; }
Imaginary base numbers
C++ from C#
Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. ''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]'' Other imaginary bases are possible too but are not as widely discussed and aren't specifically named. '''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. At a minimum, support quater-imaginary (base 2i). For extra kudos, support positive or negative bases 2i through 6i (or higher). As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base. See Wikipedia: Quater-imaginary_base for more details. For reference, here are some some decimal and complex numbers converted to quater-imaginary. Base 10 Base 2i 1 1 2 2 3 3 4 10300 5 10301 6 10302 7 10303 8 10200 9 10201 10 10202 11 10203 12 10100 13 10101 14 10102 15 10103 16 10000 Base 10 Base 2i -1 103 -2 102 -3 101 -4 100 -5 203 -6 202 -7 201 -8 200 -9 303 -10 302 -11 301 -12 300 -13 1030003 -14 1030002 -15 1030001 -16 1030000 Base 10 Base 2i 1i 10.2 2i 10.0 3i 20.2 4i 20.0 5i 30.2 6i 30.0 7i 103000.2 8i 103000.0 9i 103010.2 10i 103010.0 11i 103020.2 12i 103020.0 13i 103030.2 14i 103030.0 15i 102000.2 16i 102000.0 Base 10 Base 2i -1i 0.2 -2i 1030.0 -3i 1030.2 -4i 1020.0 -5i 1020.2 -6i 1010.0 -7i 1010.2 -8i 1000.0 -9i 1000.2 -10i 2030.0 -11i 2030.2 -12i 2020.0 -13i 2020.2 -14i 2010.0 -15i 2010.2 -16i 2000.0
#include <algorithm> #include <complex> #include <iomanip> #include <iostream> std::complex<double> inv(const std::complex<double>& c) { double denom = c.real() * c.real() + c.imag() * c.imag(); return std::complex<double>(c.real() / denom, -c.imag() / denom); } class QuaterImaginary { public: QuaterImaginary(const std::string& s) : b2i(s) { static std::string base("0123."); if (b2i.empty() || std::any_of(s.cbegin(), s.cend(), [](char c) { return base.find(c) == std::string::npos; }) || std::count(s.cbegin(), s.cend(), '.') > 1) { throw std::runtime_error("Invalid base 2i number"); } } QuaterImaginary& operator=(const QuaterImaginary& q) { b2i = q.b2i; return *this; } std::complex<double> toComplex() const { int pointPos = b2i.find('.'); int posLen = (pointPos != std::string::npos) ? pointPos : b2i.length(); std::complex<double> sum(0.0, 0.0); std::complex<double> prod(1.0, 0.0); for (int j = 0; j < posLen; j++) { double k = (b2i[posLen - 1 - j] - '0'); if (k > 0.0) { sum += prod * k; } prod *= twoI; } if (pointPos != -1) { prod = invTwoI; for (size_t j = posLen + 1; j < b2i.length(); j++) { double k = (b2i[j] - '0'); if (k > 0.0) { sum += prod * k; } prod *= invTwoI; } } return sum; } friend std::ostream& operator<<(std::ostream&, const QuaterImaginary&); private: const std::complex<double> twoI{ 0.0, 2.0 }; const std::complex<double> invTwoI = inv(twoI); std::string b2i; }; std::ostream& operator<<(std::ostream& os, const QuaterImaginary& q) { return os << q.b2i; } // only works properly if 'real' and 'imag' are both integral QuaterImaginary toQuaterImaginary(const std::complex<double>& c) { if (c.real() == 0.0 && c.imag() == 0.0) return QuaterImaginary("0"); int re = (int)c.real(); int im = (int)c.imag(); int fi = -1; std::stringstream ss; while (re != 0) { int rem = re % -4; re /= -4; if (rem < 0) { rem = 4 + rem; re++; } ss << rem << 0; } if (im != 0) { double f = (std::complex<double>(0.0, c.imag()) / std::complex<double>(0.0, 2.0)).real(); im = (int)ceil(f); f = -4.0 * (f - im); size_t index = 1; while (im != 0) { int rem = im % -4; im /= -4; if (rem < 0) { rem = 4 + rem; im++; } if (index < ss.str().length()) { ss.str()[index] = (char)(rem + 48); } else { ss << 0 << rem; } index += 2; } fi = (int)f; } auto r = ss.str(); std::reverse(r.begin(), r.end()); ss.str(""); ss.clear(); ss << r; if (fi != -1) ss << '.' << fi; r = ss.str(); r.erase(r.begin(), std::find_if(r.begin(), r.end(), [](char c) { return c != '0'; })); if (r[0] == '.')r = "0" + r; return QuaterImaginary(r); } int main() { using namespace std; for (int i = 1; i <= 16; i++) { complex<double> c1(i, 0); QuaterImaginary qi = toQuaterImaginary(c1); complex<double> c2 = qi.toComplex(); cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << " "; c1 = -c1; qi = toQuaterImaginary(c1); c2 = qi.toComplex(); cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << endl; } cout << endl; for (int i = 1; i <= 16; i++) { complex<double> c1(0, i); QuaterImaginary qi = toQuaterImaginary(c1); complex<double> c2 = qi.toComplex(); cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << " "; c1 = -c1; qi = toQuaterImaginary(c1); c2 = qi.toComplex(); cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << endl; } return 0; }
Increasing gaps between consecutive Niven numbers
C++
Note: '''Niven''' numbers are also called '''Harshad''' numbers. :::: They are also called '''multidigital''' numbers. '''Niven''' numbers are positive integers which are evenly divisible by the sum of its digits (expressed in base ten). ''Evenly divisible'' means ''divisible with no remainder''. ;Task: :* find the gap (difference) of a Niven number from the previous Niven number :* if the gap is ''larger'' than the (highest) previous gap, then: :::* show the index (occurrence) of the gap (the 1st gap is '''1''') :::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''') :::* show the Niven number that starts the gap :::* show all numbers with comma separators where appropriate (optional) :::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864''' :* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number :* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer :* show all output here, on this page ;Related task: :* Harshad or Niven series. ;Also see: :* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers. :* (PDF) version of the (above) article by Doyon.
#include <cstdint> #include <iomanip> #include <iostream> // Returns the sum of the digits of n given the // sum of the digits of n - 1 uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false; return n % d == 0; } int main() { // Print numbers with commas std::cout.imbue(std::locale("")); uint64_t previous = 1, gap = 0, sum = 0; int niven_index = 0, gap_index = 1; std::cout << "Gap index Gap Niven index Niven number\n"; for (uint64_t niven = 1; gap_index <= 32; ++niven) { sum = digit_sum(niven, sum); if (divisible(niven, sum)) { if (niven > previous + gap) { gap = niven - previous; std::cout << std::setw(9) << gap_index++ << std::setw(5) << gap << std::setw(15) << niven_index << std::setw(16) << previous << '\n'; } previous = niven; ++niven_index; } } return 0; }
Integer overflow
C++
Some languages support one or more integer types of the underlying processor. This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit. The integers supported by such a type can be ''signed'' or ''unsigned''. Arithmetic for machine level integers can often be done by single CPU instructions. This allows high performance and is the main reason to support machine level integers. ;Definition: An integer overflow happens when the result of a computation does not fit into the fixed size integer. The result can be too small or too big to be representable in the fixed size integer. ;Task: When a language has fixed size integer types, create a program that does arithmetic computations for the fixed size integers of the language. These computations must be done such that the result would overflow. The program should demonstrate what the following expressions do. For 32-bit signed integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit signed integer |- | -(-2147483647-1) | 2147483648 |- | 2000000000 + 2000000000 | 4000000000 |- | -2147483647 - 2147483647 | -4294967294 |- | 46341 * 46341 | 2147488281 |- | (-2147483647-1) / -1 | 2147483648 |} For 64-bit signed integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit signed integer |- | -(-9223372036854775807-1) | 9223372036854775808 |- | 5000000000000000000+5000000000000000000 | 10000000000000000000 |- | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |- | 3037000500 * 3037000500 | 9223372037000250000 |- | (-9223372036854775807-1) / -1 | 9223372036854775808 |} For 32-bit unsigned integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit unsigned integer |- | -4294967295 | -4294967295 |- | 3000000000 + 3000000000 | 6000000000 |- | 2147483647 - 4294967295 | -2147483648 |- | 65537 * 65537 | 4295098369 |} For 64-bit unsigned integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit unsigned integer |- | -18446744073709551615 | -18446744073709551615 |- | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |- | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |- | 4294967296 * 4294967296 | 18446744073709551616 |} ;Notes: :* When the integer overflow does trigger an exception show how the exception is caught. :* When the integer overflow produces some value, print it. :* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results. :* This should be done for signed and unsigned integers of various sizes supported by the computer programming language. :* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted. :* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
Same as C, except that if <code>std::numeric_limits<IntegerType>::is_modulo</code> is <code>true</code>, then the type <code>IntegerType</code> uses modulo arithmetic (the behavior is defined), even if it is a signed type. A C++ program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
Integer sequence
C++
Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library. If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.
// Using the proposed unbounded integer library #include <iostream> #include <seminumeric> int main() { try { auto i = std::experimental::seminumeric::integer{}; while (true) std::cout << ++i << '\n'; } catch (...) { // Do nothing } }
Intersecting number wheels
C++ from D
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { // empty } Wheel(std::initializer_list<char> data) : values(data), index(0) { //values.assign(data); if (values.size() < 1) { throw new std::runtime_error("Not enough elements"); } } char front() { return values[index]; } void popFront() { index = (index + 1) % values.size(); } }; struct NamedWheel { private: std::map<char, Wheel> wheels; public: void put(char c, Wheel w) { wheels[c] = w; } char front(char c) { char v = wheels[c].front(); while ('A' <= v && v <= 'Z') { v = wheels[v].front(); } return v; } void popFront(char c) { auto v = wheels[c].front(); wheels[c].popFront(); while ('A' <= v && v <= 'Z') { auto d = wheels[v].front(); wheels[v].popFront(); v = d; } } }; void group1() { Wheel w({ '1', '2', '3' }); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << w.front(); w.popFront(); } std::cout << '\n'; } void group2() { Wheel a({ '1', 'B', '2' }); Wheel b({ '3', '4' }); NamedWheel n; n.put('A', a); n.put('B', b); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << n.front('A'); n.popFront('A'); } std::cout << '\n'; } void group3() { Wheel a({ '1', 'D', 'D' }); Wheel d({ '6', '7', '8' }); NamedWheel n; n.put('A', a); n.put('D', d); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << n.front('A'); n.popFront('A'); } std::cout << '\n'; } void group4() { Wheel a({ '1', 'B', 'C' }); Wheel b({ '3', '4' }); Wheel c({ '5', 'B' }); NamedWheel n; n.put('A', a); n.put('B', b); n.put('C', c); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << n.front('A'); n.popFront('A'); } std::cout << '\n'; } int main() { group1(); group2(); group3(); group4(); return 0; }
Inverted syntax
C++
'''Inverted syntax with conditional expressions''' In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumbrella=true IF raining=true '''Inverted syntax with assignment''' In traditional syntax, assignments are usually expressed with the variable appearing before the expression: a = 6 In inverted syntax, the expression appears before the variable: 6 = a '''Task''' The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.
class invertedAssign { int data; public: invertedAssign(int data):data(data){} int getData(){return data;} void operator=(invertedAssign& other) const { other.data = this->data; } }; #include <iostream> int main(){ invertedAssign a = 0; invertedAssign b = 42; std::cout << a.getData() << ' ' << b.getData() << '\n'; b = a; std::cout << a.getData() << ' ' << b.getData() << '\n'; }
Iterated digits squaring
C++
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): : Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page ;Related tasks: * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]]
#include <iostream> // returns sum of squares of digits of n unsigned int sum_square_digits(unsigned int n) { int i,num=n,sum=0; // process digits one at a time until there are none left while (num > 0) { // peal off the last digit from the number int digit=num % 10; num=(num - digit)/10; // add it's square to the sum sum+=digit*digit; } return sum; } int main(void) { unsigned int i=0,result=0, count=0; for (i=1; i<=100000000; i++) { // if not 1 or 89, start the iteration if ((i != 1) || (i != 89)) { result = sum_square_digits(i); } // otherwise we're done already else { result = i; } // while we haven't reached 1 or 89, keep iterating while ((result != 1) && (result != 89)) { result = sum_square_digits(result); } if (result == 89) { count++; } } std::cout << count << std::endl; return 0; }
Jacobi symbol
C++
The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) * (a | p) 1 if a is a square (mod p) * (a | p) -1 if a is not a square (mod p) * (a | p) 0 if a 0 If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n). ;Task: Calculate the Jacobi symbol (a | n). ;Reference: * Wikipedia article on Jacobi symbol.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
Jaro similarity
C++ from C
The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match. ;;Definition The Jaro similarity d_j of two given strings s_1 and s_2 is : d_j = \left\{ \begin{array}{l l} 0 & \text{if }m = 0\\ \frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right. Where: * m is the number of ''matching characters''; * t is half the number of ''transpositions''. Two characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters. Each character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one. ;;Example Given the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find: * m = 4 * |s_1| = 6 * |s_2| = 5 * t = 0 We find a Jaro score of: : d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822 ;Task Implement the Jaro algorithm and show the similarity scores for each of the following pairs: * ("MARTHA", "MARHTA") * ("DIXON", "DICKSONX") * ("JELLYFISH", "SMELLYFISH") ; See also * Jaro-Winkler distance on Wikipedia.
#include <algorithm> #include <iostream> #include <string> double jaro(const std::string s1, const std::string s2) { const uint l1 = s1.length(), l2 = s2.length(); if (l1 == 0) return l2 == 0 ? 1.0 : 0.0; const uint match_distance = std::max(l1, l2) / 2 - 1; bool s1_matches[l1]; bool s2_matches[l2]; std::fill(s1_matches, s1_matches + l1, false); std::fill(s2_matches, s2_matches + l2, false); uint matches = 0; for (uint i = 0; i < l1; i++) { const int end = std::min(i + match_distance + 1, l2); for (int k = std::max(0u, i - match_distance); k < end; k++) if (!s2_matches[k] && s1[i] == s2[k]) { s1_matches[i] = true; s2_matches[k] = true; matches++; break; } } if (matches == 0) return 0.0; double t = 0.0; uint k = 0; for (uint i = 0; i < l1; i++) if (s1_matches[i]) { while (!s2_matches[k]) k++; if (s1[i] != s2[k]) t += 0.5; k++; } const double m = matches; return (m / l1 + m / l2 + (m - t) / m) / 3.0; } int main() { using namespace std; cout << jaro("MARTHA", "MARHTA") << endl; cout << jaro("DIXON", "DICKSONX") << endl; cout << jaro("JELLYFISH", "SMELLYFISH") << endl; return 0; }
Jewels and stones
C++ from D
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct. The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'. Note that: :# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. :# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'. :# The parameters do not need to have exactly the same names. :# Validating the arguments is unnecessary. So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3. This task was inspired by this problem.
#include <algorithm> #include <iostream> int countJewels(const std::string& s, const std::string& j) { int count = 0; for (char c : s) { if (j.find(c) != std::string::npos) { count++; } } return count; } int main() { using namespace std; cout << countJewels("aAAbbbb", "aA") << endl; cout << countJewels("ZZ", "z") << endl; return 0; }
Julia set
C++
Task Generate and draw a Julia set. ;Related tasks * Mandelbrot Set
#include <windows.h> #include <string> #include <complex> const int BMP_SIZE = 600, ITERATIONS = 512; const long double FCT = 2.85, hFCT = FCT / 2.0; 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; } DWORD* bits() const { 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 julia { public: void draw( std::complex<long double> k ) { bmp.create( BMP_SIZE, BMP_SIZE ); DWORD* bits = bmp.bits(); int res, pos; std::complex<long double> c, factor( FCT / BMP_SIZE, FCT / BMP_SIZE ) ; for( int y = 0; y < BMP_SIZE; y++ ) { pos = y * BMP_SIZE; c.imag( ( factor.imag() * y ) + -hFCT ); for( int x = 0; x < BMP_SIZE; x++ ) { c.real( factor.real() * x + -hFCT ); res = inSet( c, k ); if( res ) { int n_res = res % 255; if( res < ( ITERATIONS >> 1 ) ) res = RGB( n_res << 2, n_res << 3, n_res << 4 ); else res = RGB( n_res << 4, n_res << 2, n_res << 5 ); } bits[pos++] = res; } } bmp.saveBitmap( "./js.bmp" ); } private: int inSet( std::complex<long double> z, std::complex<long double> c ) { long double dist;//, three = 3.0; for( int ec = 0; ec < ITERATIONS; ec++ ) { z = z * z; z = z + c; dist = ( z.imag() * z.imag() ) + ( z.real() * z.real() ); if( dist > 3 ) return( ec ); } return 0; } myBitmap bmp; }; int main( int argc, char* argv[] ) { std::complex<long double> c; long double factor = FCT / BMP_SIZE; c.imag( ( factor * 184 ) + -1.4 ); c.real( ( factor * 307 ) + -2.0 ); julia j; j.draw( c ); return 0; }
Jump anywhere
C++
Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range. This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions! * Some languages can ''go to'' any global label in a program. * Some languages can break multiple function calls, also known as ''unwinding the call stack''. * Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation). These jumps are not all alike. A simple ''goto'' never touches the call stack. A continuation saves the call stack, so you can continue a function call after it ends. ;Task: Use your language to demonstrate the various types of jumps that it supports. Because the possibilities vary by language, this task is not specific. You have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
#include <iostream> #include <utility> using namespace std; int main(void) { cout << "Find a solution to i = 2 * j - 7\n"; pair<int, int> answer; for(int i = 0; true; i++) { for(int j = 0; j < i; j++) { if( i == 2 * j - 7) { // use brute force and run until a solution is found answer = make_pair(i, j); goto loopexit; } } } loopexit: cout << answer.first << " = 2 * " << answer.second << " - 7\n\n"; // jumping out of nested loops is the main usage of goto in // C++. goto can be used in other places but there is usually // a better construct. goto is not allowed to jump across // initialized variables which limits where it can be used. // this is case where C++ is more restrictive than C. goto spagetti; int k; k = 9; // this is assignment, can be jumped over /* The line below won't compile because a goto is not allowed * to jump over an initialized value. int j = 9; */ spagetti: cout << "k = " << k << "\n"; // k was never initialized, accessing it is undefined behavior }