_id
stringlengths
2
5
text
stringlengths
7
10.9k
title
stringclasses
1 value
c655
#include <concepts> #include <iostream> void PrintMatrix(std::predicate<int, int, int> auto f, int size) { for(int y = 0; y < size; y++) { for(int x = 0; x < size; x++) { std::cout << " " << f(x, y, size); } std::cout << "\n"; } std::cout << "\n"; } int main() { auto diagonals = [](int x, int y, int size) { return x == y || ((size - x - 1) == y); }; PrintMatrix(diagonals, 8); PrintMatrix(diagonals, 9); }
c656
#include <string> #include <set> #include <list> #include <map> #include <iostream> struct Employee { std::string Name; std::string ID; unsigned long Salary; std::string Department; Employee(std::string _Name = "", std::string _ID = "", unsigned long _Salary = 0, std::string _Department = "") : Name(_Name), ID(_ID), Salary(_Salary), Department(_Department) { } void display(std::ostream& out) const { out << Name << "\t" << ID << "\t" << Salary << "\t" << Department << std::endl; } }; struct CompareEarners { bool operator()(const Employee& e1, const Employee& e2) { return (e1.Salary > e2.Salary); } }; typedef std::list<Employee> EMPLOYEELIST; typedef std::set<Employee, CompareEarners> DEPARTMENTPAYROLL; typedef std::map<std::string, DEPARTMENTPAYROLL> DEPARTMENTLIST; void initialize(EMPLOYEELIST& Employees) { Employees.push_back(Employee("Tyler Bennett", "E10297", 32000, "D101")); Employees.push_back(Employee("John Rappl", "E21437", 47000, "D050")); Employees.push_back(Employee("George Woltman", "E21437", 53500, "D101")); Employees.push_back(Employee("Adam Smith", "E21437", 18000, "D202")); Employees.push_back(Employee("Claire Buckman", "E39876", 27800, "D202")); Employees.push_back(Employee("David McClellan", "E04242", 41500, "D101")); Employees.push_back(Employee("Rich Holcomb", "E01234", 49500, "D202")); Employees.push_back(Employee("Nathan Adams", "E41298", 21900, "D050")); Employees.push_back(Employee("Richard Potter", "E43128", 15900, "D101")); Employees.push_back(Employee("David Motsinger", "E27002", 19250, "D202")); Employees.push_back(Employee("Tim Sampair", "E03033", 27000, "D101")); Employees.push_back(Employee("Kim Arlich", "E10001", 57000, "D190")); Employees.push_back(Employee("Timothy Grove", "E16398", 29900, "D190")); } void group(EMPLOYEELIST& Employees, DEPARTMENTLIST& Departments) { for( EMPLOYEELIST::iterator iEmployee = Employees.begin(); Employees.end() != iEmployee; ++iEmployee ) { DEPARTMENTPAYROLL& groupSet = Departments[iEmployee->Department]; groupSet.insert(*iEmployee); } } void present(DEPARTMENTLIST& Departments, unsigned int N) { for( DEPARTMENTLIST::iterator iDepartment = Departments.begin(); Departments.end() != iDepartment; ++iDepartment ) { std::cout << "In department " << iDepartment->first << std::endl; std::cout << "Name\t\tID\tSalary\tDepartment" << std::endl; unsigned int rank = 1; for( DEPARTMENTPAYROLL::iterator iEmployee = iDepartment->second.begin(); ( iDepartment->second.end() != iEmployee) && (rank <= N); ++iEmployee, ++rank ) { iEmployee->display(std::cout); } std::cout << std::endl; } } int main(int argc, char* argv[]) { EMPLOYEELIST Employees; initialize(Employees); DEPARTMENTLIST Departments; group(Employees, Departments); present(Departments, 3); return 0; }
c657
#include <vector> #include <iostream> #include <fstream> #include <sstream> typedef struct { int s[4]; }userI; class jit{ public: void decode( std::string& file, std::vector<userI>& ui ) { std::ifstream f( file.c_str(), std::ios_base::in ); fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() ); f.close(); for( std::vector<userI>::iterator t = ui.begin(); t != ui.end(); t++ ) { if( !decode( ( *t ).s ) ) break; } std::cout << "\n\n"; } private: bool decode( int* ui ) { int l = 0, t = 0, p = 0, c = 0, a = 0; for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) { if( p == ui[0] && l == ui[1] && t == ui[2] && c == ui[3] ) { if( *i == '!' ) return false; std::cout << *i; return true; } if( *i == '\n' ) { l++; t = c = 0; } else if( *i == '\t' ) { t++; c = 0; } else if( *i == '\f' ) { p++; l = t = c = 0; } else { c++;} } return false; } std::string fileBuffer; }; void getUserInput( std::vector<userI>& u ) { std::string h = "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 " "0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 33 0 50 0 46 0 54 0 76 0 47 0 84 2 28"; std::stringstream ss( h ); userI a; int x = 0; while( std::getline( ss, h, ' ' ) ) { a.s[x] = atoi( h.c_str() ); if( ++x == 4 ) { u.push_back( a ); x = 0; } } } int main( int argc, char* argv[] ) { std::vector<userI> ui; getUserInput( ui ); jit j; j.decode( std::string( "theRaven.txt" ), ui ); return 0; }
c658
#include <iostream> #include <time.h> using namespace std; const int MAX = 30; class cSort { public: void sort( int* arr, int len ) { int mi, mx, z = 0; findMinMax( arr, len, mi, mx ); int nlen = ( mx - mi ) + 1; int* temp = new int[nlen]; memset( temp, 0, nlen * sizeof( int ) ); for( int i = 0; i < len; i++ ) temp[arr[i] - mi]++; for( int i = mi; i <= mx; i++ ) { while( temp[i - mi] ) { arr[z++] = i; temp[i - mi]--; } } delete [] temp; } private: void findMinMax( int* arr, int len, int& mi, int& mx ) { mi = INT_MAX; mx = 0; for( int i = 0; i < len; i++ ) { if( arr[i] > mx ) mx = arr[i]; if( arr[i] < mi ) mi = arr[i]; } } }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); int arr[MAX]; for( int i = 0; i < MAX; i++ ) arr[i] = rand() % 140 - rand() % 40 + 1; for( int i = 0; i < MAX; i++ ) cout << arr[i] << ", "; cout << endl << endl; cSort s; s.sort( arr, MAX ); for( int i = 0; i < MAX; i++ ) cout << arr[i] << ", "; cout << endl << endl; return system( "pause" ); }
c659
#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; }
c660
#include <iostream> #include <math.h> struct PolarPoint; struct CartesianPoint { double x; double y; operator PolarPoint(); }; struct PolarPoint { double rho; double theta; operator CartesianPoint(); }; CartesianPoint::operator PolarPoint() { return PolarPoint { sqrt(x*x + y*y), atan2(y, x) }; } PolarPoint::operator CartesianPoint() { return CartesianPoint { rho * cos(theta), rho * sin(theta) }; } int main() { CartesianPoint cp1{2,-2}; PolarPoint pp1 = cp1; CartesianPoint cp2 = pp1; std::cout << "rho=" << pp1.rho << ", theta=" << pp1.theta << "\n"; std::cout << "x=" << cp2.x << ", y=" << cp2.y << "\n"; }
c661
#include <algorithm> #include <iostream> #include <vector> struct Point { int x, y; void rot(int n, bool rx, bool ry) { if (!ry) { if (rx) { x = (n - 1) - x; y = (n - 1) - y; } std::swap(x, y); } } }; Point fromD(int n, int d) { Point p = { 0, 0 }; bool rx, ry; int t = d; for (int s = 1; s < n; s <<= 1) { rx = ((t & 2) != 0); ry = (((t ^ (rx ? 1 : 0)) & 1) != 0); p.rot(s, rx, ry); p.x += (rx ? s : 0); p.y += (ry ? s : 0); t >>= 2; } return p; } std::vector<Point> getPointsForCurve(int n) { std::vector<Point> points; for (int d = 0; d < n * n; ++d) { points.push_back(fromD(n, d)); } return points; } std::vector<std::string> drawCurve(const std::vector<Point> &points, int n) { auto canvas = new char *[n]; for (size_t i = 0; i < n; i++) { canvas[i] = new char[n * 3 - 2]; std::memset(canvas[i], ' ', n * 3 - 2); } for (int i = 1; i < points.size(); i++) { auto lastPoint = points[i - 1]; auto curPoint = points[i]; int deltaX = curPoint.x - lastPoint.x; int deltaY = curPoint.y - lastPoint.y; if (deltaX == 0) { int row = std::max(curPoint.y, lastPoint.y); int col = curPoint.x * 3; canvas[row][col] = '|'; } else { int row = curPoint.y; int col = std::min(curPoint.x, lastPoint.x) * 3 + 1; canvas[row][col] = '_'; canvas[row][col + 1] = '_'; } } std::vector<std::string> lines; for (size_t i = 0; i < n; i++) { std::string temp; temp.assign(canvas[i], n * 3 - 2); lines.push_back(temp); } return lines; } int main() { for (int order = 1; order < 6; order++) { int n = 1 << order; auto points = getPointsForCurve(n); std::cout << "Hilbert curve, order=" << order << '\n'; auto lines = drawCurve(points, n); for (auto &line : lines) { std::cout << line << '\n'; } std::cout << '\n'; } return 0; }
c662
#include <iostream> #include <fstream> bool test(const std::string &line) { unsigned int e = 0; for (char c : line) { switch(std::tolower(c)) { case 'a': return false; case 'i': return false; case 'o': return false; case 'u': return false; case 'e': ++e; } } return e > 3; } int main() { std::ifstream dict{"unixdict.txt"}; if (! dict.is_open()) { std::cerr << "Cannot open unixdict.txt\n"; return 3; } for (std::string line; std::getline(dict, line);) { if (test(line)) std::cout << line << std::endl; } return 0; }
c663
#include <iostream> #include <cstdlib> #include <ctime> int main() { srand(time(0)); int n = 1 + (rand() % 10); int g; std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! "; while(true) { std::cin >> g; if (g == n) break; else std::cout << "That's not my number.\nTry another guess! "; } std::cout << "You've guessed my number!"; return 0; }
c664
template<typename Method, typename F, typename Float> double integrate(F f, Float a, Float b, int steps, Method m) { double s = 0; double h = (b-a)/steps; for (int i = 0; i < steps; ++i) s += m(f, a + h*i, h); return h*s; } class rectangular { public: enum position_type { left, middle, right }; rectangular(position_type pos): position(pos) {} template<typename F, typename Float> double operator()(F f, Float x, Float h) const { switch(position) { case left: return f(x); case middle: return f(x+h/2); case right: return f(x+h); } } private: const position_type position; }; class trapezium { public: template<typename F, typename Float> double operator()(F f, Float x, Float h) const { return (f(x) + f(x+h))/2; } }; class simpson { public: template<typename F, typename Float> double operator()(F f, Float x, Float h) const { return (f(x) + 4*f(x+h/2) + f(x+h))/6; } }; double f(double x) { return x*x; } double rl = integrate(f, 0.0, 1.0, 10, rectangular(rectangular::left)); double rm = integrate(f, 0.0, 1.0, 10, rectangular(rectangular::middle)); double rr = integrate(f, 0.0, 1.0, 10, rectangular(rectangular::right)); double t = integrate(f, 0.0, 1.0, 10, trapezium()); double s = integrate(f, 0.0, 1.0, 10, simpson());
c665
#include <algorithm> #include <iostream> #include <iterator> int main(void) { for (int g = 1; g < 10; g++) { int v[11], n=0; generate_n(std::ostream_iterator<int>(std::cout, " "), 10, [&]{n++; return v[n]=(g<n)? v[n-g]*n : n;}); std::cout << std::endl; } return 0; }
c666
#include <time.h> #include <stdlib.h> #include <vector> #include <string> #include <iostream> class p15 { public : void play() { bool p = true; std::string a; while( p ) { createBrd(); while( !isDone() ) { drawBrd();getMove(); } drawBrd(); std::cout << "\n\nCongratulations!\nPlay again (Y/N)?"; std::cin >> a; if( a != "Y" && a != "y" ) break; } } private: void createBrd() { int i = 1; std::vector<int> v; for( ; i < 16; i++ ) { brd[i - 1] = i; } brd[15] = 0; x = y = 3; for( i = 0; i < 1000; i++ ) { getCandidates( v ); move( v[rand() % v.size()] ); v.clear(); } } void move( int d ) { int t = x + y * 4; switch( d ) { case 1: y--; break; case 2: x++; break; case 4: y++; break; case 8: x--; } brd[t] = brd[x + y * 4]; brd[x + y * 4] = 0; } void getCandidates( std::vector<int>& v ) { if( x < 3 ) v.push_back( 2 ); if( x > 0 ) v.push_back( 8 ); if( y < 3 ) v.push_back( 4 ); if( y > 0 ) v.push_back( 1 ); } void drawBrd() { int r; std::cout << "\n\n"; for( int y = 0; y < 4; y++ ) { std::cout << "+----+----+----+----+\n"; for( int x = 0; x < 4; x++ ) { r = brd[x + y * 4]; std::cout << "| "; if( r < 10 ) std::cout << " "; if( !r ) std::cout << " "; else std::cout << r << " "; } std::cout << "|\n"; } std::cout << "+----+----+----+----+\n"; } void getMove() { std::vector<int> v; getCandidates( v ); std::vector<int> p; getTiles( p, v ); unsigned int i; while( true ) { std::cout << "\nPossible moves: "; for( i = 0; i < p.size(); i++ ) std::cout << p[i] << " "; int z; std::cin >> z; for( i = 0; i < p.size(); i++ ) if( z == p[i] ) { move( v[i] ); return; } } } void getTiles( std::vector<int>& p, std::vector<int>& v ) { for( unsigned int t = 0; t < v.size(); t++ ) { int xx = x, yy = y; switch( v[t] ) { case 1: yy--; break; case 2: xx++; break; case 4: yy++; break; case 8: xx--; } p.push_back( brd[xx + yy * 4] ); } } bool isDone() { for( int i = 0; i < 15; i++ ) { if( brd[i] != i + 1 ) return false; } return true; } int brd[16], x, y; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); p15 p; p.play(); return 0; }
c667
template<class T> class matrix { public: matrix( unsigned int nSize ) : m_oData(nSize * nSize, 0), m_nSize(nSize) {} inline T& operator()(unsigned int x, unsigned int y) { return m_oData[x+m_nSize*y]; } void identity() { int nCount = 0; int nStride = m_nSize + 1; std::generate( m_oData.begin(), m_oData.end(), [&]() { return !(nCount++%nStride); } ); } inline unsigned int size() { return m_nSize; } private: std::vector<T> m_oData; unsigned int m_nSize; }; int main() { int nSize; std::cout << "Enter matrix size (N): "; std::cin >> nSize; matrix<int> oMatrix( nSize ); oMatrix.identity(); for ( unsigned int y = 0; y < oMatrix.size(); y++ ) { for ( unsigned int x = 0; x < oMatrix.size(); x++ ) { std::cout << oMatrix(x,y) << " "; } std::cout << std::endl; } return 0; }
c668
#include <vector> #include <algorithm> #include <functional> #include <iterator> #include <iostream> int main() { std::vector<int> ary; for (int i = 0; i < 10; i++) ary.push_back(i); std::vector<int> evens; std::remove_copy_if(ary.begin(), ary.end(), back_inserter(evens), std::bind2nd(std::modulus<int>(), 2)); std::copy(evens.begin(), evens.end(), std::ostream_iterator<int>(std::cout, "\n")); return 0; }
c669
#include <exception> #include <string> #include <iostream> using namespace std; namespace Roman { int ToInt(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; } throw exception("Invalid character"); } int ToInt(const string& s) { int retval = 0, pvs = 0; for (auto pc = s.rbegin(); pc != s.rend(); ++pc) { const int inc = ToInt(*pc); retval += inc < pvs ? -inc : inc; pvs = inc; } return retval; } } int main(int argc, char* argv[]) { try { cout << "MCMXC = " << Roman::ToInt("MCMXC") << "\n"; cout << "MMVIII = " << Roman::ToInt("MMVIII") << "\n"; cout << "MDCLXVI = " << Roman::ToInt("MDCLXVI") << "\n"; } catch (exception& e) { cerr << e.what(); return -1; } return 0; }
c670
#include <iostream> #include <fstream> #include <string> #include <iterator> int main( ) { if (std::ifstream infile("sample.txt")) { std::string fileData(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>()); cout << "File has " << fileData.size() << "chars\n"; return 0; } else { std::cout << "file not found!\n"; return 1; } }
c671
#include <winsock2.h> #include <ws2tcpip.h> #include <iostream> int main() { WSADATA wsaData; WSAStartup( MAKEWORD( 2, 2 ), &wsaData ); addrinfo *result = NULL; addrinfo hints; ZeroMemory( &hints, sizeof( hints ) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; getaddrinfo( "74.125.45.100", "80", &hints, &result ); SOCKET s = socket( result->ai_family, result->ai_socktype, result->ai_protocol ); connect( s, result->ai_addr, (int)result->ai_addrlen ); freeaddrinfo( result ); send( s, "GET / HTTP/1.0\n\n", 16, 0 ); char buffer[512]; int bytes; do { bytes = recv( s, buffer, 512, 0 ); if ( bytes > 0 ) std::cout.write(buffer, bytes); } while ( bytes > 0 ); return 0; }
c672
#include <iomanip> #include <iostream> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> using big_int = boost::multiprecision::cpp_int; template <typename integer> integer isqrt(integer x) { integer q = 1; while (q <= x) q <<= 2; integer r = 0; while (q > 1) { q >>= 2; integer t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; } std::string commatize(const big_int& n) { std::ostringstream out; out << n; std::string str(out.str()); std::string result; size_t digits = str.size(); result.reserve(4 * digits/3); for (size_t i = 0; i < digits; ++i) { if (i > 0 && i % 3 == digits % 3) result += ','; result += str[i]; } return result; } int main() { std::cout << "Integer square root for numbers 0 to 65:\n"; for (int n = 0; n <= 65; ++n) std::cout << isqrt(n) << ' '; std::cout << "\n\n"; std::cout << "Integer square roots of odd powers of 7 from 1 to 73:\n"; const int power_width = 83, isqrt_width = 42; std::cout << " n |" << std::setw(power_width) << "7 ^ n" << " |" << std::setw(isqrt_width) << "isqrt(7 ^ n)" << '\n'; std::cout << std::string(6 + power_width + isqrt_width, '-') << '\n'; big_int p = 7; for (int n = 1; n <= 73; n += 2, p *= 49) { std::cout << std::setw(2) << n << " |" << std::setw(power_width) << commatize(p) << " |" << std::setw(isqrt_width) << commatize(isqrt(p)) << '\n'; } return 0; }
c673
#include <iostream> #include <set> #include <cmath> int main() { std::set<int> values; for (int a=2; a<=5; a++) for (int b=2; b<=5; b++) values.insert(std::pow(a, b)); for (int i : values) std::cout << i << " "; std::cout << std::endl; return 0; }
c674
#include <string> #include <boost/array.hpp> #include <boost/assign/list_of.hpp> #include <boost/format.hpp> #include <boost/foreach.hpp> #include <iostream> #include <math.h> using std::string; using namespace boost::assign; int get_Index(float angle) { return static_cast<int>(floor(angle / 11.25 +0.5 )) % 32 + 1; } string get_Abbr_From_Index(int i) { static boost::array<std::string, 32> points(list_of ("N")("NbE")("NNE")("NEbN")("NE")("NEbE")("ENE")("EbN") ("E")("EbS")("ESE")("SEbE")("SE")("SEbS")("SSE")("SbE") ("S")("SbW")("SSW")("SWbS")("SW")("SWbW")("WSW")("WbS") ("W")("WbN")("WNW")("NWbW")("NW")("NWbN")("NNW")("NbW")); return points[i-1]; } string Build_Name_From_Abbreviation(string a) { string retval; for (int i = 0; i < a.size(); ++i){ if ((1 == i) && (a[i] != 'b') && (a.size() == 3)) retval += "-"; switch (a[i]){ case 'N' : retval += "north"; break; case 'S' : retval += "south"; break; case 'E' : retval += "east"; break; case 'W' : retval += "west"; break; case 'b' : retval += " by "; break; } } retval[0] = toupper(retval[0]); return retval; } int main() { boost::array<float,33> headings(list_of (0.0)(16.87)(16.88)(33.75)(50.62)(50.63)(67.5)(84.37)(84.38)(101.25) (118.12)(118.13)(135.0)(151.87)(151.88)(168.75)(185.62)(185.63)(202.5) (219.37)(219.38)(236.25)(253.12)(253.13)(270.0)(286.87)(286.88)(303.75) (320.62)(320.63)(337.5)(354.37)(354.38)); int i; boost::format f("%1$4d %2$-20s %3$_7.2f"); BOOST_FOREACH(float a, headings) { i = get_Index(a); std::cout << f % i % Build_Name_From_Abbreviation(get_Abbr_From_Index(i)) % a << std::endl; } return 0; }
c675
#include <iostream> class ContinuedFraction { public: virtual const int nextTerm(){}; virtual const bool moreTerms(){}; }; class r2cf : public ContinuedFraction { private: int n1, n2; public: r2cf(const int numerator, const int denominator): n1(numerator), n2(denominator){} const int nextTerm() { const int thisTerm = n1/n2; const int t2 = n2; n2 = n1 - thisTerm * n2; n1 = t2; return thisTerm; } const bool moreTerms() {return fabs(n2) > 0;} }; class SQRT2 : public ContinuedFraction { private: bool first=true; public: const int nextTerm() {if (first) {first = false; return 1;} else return 2;} const bool moreTerms() {return true;} };
c676
#include <boost/scoped_ptr.hpp> #include <iostream> #include <queue> template<typename T> class TreeNode { public: TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) : mValue(n), mLeft(left), mRight(right) {} T getValue() const { return mValue; } TreeNode* left() const { return mLeft.get(); } TreeNode* right() const { return mRight.get(); } void preorderTraverse() const { std::cout << " " << getValue(); if(mLeft) { mLeft->preorderTraverse(); } if(mRight) { mRight->preorderTraverse(); } } void inorderTraverse() const { if(mLeft) { mLeft->inorderTraverse(); } std::cout << " " << getValue(); if(mRight) { mRight->inorderTraverse(); } } void postorderTraverse() const { if(mLeft) { mLeft->postorderTraverse(); } if(mRight) { mRight->postorderTraverse(); } std::cout << " " << getValue(); } void levelorderTraverse() const { std::queue<const TreeNode*> q; q.push(this); while(!q.empty()) { const TreeNode* n = q.front(); q.pop(); std::cout << " " << n->getValue(); if(n->left()) { q.push(n->left()); } if(n->right()) { q.push(n->right()); } } } protected: T mValue; boost::scoped_ptr<TreeNode> mLeft; boost::scoped_ptr<TreeNode> mRight; private: TreeNode(); }; int main() { TreeNode<int> root(1, new TreeNode<int>(2, new TreeNode<int>(4, new TreeNode<int>(7)), new TreeNode<int>(5)), new TreeNode<int>(3, new TreeNode<int>(6, new TreeNode<int>(8), new TreeNode<int>(9)))); std::cout << "preorder: "; root.preorderTraverse(); std::cout << std::endl; std::cout << "inorder: "; root.inorderTraverse(); std::cout << std::endl; std::cout << "postorder: "; root.postorderTraverse(); std::cout << std::endl; std::cout << "level-order:"; root.levelorderTraverse(); std::cout << std::endl; return 0; }
c677
#include <iostream> #include <numeric> int main() { std::cout << "The greatest common divisor of 12 and 18 is " << std::gcd(12, 18) << " !\n"; }
c678
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (directory_iterator iter(current_dir), end; iter != end; ++iter) { boost::smatch match; std::string fn = iter->path().filename().string(); if (boost::regex_match( fn, match, pattern)) { std::cout << match[0] << "\n"; } } }
c679
#include <iostream> class N { private: int dVal = 0, dLen; public: N(char const* x = "0"){ int i = 0, q = 1; for (; x[i] > 0; i++); for (dLen = --i/2; i >= 0; i--) { dVal+=(x[i]-48)*q; q*=2; }} const N& operator++() { for (int i = 0;;i++) { if (dLen < i) dLen = i; switch ((dVal >> (i*2)) & 3) { case 0: dVal += (1 << (i*2)); return *this; case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this; case 2: dVal &= ~(3 << (i*2)); }}} const bool operator<=(const N& other) const {return dVal <= other.dVal;} friend std::ostream& operator<<(std::ostream&, const N&); }; N operator "" N(char const* x) {return N(x);} std::ostream &operator<<(std::ostream &os, const N &G) { const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"}; if (G.dVal == 0) return os << "0"; os << dig1[(G.dVal >> (G.dLen*2)) & 3]; for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3]; return os; }
c680
void step_up() { while (!step()) step_up(); }
c681
#include <algorithm> #include <iostream> 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); }
c682
#include <windows.h> #include <string> using namespace std; const int BMP_SIZE = 512; 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 mSquares { public: mSquares() { bmp.create( BMP_SIZE, BMP_SIZE ); createPallete(); } void draw() { HDC dc = bmp.getDC(); for( int y = 0; y < BMP_SIZE; y++ ) for( int x = 0; x < BMP_SIZE; x++ ) { int c = ( x ^ y ) % 256; SetPixel( dc, x, y, clrs[c] ); } BitBlt( GetDC( GetConsoleWindow() ), 30, 30, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); } private: void createPallete() { for( int x = 0; x < 256; x++ ) clrs[x] = RGB( x<<1, x, x<<2 ); } unsigned int clrs[256]; myBitmap bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() ); mSquares s; s.draw(); return system( "pause" ); }
c683
#include <cstdint> #include <iostream> #include <vector> std::vector<bool> prime_sieve(uint64_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (uint64_t i = 4; i < limit; i += 2) sieve[i] = false; for (uint64_t p = 3; ; p += 2) { uint64_t q = p * p; if (q >= limit) break; if (sieve[p]) { uint64_t inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; } std::vector<uint64_t> wieferich_primes(uint64_t limit) { std::vector<uint64_t> result; std::vector<bool> sieve(prime_sieve(limit)); for (uint64_t p = 2; p < limit; ++p) if (sieve[p] && modpow(2, p - 1, p * p) == 1) result.push_back(p); return result; } int main() { const uint64_t limit = 5000; std::cout << "Wieferich primes less than " << limit << ":\n"; for (uint64_t p : wieferich_primes(limit)) std::cout << p << '\n'; }
c684
#include <iostream> #include <stdlib.h> class trit { public: static const trit False, Maybe, True; trit operator !() const { return static_cast<Value>(-value); } trit operator &&(const trit &b) const { return (value < b.value) ? value : b.value; } trit operator ||(const trit &b) const { return (value > b.value) ? value : b.value; } trit operator >>(const trit &b) const { return -value > b.value ? static_cast<Value>(-value) : b.value; } trit operator ==(const trit &b) const { return static_cast<Value>(value * b.value); } char chr() const { return "F?T"[value + 1]; } protected: typedef enum { FALSE=-1, MAYBE, TRUE } Value; Value value; trit(const Value value) : value(value) { } }; std::ostream& operator<<(std::ostream &os, const trit &t) { os << t.chr(); return os; } const trit trit::False = trit(trit::FALSE); const trit trit::Maybe = trit(trit::MAYBE); const trit trit::True = trit(trit::TRUE); int main(int, char**) { const trit trits[3] = { trit::True, trit::Maybe, trit::False }; #define for_each(name) \ for (size_t name=0; name<3; ++name) #define show_op(op) \ std::cout << std::endl << #op << " "; \ for_each(a) std::cout << ' ' << trits[a]; \ std::cout << std::endl << " -------"; \ for_each(a) { \ std::cout << std::endl << trits[a] << " |"; \ for_each(b) std::cout << ' ' << (trits[a] op trits[b]); \ } \ std::cout << std::endl; std::cout << "! ----" << std::endl; for_each(a) std::cout << trits[a] << " | " << !trits[a] << std::endl; show_op(&&); show_op(||); show_op(>>); show_op(==); return EXIT_SUCCESS; }
c685
#include <string> #include <algorithm> #include <iostream> #include <set> #include <vector> auto collectSubStrings( const std::string& s, int maxSubLength ) { int l = s.length(); auto res = std::set<std::string>(); for ( int start = 0; start < l; start++ ) { int m = std::min( maxSubLength, l - start + 1 ); for ( int length = 1; length < m; length++ ) { res.insert( s.substr( start, length ) ); } } return res; } std::string lcs( const std::string& s0, const std::string& s1 ) { auto maxSubLength = std::min( s0.length(), s1.length() ); auto set0 = collectSubStrings( s0, maxSubLength ); auto set1 = collectSubStrings( s1, maxSubLength ); auto common = std::vector<std::string>(); std::set_intersection( set0.begin(), set0.end(), set1.begin(), set1.end(), std::back_inserter( common ) ); std::nth_element( common.begin(), common.begin(), common.end(), []( const std::string& s1, const std::string& s2 ) { return s1.length() > s2.length(); } ); return *common.begin(); } int main( int argc, char* argv[] ) { auto s1 = std::string( "thisisatest" ); auto s2 = std::string( "testing123testing" ); std::cout << "The longest common substring of " << s1 << " and " << s2 << " is:\n"; std::cout << "\"" << lcs( s1, s2 ) << "\" !\n"; return 0; }
c686
#include <QImage> #include <cstdlib> #include <QColor> #include <iostream> int main( int argc , char *argv[ ] ) { if ( argc != 3 ) { std::cout << "Call this with imagecompare <file of image 1>" << " <file of image 2>\n" ; return 1 ; } QImage firstImage ( argv[ 1 ] ) ; QImage secondImage ( argv[ 2 ] ) ; double totaldiff = 0.0 ; int h = firstImage.height( ) ; int w = firstImage.width( ) ; int hsecond = secondImage.height( ) ; int wsecond = secondImage.width( ) ; if ( w != wsecond || h != hsecond ) { std::cerr << "Error, pictures must have identical dimensions!\n" ; return 2 ; } for ( int y = 0 ; y < h ; y++ ) { uint *firstLine = ( uint* )firstImage.scanLine( y ) ; uint *secondLine = ( uint* )secondImage.scanLine( y ) ; for ( int x = 0 ; x < w ; x++ ) { uint pixelFirst = firstLine[ x ] ; int rFirst = qRed( pixelFirst ) ; int gFirst = qGreen( pixelFirst ) ; int bFirst = qBlue( pixelFirst ) ; uint pixelSecond = secondLine[ x ] ; int rSecond = qRed( pixelSecond ) ; int gSecond = qGreen( pixelSecond ) ; int bSecond = qBlue( pixelSecond ) ; totaldiff += std::abs( rFirst - rSecond ) / 255.0 ; totaldiff += std::abs( gFirst - gSecond ) / 255.0 ; totaldiff += std::abs( bFirst -bSecond ) / 255.0 ; } } std::cout << "The difference of the two pictures is " << (totaldiff * 100) / (w * h * 3) << " % !\n" ; return 0 ; }
c687
#include <iostream> using namespace std; int toInt(const char c) { return c-'0'; } int confirm( const char *id) { bool is_odd_dgt = true; int s = 0; const char *cp; for(cp=id; *cp; cp++); while(cp > id) { --cp; int k = toInt(*cp); if (is_odd_dgt) { s += k; } else { s += (k!=9)? (2*k)%9 : 9; } is_odd_dgt = !is_odd_dgt; } return 0 == s%10; } int main( ) { const char * t_cases[] = { "49927398716", "49927398717", "1234567812345678", "1234567812345670", NULL, }; for ( const char **cp = t_cases; *cp; cp++) { cout << *cp << ": " << confirm(*cp) << endl; } return 0; }
c688
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
c689
#include <iostream> template<class T> void quibble(std::ostream& o, T i, T e) { o << "{"; if (e != i) { T n = i++; const char* more = ""; while (e != i) { o << more << *n; more = ", "; n = i++; } o << (*more?" and ":"") << *n; } o << "}"; } int main(int argc, char** argv) { char const* a[] = {"ABC","DEF","G","H"}; for (int i=0; i<5; i++) { quibble(std::cout, a, a+i); std::cout << std::endl; } return 0; }
c690
#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); 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]; } for (size_t k = 0; k < n; ++k) { size_t max_index = k; scalar_type max_value = 0; for (size_t i = k; i < n; ++i) { 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; 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; } } 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; }
c691
#include <iostream> bool check_isbn13(std::string isbn) { int count = 0; int sum = 0; for (auto ch : isbn) { 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; }
c692
#include <iostream> #include <iterator> #include <vector> int main( int argc, char* argv[] ) { std::vector<bool> t; t.push_back( 0 ); size_t len = 1; std::cout << t[0] << "\n"; do { for( size_t x = 0; x < len; x++ ) t.push_back( t[x] ? 0 : 1 ); std::copy( t.begin(), t.end(), std::ostream_iterator<bool>( std::cout ) ); std::cout << "\n"; len = t.size(); } while( len < 60 ); return 0; }
c693
#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; }
c694
#include <map> #include <set> template<typename Goal> class topological_sorter { protected: struct relations { std::size_t dependencies; std::set<Goal> dependents; }; std::map<Goal, relations> map; public: void add_goal(Goal const &goal) { map[goal]; } void add_dependency(Goal const &goal, Goal const &dependency) { if (dependency == goal) return; auto &dependents = map[dependency].dependents; if (dependents.find(goal) == dependents.end()) { dependents.insert(goal); ++map[goal].dependencies; } } template<typename Container> void add_dependencies(Goal const &goal, Container const &dependencies) { for (auto const &dependency : dependencies) add_dependency(goal, dependency); } template<typename ResultContainer, typename CyclicContainer> void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) { sorted.clear(); unsortable.clear(); for (auto const &lookup : map) { auto const &goal = lookup.first; auto const &relations = lookup.second; if (relations.dependencies == 0) sorted.push_back(goal); } for (std::size_t index = 0; index < sorted.size(); ++index) for (auto const &goal : map[sorted[index]].dependents) if (--map[goal].dependencies == 0) sorted.push_back(goal); for (auto const &lookup : map) { auto const &goal = lookup.first; auto const &relations = lookup.second; if (relations.dependencies != 0) unsortable.push_back(goal); } } template<typename ResultContainer, typename CyclicContainer> void sort(ResultContainer &sorted, CyclicContainer &unsortable) { topological_sorter<Goal> temporary = *this; temporary.destructive_sort(sorted, unsortable); } void clear() { map.clear(); } }; #include <fstream> #include <sstream> #include <iostream> #include <string> #include <vector> using namespace std; void display_heading(string const &message) { cout << endl << "~ " << message << " ~" << endl; } void display_results(string const &input) { topological_sorter<string> sorter; vector<string> sorted, unsortable; stringstream lines(input); string line; while (getline(lines, line)) { stringstream buffer(line); string goal, dependency; buffer >> goal; sorter.add_goal(goal); while (buffer >> dependency) sorter.add_dependency(goal, dependency); } sorter.destructive_sort(sorted, unsortable); if (sorted.size() == 0) display_heading("Error: no independent variables found!"); else { display_heading("Result"); for (auto const &goal : sorted) cout << goal << endl; } if (unsortable.size() != 0) { display_heading("Error: cyclic dependencies detected!"); for (auto const &goal : unsortable) cout << goal << endl; } } int main(int argc, char **argv) { if (argc == 1) { string example = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n" "dw01 ieee dw01 dware gtech\n" "dw02 ieee dw02 dware\n" "dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n" "dw04 dw04 ieee dw01 dware gtech\n" "dw05 dw05 ieee dware\n" "dw06 dw06 ieee dware\n" "dw07 ieee dware\n" "dware ieee dware\n" "gtech ieee gtech\n" "ramlib std ieee\n" "std_cell_lib ieee std_cell_lib\n" "synopsys\n" "cycle_11 cycle_12\n" "cycle_12 cycle_11\n" "cycle_21 dw01 cycle_22 dw02 dw03\n" "cycle_22 cycle_21 dw01 dw04"; display_heading("Example: each line starts with a goal followed by it's dependencies"); cout << example << endl; display_results(example); display_heading("Enter lines of data (press enter when finished)"); string line, data; while (getline(cin, line) && !line.empty()) data += line + '\n'; if (!data.empty()) display_results(data); } else while (*(++argv)) { ifstream file(*argv); typedef istreambuf_iterator<char> iterator; display_results(string(iterator(file), iterator())); } }
c695
#include <numeric> #include <cctype> #include <iostream> #include <string> template<typename result_sink_t> auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { if(sedol.size() != 6) return result_sink(0, "length of sedol string != 6"); const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; if(sedol.find_first_not_of(valid_chars) != std::string::npos) return result_sink(0, "sedol string contains disallowed characters"); const int weights[] = {1,3,1,7,3,9}; auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 , [](int acc, int prod){ return acc + prod; } , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } ); return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { using namespace std; string inputs[] = { "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; for(auto const & sedol : inputs) { sedol_checksum(sedol, [&](auto sum, char const * errorMessage) { if(errorMessage) cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; else cout << sedol << sum << "\n"; }); } return 0; }
c696
#include <iostream> void leoN( int cnt, int l0 = 1, int l1 = 1, int add = 1 ) { int t; for( int i = 0; i < cnt; i++ ) { std::cout << l0 << " "; t = l0 + l1 + add; l0 = l1; l1 = t; } } int main( int argc, char* argv[] ) { std::cout << "Leonardo Numbers: "; leoN( 25 ); std::cout << "\n\nFibonacci Numbers: "; leoN( 25, 0, 1, 0 ); return 0; }
c697
#include <iostream> #include <string_view> #include <boost/hana.hpp> #include <boost/hana/experimental/printable.hpp> using namespace std; namespace hana = boost::hana; constexpr auto Amb(auto constraint, auto&& ...params) { auto possibleSolutions = hana::cartesian_product(hana::tuple(params...)); auto foldOperation = [constraint](auto a, auto b) { bool meetsConstraint = constraint(a); return meetsConstraint ? a : b; }; return hana::fold_right(possibleSolutions, foldOperation); } void AlgebraExample() { constexpr hana::tuple x{1, 2, 3}; constexpr hana::tuple y{7, 6, 4, 5}; constexpr auto constraint = [](auto t) { return t[hana::size_c<0>] * t[hana::size_c<1>] == 8; }; auto result = Amb(constraint, x, y); cout << "\nx = " << hana::experimental::print(x); cout << "\ny = " << hana::experimental::print(y); cout << "\nx * y == 8: " << hana::experimental::print(result); } void StringExample() { constexpr hana::tuple words1 {"the"sv, "that"sv, "a"sv}; constexpr hana::tuple words2 {"frog"sv, "elephant"sv, "thing"sv}; constexpr hana::tuple words3 {"walked"sv, "treaded"sv, "grows"sv}; constexpr hana::tuple words4 {"slowly"sv, "quickly"sv}; constexpr auto constraint = [](const auto t) { auto adjacent = hana::zip(hana::drop_back(t), hana::drop_front(t)); return hana::all_of(adjacent, [](auto t) { return t[hana::size_c<0>].back() == t[hana::size_c<1>].front(); }); }; auto wordResult = Amb(constraint, words1, words2, words3, words4); cout << "\n\nWords 1: " << hana::experimental::print(words1); cout << "\nWords 2: " << hana::experimental::print(words2); cout << "\nWords 3: " << hana::experimental::print(words3); cout << "\nWords 4: " << hana::experimental::print(words4); cout << "\nSolution: " << hana::experimental::print(wordResult) << "\n"; } int main() { AlgebraExample(); StringExample(); }
c698
#include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; pair<int, int> twoSum(vector<int> numbers, int sum) { auto m = map<int, int>(); for (size_t i = 0; i < numbers.size(); ++i) { auto key = sum - numbers[i]; if (m.find(key) != m.end()) { return make_pair(m[key], i); } m[numbers[i]] = i; } return make_pair(-1, -1); } int main() { auto numbers = vector<int>{ 0, 2, 11, 19, 90 }; const int sum = 21; auto ts = twoSum(numbers, sum); if (ts.first != -1) { cout << "{" << ts.first << ", " << ts.second << "}" << endl; } else { cout << "no result" << endl; } return 0; }
c699
#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>); }
c700
#include <iostream> #include <boost/tokenizer.hpp> #include <string> int main( ) { std::string str( "a!===b=!=c" ) , output ; typedef boost::tokenizer<boost::char_separator<char> > tokenizer ; boost::char_separator<char> separator ( "==" , "!=" ) , sep ( "!" ) ; tokenizer mytok( str , separator ) ; tokenizer::iterator tok_iter = mytok.begin( ) ; for ( ; tok_iter != mytok.end( ) ; ++tok_iter ) output.append( *tok_iter ) ; tokenizer nexttok ( output , sep ) ; for ( tok_iter = nexttok.begin( ) ; tok_iter != nexttok.end( ) ; ++tok_iter ) std::cout << *tok_iter << " " ; std::cout << '\n' ; return 0 ; }
c701
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class spiral { public: spiral() { bmp.create( BMP_SIZE, BMP_SIZE ); } void draw( int c, int s ) { double a = .2, b = .3, r, x, y; int w = BMP_SIZE >> 1; HDC dc = bmp.getDC(); for( double d = 0; d < c * 6.28318530718; d += .002 ) { r = a + b * d; x = r * cos( d ); y = r * sin( d ); SetPixel( dc, ( int )( s * x + w ), ( int )( s * y + w ), 255 ); } bmp.saveBitmap( "./spiral.bmp" ); } private: myBitmap bmp; }; int main(int argc, char* argv[]) { spiral s; s.draw( 16, 8 ); return 0; }
c702
#include <windows.h> #include <string> using namespace std; enum states { NONE, TREE, FIRE }; const int MAX_SIDE = 500; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; 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() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } 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: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class forest { public: forest() { _bmp.create( MAX_SIDE, MAX_SIDE ); initForest( 0.05f, 0.005f ); } void initForest( float p, float f ) { _p = p; _f = f; seedForest(); } void mainLoop() { display(); simulate(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float probRand() { return ( float )rand() / 32768.0f; } void display() { HDC bdc = _bmp.getDC(); DWORD clr; for( int y = 0; y < MAX_SIDE; y++ ) { for( int x = 0; x < MAX_SIDE; x++ ) { switch( _forest[x][y] ) { case FIRE: clr = 255; break; case TREE: clr = RGB( 0, 255, 0 ); break; default: clr = 0; } SetPixel( bdc, x, y, clr ); } } HDC dc = GetDC( _hwnd ); BitBlt( dc, 0, 0, MAX_SIDE, MAX_SIDE, _bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( _hwnd, dc ); } void seedForest() { ZeroMemory( _forestT, sizeof( _forestT ) ); ZeroMemory( _forest, sizeof( _forest ) ); for( int y = 0; y < MAX_SIDE; y++ ) for( int x = 0; x < MAX_SIDE; x++ ) if( probRand() < _p ) _forest[x][y] = TREE; } bool getNeighbors( int x, int y ) { int a, b; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( !xx && !yy ) continue; a = x + xx; b = y + yy; if( a < MAX_SIDE && b < MAX_SIDE && a > -1 && b > -1 ) if( _forest[a][b] == FIRE ) return true; } return false; } void simulate() { for( int y = 0; y < MAX_SIDE; y++ ) { for( int x = 0; x < MAX_SIDE; x++ ) { switch( _forest[x][y] ) { case FIRE: _forestT[x][y] = NONE; break; case NONE: if( probRand() < _p ) _forestT[x][y] = TREE; break; case TREE: if( getNeighbors( x, y ) || probRand() < _f ) _forestT[x][y] = FIRE; } } } for( int y = 0; y < MAX_SIDE; y++ ) for( int x = 0; x < MAX_SIDE; x++ ) _forest[x][y] = _forestT[x][y]; } myBitmap _bmp; HWND _hwnd; BYTE _forest[MAX_SIDE][MAX_SIDE], _forestT[MAX_SIDE][MAX_SIDE]; float _p, _f; }; class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _ff.setHWND( _hwnd ); _ff.initForest( 0.02f, 0.001f ); 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 ); } else { _ff.mainLoop(); } } return UnregisterClass( "_FOREST_FIRE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); 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 = "_FOREST_FIRE_"; RegisterClassEx( &wcex ); return CreateWindow( "_FOREST_FIRE_", ".: Forest Fire -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, MAX_SIDE, MAX_SIDE, NULL, NULL, _hInst, NULL ); } HINSTANCE _hInst; HWND _hwnd; forest _ff; }; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
c703
#include <iostream> #include <sstream> #include <string> const char *text = { "In olden times when wishing still helped one, there lived a king " "whose daughters were all beautiful, but the youngest was so beautiful " "that the sun itself, which has seen so much, was astonished whenever " "it shone in her face. Close by the king's castle lay a great dark " "forest, and under an old lime tree in the forest was a well, and when " "the day was very warm, the king's child went out into the forest and " "sat down by the side of the cool fountain, and when she was bored she " "took a golden ball, and threw it up on high and caught it, and this " "ball was her favorite plaything." }; std::string wrap(const char *text, size_t line_length = 72) { std::istringstream words(text); std::ostringstream wrapped; std::string word; if (words >> word) { wrapped << word; size_t space_left = line_length - word.length(); while (words >> word) { if (space_left < word.length() + 1) { wrapped << '\n' << word; space_left = line_length - word.length(); } else { wrapped << ' ' << word; space_left -= word.length() + 1; } } } return wrapped.str(); } int main() { std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n"; std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n"; }
c704
#include <string> #include <vector> #include <algorithm> #include <boost/tokenizer.hpp> #include <iostream> std::vector<std::string> splitOnChar ( std::string & s , const char c ) { typedef boost::tokenizer<boost::char_separator<char>> tokenizer ; std::vector<std::string> parts ; boost::char_separator<char> sep( &c ) ; tokenizer tokens( s , sep ) ; for ( auto it = tokens.begin( ) ; it != tokens.end( ) ; it++ ) parts.push_back( *it ) ; return parts ; } bool myCompare ( const std::string & s1 , const std::string & s2 ) { std::string firstcopy( s1 ) ; std::string secondcopy ( s2 ) ; std::vector<std::string> firstparts( splitOnChar ( firstcopy, '.' ) ) ; std::vector<std::string> secondparts( splitOnChar ( secondcopy, '.' ) ) ; std::vector<int> numbers1( firstparts.size( ) ) ; std::vector<int> numbers2( secondparts.size( ) ) ; std::transform( firstparts.begin( ) , firstparts.end( ) , numbers1.begin( ) , []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ; std::transform( secondparts.begin( ) , secondparts.end( ) , numbers2.begin( ) , []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ; auto it1 = numbers1.begin( ) ; auto it2 = numbers2.begin( ) ; while ( *it1 == *it2 ) { it1++ ; it2++ ; } if ( it1 == numbers1.end( ) || it2 == numbers2.end( ) ) return std::lexicographical_compare( s1.begin( ) , s1.end( ) , s2.begin( ) , s2.end( ) ) ; return *it1 < *it2 ; } int main( ) { std::vector<std::string> arrayOID { "1.3.6.1.4.1.11.2.17.19.3.4.0.10" , "1.3.6.1.4.1.11.2.17.5.2.0.79" , "1.3.6.1.4.1.11.2.17.19.3.4.0.4" , "1.3.6.1.4.1.11150.3.4.0.1" , "1.3.6.1.4.1.11.2.17.19.3.4.0.1" , "1.3.6.1.4.1.11150.3.4.0" } ; std::sort( arrayOID.begin( ) , arrayOID.end( ) , myCompare ) ; for ( std::string s : arrayOID ) std::cout << s << '\n' ; return 0 ; }
c705
#include <string> #include <cstdlib> #include <iostream> #include <cassert> #include <algorithm> #include <vector> #include <ctime> std::string allowed_chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; class selection { public: 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; } static int target_length() { return target.length(); } private: static std::string target; }; std::string selection::target = "METHINKS IT IS LIKE A WEASEL"; 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()]; } 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; } 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"; }
c706
#include <atomic> #include <chrono> #include <cmath> #include <iostream> #include <mutex> #include <thread> using namespace std::chrono_literals; class Integrator { public: using clock_type = std::chrono::high_resolution_clock; using dur_t = std::chrono::duration<double>; using func_t = double(*)(double); explicit Integrator(func_t f = nullptr); ~Integrator(); void input(func_t new_input); double output() { return integrate(); } private: std::atomic_flag continue_; std::mutex mutex; std::thread worker; func_t func; double state = 0; clock_type::time_point const beginning = clock_type::now(); clock_type::time_point t_prev = beginning; void do_work(); double integrate(); }; Integrator::Integrator(func_t f) : func(f) { continue_.test_and_set(); worker = std::thread(&Integrator::do_work, this); } Integrator::~Integrator() { continue_.clear(); worker.join(); } void Integrator::input(func_t new_input) { integrate(); std::lock_guard<std::mutex> lock(mutex); func = new_input; } void Integrator::do_work() { while (continue_.test_and_set()) { integrate(); std::this_thread::sleep_for(1ms); } } double Integrator::integrate() { std::lock_guard<std::mutex> lock(mutex); auto now = clock_type::now(); dur_t start = t_prev - beginning; dur_t fin = now - beginning; if (func) state += (func(start.count()) + func(fin.count())) * (fin - start).count() / 2; t_prev = now; return state; } double sine(double time) { constexpr double PI = 3.1415926535897932; return std::sin(2 * PI * 0.5 * time); } int main() { Integrator foo(sine); std::this_thread::sleep_for(2s); foo.input(nullptr); std::this_thread::sleep_for(500ms); std::cout << foo.output(); }
c707
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { x++; } std::cout << n << ": " << x << std::endl; } return 0; }
c708
#include <iostream> #include <iomanip> #include <cmath> namespace Rosetta { template <int N> class GaussLegendreQuadrature { public: enum {eDEGREE = N}; template <typename Function> double integrate(double a, double b, Function f) { double p = (b - a) / 2; double q = (b + a) / 2; const LegendrePolynomial& legpoly = s_LegendrePolynomial; double sum = 0; for (int i = 1; i <= eDEGREE; ++i) { sum += legpoly.weight(i) * f(p * legpoly.root(i) + q); } return p * sum; } void print_roots_and_weights(std::ostream& out) const { const LegendrePolynomial& legpoly = s_LegendrePolynomial; out << "Roots: "; for (int i = 0; i <= eDEGREE; ++i) { out << ' ' << legpoly.root(i); } out << std::endl; out << "Weights:"; for (int i = 0; i <= eDEGREE; ++i) { out << ' ' << legpoly.weight(i); } out << std::endl; } private: class LegendrePolynomial { public: LegendrePolynomial () { for (int i = 0; i <= eDEGREE; ++i) { double dr = 1; Evaluation eval(cos(M_PI * (i - 0.25) / (eDEGREE + 0.5))); do { dr = eval.v() / eval.d(); eval.evaluate(eval.x() - dr); } while (fabs (dr) > 2e-16); this->_r[i] = eval.x(); this->_w[i] = 2 / ((1 - eval.x() * eval.x()) * eval.d() * eval.d()); } } double root(int i) const { return this->_r[i]; } double weight(int i) const { return this->_w[i]; } private: double _r[eDEGREE + 1]; double _w[eDEGREE + 1]; class Evaluation { public: explicit Evaluation (double x) : _x(x), _v(1), _d(0) { this->evaluate(x); } void evaluate(double x) { this->_x = x; double vsub1 = x; double vsub2 = 1; double f = 1 / (x * x - 1); for (int i = 2; i <= eDEGREE; ++i) { this->_v = ((2 * i - 1) * x * vsub1 - (i - 1) * vsub2) / i; this->_d = i * f * (x * this->_v - vsub1); vsub2 = vsub1; vsub1 = this->_v; } } double v() const { return this->_v; } double d() const { return this->_d; } double x() const { return this->_x; } private: double _x; double _v; double _d; }; }; static LegendrePolynomial s_LegendrePolynomial; }; template <int N> typename GaussLegendreQuadrature<N>::LegendrePolynomial GaussLegendreQuadrature<N>::s_LegendrePolynomial; } double RosettaExp(double x) { return exp(x); } int main() { Rosetta::GaussLegendreQuadrature<5> gl5; std::cout << std::setprecision(10); gl5.print_roots_and_weights(std::cout); std::cout << "Integrating Exp(X) over [-3, 3]: " << gl5.integrate(-3., 3., RosettaExp) << std::endl; std::cout << "Actual value: " << RosettaExp(3) - RosettaExp(-3) << std::endl; }
c709
#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, scalar_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} 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_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[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 print(std::ostream& out, const matrix<scalar_type>& a) { size_t rows = a.rows(), columns = a.columns(); out << std::fixed << std::setprecision(5); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < columns; ++column) { if (column > 0) out << ' '; out << std::setw(9) << a(row, column); } out << '\n'; } } template <typename scalar_type> matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) { assert(input.rows() == input.columns()); size_t n = input.rows(); matrix<scalar_type> result(n, n); for (size_t i = 0; i < n; ++i) { for (size_t k = 0; k < i; ++k) { scalar_type value = input(i, k); for (size_t j = 0; j < k; ++j) value -= result(i, j) * result(k, j); result(i, k) = value/result(k, k); } scalar_type value = input(i, i); for (size_t j = 0; j < i; ++j) value -= result(i, j) * result(i, j); result(i, i) = std::sqrt(value); } return result; } void print_cholesky_factor(const matrix<double>& matrix) { std::cout << "Matrix:\n"; print(std::cout, matrix); std::cout << "Cholesky factor:\n"; print(std::cout, cholesky_factor(matrix)); } int main() { matrix<double> matrix1(3, 3, {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}); print_cholesky_factor(matrix1); matrix<double> matrix2(4, 4, {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}); print_cholesky_factor(matrix2); return 0; }
c710
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { counter = 0; std::cout << " Puzzle: " << ( *i ).first << " cells and blocks [ "; for( std::vector<int>::iterator it = ( *i ).second.begin(); it != ( *i ).second.end(); it++ ) std::cout << *it << " "; std::cout << "] "; int s = std::accumulate( ( *i ).second.begin(), ( *i ).second.end(), 0 ) + ( ( *i ).second.size() > 0 ? ( *i ).second.size() - 1 : 0 ); if( ( *i ).first - s < 0 ) { std::cout << "has no solution!\n\n\n"; continue; } std::cout << "\n Possible configurations:\n\n"; std::string b( ( *i ).first, '-' ); solve( *i, b, 0 ); std::cout << "\n\n"; } } private: void solve( puzzle p, std::string n, int start ) { if( p.second.size() < 1 ) { output( n ); return; } std::string temp_string; int offset, this_block_size = p.second[0]; int space_need_for_others = std::accumulate( p.second.begin() + 1, p.second.end(), 0 ); space_need_for_others += p.second.size() - 1; int space_for_curr_block = p.first - space_need_for_others - std::accumulate( p.second.begin(), p.second.begin(), 0 ); std::vector<int> v1( p.second.size() - 1 ); std::copy( p.second.begin() + 1, p.second.end(), v1.begin() ); puzzle p1 = std::make_pair( space_need_for_others, v1 ); for( int a = 0; a < space_for_curr_block; a++ ) { temp_string = n; if( start + this_block_size > n.length() ) return; for( offset = start; offset < start + this_block_size; offset++ ) temp_string.at( offset ) = 'o'; if( p1.first ) solve( p1, temp_string, offset + 1 ); else output( temp_string ); start++; } } void output( std::string s ) { char b = 65 - ( s.at( 0 ) == '-' ? 1 : 0 ); bool f = false; std::cout << std::setw( 3 ) << ++counter << "\t|"; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { b += ( *i ) == 'o' && f ? 1 : 0; std::cout << ( ( *i ) == 'o' ? b : '_' ) << "|"; f = ( *i ) == '-' ? true : false; } std::cout << "\n"; } unsigned counter; }; int main( int argc, char* argv[] ) { std::vector<puzzle> problems; std::vector<int> blocks; blocks.push_back( 2 ); blocks.push_back( 1 ); problems.push_back( std::make_pair( 5, blocks ) ); blocks.clear(); problems.push_back( std::make_pair( 5, blocks ) ); blocks.push_back( 8 ); problems.push_back( std::make_pair( 10, blocks ) ); blocks.clear(); blocks.push_back( 2 ); blocks.push_back( 3 ); problems.push_back( std::make_pair( 5, blocks ) ); blocks.push_back( 2 ); blocks.push_back( 3 ); problems.push_back( std::make_pair( 15, blocks ) ); nonoblock nn; nn.solve( problems ); return 0; }
c711
#include <iostream> #include <vector> using Sequence = std::vector<int>; std::ostream& operator<<(std::ostream& os, const Sequence& v) { os << "[ "; for (const auto& e : v) { std::cout << e << ", "; } os << "]"; return os; } int next_in_cycle(const Sequence& s, size_t i) { return s[i % s.size()]; } Sequence gen_kolakoski(const Sequence& s, int n) { Sequence seq; for (size_t i = 0; seq.size() < n; ++i) { const int next = next_in_cycle(s, i); Sequence nv(i >= seq.size() ? next : seq[i], next); seq.insert(std::end(seq), std::begin(nv), std::end(nv)); } return { std::begin(seq), std::begin(seq) + n }; } bool is_possible_kolakoski(const Sequence& s) { Sequence r; for (size_t i = 0; i < s.size();) { int count = 1; for (size_t j = i + 1; j < s.size(); ++j) { if (s[j] != s[i]) break; ++count; } r.push_back(count); i += count; } for (size_t i = 0; i < r.size(); ++i) if (r[i] != s[i]) return false; return true; } int main() { std::vector<Sequence> seqs = { { 1, 2 }, { 2, 1 }, { 1, 3, 1, 2 }, { 1, 3, 2, 1 } }; for (const auto& s : seqs) { auto kol = gen_kolakoski(s, s.size() > 2 ? 30 : 20); std::cout << "Starting with: " << s << ": " << std::endl << "Kolakoski sequence: " << kol << std::endl << "Possibly kolakoski? " << is_possible_kolakoski(kol) << std::endl; } return 0; }
c712
#include <algorithm> #include <iostream> #include <string> std::string generate(int n, char left = '[', char right = ']') { std::string str(std::string(n, left) + std::string(n, right)); std::random_shuffle(str.begin(), str.end()); return str; } bool balanced(const std::string &str, char left = '[', char right = ']') { int count = 0; for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == left) count++; else if (*it == right) if (--count < 0) return false; } return count == 0; } int main() { srand(time(NULL)); for (int i = 0; i < 9; ++i) { std::string s(generate(i)); std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n"; } }
c713
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } int main() { for (unsigned int n = 1; n < 200; n += 2) { auto p = n * n * n + 2; if (is_prime(p)) std::cout << std::setw(3) << n << std::setw(9) << p << '\n'; } }
c714
#include <iostream> #include <iomanip> int main( int argc, char* argv[] ) { int sol = 1; std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n"; for( int f = 1; f < 8; f++ ) { for( int p = 1; p < 8; p++ ) { for( int s = 1; s < 8; s++ ) { if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) { std::cout << "SOLUTION #" << std::setw( 2 ) << sol++ << std::setw( 2 ) << ":\t" << std::setw( 2 ) << f << "\t\t " << std::setw( 3 ) << p << "\t\t" << std::setw( 6 ) << s << "\n"; } } } } return 0; }
c715
#include <iostream> #include <cmath> #ifdef M_PI double const pi = M_PI; #else double const pi = 4*std::atan(1); #endif double const degree = pi/180; int main() { std::cout << "=== radians ===\n"; std::cout << "sin(pi/3) = " << std::sin(pi/3) << "\n"; std::cout << "cos(pi/3) = " << std::cos(pi/3) << "\n"; std::cout << "tan(pi/3) = " << std::tan(pi/3) << "\n"; std::cout << "arcsin(1/2) = " << std::asin(0.5) << "\n"; std::cout << "arccos(1/2) = " << std::acos(0.5) << "\n"; std::cout << "arctan(1/2) = " << std::atan(0.5) << "\n"; std::cout << "\n=== degrees ===\n"; std::cout << "sin(60°) = " << std::sin(60*degree) << "\n"; std::cout << "cos(60°) = " << std::cos(60*degree) << "\n"; std::cout << "tan(60°) = " << std::tan(60*degree) << "\n"; std::cout << "arcsin(1/2) = " << std::asin(0.5)/degree << "°\n"; std::cout << "arccos(1/2) = " << std::acos(0.5)/degree << "°\n"; std::cout << "arctan(1/2) = " << std::atan(0.5)/degree << "°\n"; return 0; }
c716
#include <iostream> std::ostream& operator<<(std::ostream& out, const std::string& str) { return out << str.c_str(); } std::string textBetween(const std::string& source, const std::string& beg, const std::string& end) { size_t startIndex; if (beg == "start") { startIndex = 0; } else { startIndex = source.find(beg); if (startIndex == std::string::npos) { return ""; } startIndex += beg.length(); } size_t endIndex = source.find(end, startIndex); if (endIndex == std::string::npos || end == "end") { return source.substr(startIndex); } return source.substr(startIndex, endIndex - startIndex); } void print(const std::string& source, const std::string& beg, const std::string& end) { using namespace std; cout << "text: '" << source << "'\n"; cout << "start: '" << beg << "'\n"; cout << "end: '" << end << "'\n"; cout << "result: '" << textBetween(source, beg, end) << "'\n"; cout << '\n'; } int main() { print("Hello Rosetta Code world", "Hello ", " world"); print("Hello Rosetta Code world", "start", " world"); print("Hello Rosetta Code world", "Hello ", "end"); print("<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">", "<text>", "<table>"); print("<table style=\"myTable\"><tr><td>hello world</td></tr></table>", "<table>", "</table>"); print("The quick brown fox jumps over the lazy other fox", "quick ", " fox"); print("One fish two fish red fish blue fish", "fish ", " red"); print("FooBarBazFooBuxQuux", "Foo", "Foo"); return 0; }
c717
#include <algorithm> #include <iostream> #include <numeric> #include <vector> #include <list> using std::begin, std::end, std::for_each; std::list<std::vector<int>> combinations(int from, int to) { if (from > to) return {}; auto pool = std::vector<int>(to - from); std::iota(begin(pool), end(pool), from); auto solutions = std::list<std::vector<int>>{}; for (auto a : pool) for (auto b : pool) for (auto c : pool) for (auto d : pool) for (auto e : pool) for (auto f : pool) for (auto g : pool) if ( a == c + d && b + c == e + f && d + e == g ) solutions.push_back({a, b, c, d, e, f, g}); return solutions; } std::list<std::vector<int>> filter_unique(int from, int to) { auto has_non_unique_values = [](const auto & range, auto target) { return std::count( begin(range), end(range), target) > 1; }; auto results = combinations(from, to); for (auto subrange = cbegin(results); subrange != cend(results); ++subrange) { bool repetition = false; for (auto x : *subrange) repetition |= has_non_unique_values(*subrange, x); if (repetition) { results.erase(subrange); --subrange; } } return results; } template <class Container> inline void print_range(const Container & c) { for (const auto & subrange : c) { std::cout << "["; for (auto elem : subrange) std::cout << elem << ' '; std::cout << "\b]\n"; } } int main() { std::cout << "Unique-numbers combinations in range 1-7:\n"; auto solution1 = filter_unique(1, 8); print_range(solution1); std::cout << "\nUnique-numbers combinations in range 3-9:\n"; auto solution2 = filter_unique(3,10); print_range(solution2); std::cout << "\nNumber of combinations in range 0-9: " << combinations(0, 10).size() << "." << std::endl; return 0; }
c718
#include <iostream> #include <stddef.h> #include <assert.h> using std::cout; using std::endl; class SMA { public: SMA(unsigned int period) : period(period), window(new double[period]), head(NULL), tail(NULL), total(0) { assert(period >= 1); } ~SMA() { delete[] window; } void add(double val) { if (head == NULL) { head = window; *head = val; tail = head; inc(tail); total = val; return; } if (head == tail) { total -= *head; inc(head); } *tail = val; inc(tail); total += val; } double avg() const { ptrdiff_t size = this->size(); if (size == 0) { return 0; } return total / (double) size; } private: unsigned int period; double * window; double * head; double * tail; double total; void inc(double * & p) { if (++p >= window + period) { p = window; } } ptrdiff_t size() const { if (head == NULL) return 0; if (head == tail) return period; return (period + tail - head) % period; } }; int main(int argc, char * * argv) { SMA foo(3); SMA bar(5); int data[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 }; for (int * itr = data; itr < data + 10; itr++) { foo.add(*itr); cout << "Added " << *itr << " avg: " << foo.avg() << endl; } cout << endl; for (int * itr = data; itr < data + 10; itr++) { bar.add(*itr); cout << "Added " << *itr << " avg: " << bar.avg() << endl; } return 0; }
c719
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsigned int mask_length() const { return mask_length_; } friend std::istream& operator>>(std::istream&, ipv4_cidr&); private: std::uint32_t address_ = 0; unsigned int mask_length_ = 0; }; std::istream& operator>>(std::istream& in, ipv4_cidr& cidr) { int a, b, c, d, m; char ch; if (!(in >> a >> ch) || a < 0 || a > UINT8_MAX || ch != '.' || !(in >> b >> ch) || b < 0 || b > UINT8_MAX || ch != '.' || !(in >> c >> ch) || c < 0 || c > UINT8_MAX || ch != '.' || !(in >> d >> ch) || d < 0 || d > UINT8_MAX || ch != '/' || !(in >> m) || m < 1 || m > 32) { in.setstate(std::ios_base::failbit); return in; } uint32_t mask = ~((1 << (32 - m)) - 1); uint32_t address = (a << 24) + (b << 16) + (c << 8) + d; address &= mask; cidr.address_ = address; cidr.mask_length_ = m; return in; } std::ostream& operator<<(std::ostream& out, const ipv4_cidr& cidr) { uint32_t address = cidr.address(); unsigned int d = address & UINT8_MAX; address >>= 8; unsigned int c = address & UINT8_MAX; address >>= 8; unsigned int b = address & UINT8_MAX; address >>= 8; unsigned int a = address & UINT8_MAX; out << a << '.' << b << '.' << c << '.' << d << '/' << cidr.mask_length(); return out; } int main(int argc, char** argv) { const char* tests[] = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18" }; for (auto test : tests) { std::istringstream in(test); ipv4_cidr cidr; if (in >> cidr) std::cout << std::setw(18) << std::left << test << " -> " << cidr << '\n'; else std::cerr << test << ": invalid CIDR\n"; } return 0; }
c720
#include <string> #include <iostream> #include <algorithm> int main() { std::string s; std::getline(std::cin, s); std::reverse(s.begin(), s.end()); std::cout << s << '\n'; }
c721
#include <windows.h> #include <iostream> #include <string> using namespace std; const int BMP_SIZE = 512, CELL_SIZE = 8; enum directions { NONE, NOR = 1, EAS = 2, SOU = 4, WES = 8 }; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; 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() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } 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: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class mazeGenerator { public: mazeGenerator() { _world = 0; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.setPenColor( RGB( 0, 255, 0 ) ); } ~mazeGenerator() { killArray(); } void create( int side ) { _s = side; generate(); display(); } private: void generate() { killArray(); _world = new BYTE[_s * _s]; ZeroMemory( _world, _s * _s ); _ptX = rand() % _s; _ptY = rand() % _s; carve(); } void carve() { while( true ) { int d = getDirection(); if( d < NOR ) return; switch( d ) { case NOR: _world[_ptX + _s * _ptY] |= NOR; _ptY--; _world[_ptX + _s * _ptY] = SOU | SOU << 4; break; case EAS: _world[_ptX + _s * _ptY] |= EAS; _ptX++; _world[_ptX + _s * _ptY] = WES | WES << 4; break; case SOU: _world[_ptX + _s * _ptY] |= SOU; _ptY++; _world[_ptX + _s * _ptY] = NOR | NOR << 4; break; case WES: _world[_ptX + _s * _ptY] |= WES; _ptX--; _world[_ptX + _s * _ptY] = EAS | EAS << 4; } } } void display() { _bmp.clear(); HDC dc = _bmp.getDC(); for( int y = 0; y < _s; y++ ) { int yy = y * _s; for( int x = 0; x < _s; x++ ) { BYTE b = _world[x + yy]; int nx = x * CELL_SIZE, ny = y * CELL_SIZE; if( !( b & NOR ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny ); } if( !( b & EAS ) ) { MoveToEx( dc, nx + CELL_SIZE, ny, NULL ); LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 ); } if( !( b & SOU ) ) { MoveToEx( dc, nx, ny + CELL_SIZE, NULL ); LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE ); } if( !( b & WES ) ) { MoveToEx( dc, nx, ny, NULL ); LineTo( dc, nx, ny + CELL_SIZE + 1 ); } } } BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY ); } int getDirection() { int d = 1 << rand() % 4; while( true ) { for( int x = 0; x < 4; x++ ) { if( testDir( d ) ) return d; d <<= 1; if( d > 8 ) d = 1; } d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4; if( !d ) return -1; switch( d ) { case NOR: _ptY--; break; case EAS: _ptX++; break; case SOU: _ptY++; break; case WES: _ptX--; break; } d = 1 << rand() % 4; } } bool testDir( int d ) { switch( d ) { case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] ); case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] ); case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] ); case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] ); } return false; } void killArray() { if( _world ) delete [] _world; } BYTE* _world; int _s, _ptX, _ptY; myBitmap _bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() ); mazeGenerator mg; int s; while( true ) { cout << "Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): "; cin >> s; if( !s ) return 0; if( !( s & 1 ) ) s++; if( s >= 3 ) mg.create( s ); cout << endl; system( "pause" ); system( "cls" ); } return 0; }
c722
#include <string> #include <algorithm> bool is_palindrome(std::string const& s) { return std::equal(s.begin(), s.end(), s.rbegin()); }
c723
#include <iostream> #include <vector> #include <chrono> #include <climits> #include <cmath> using namespace std; vector <long long> primes{ 3, 5 }; int main() { cout.imbue(locale("")); const int cutOff = 200, bigUn = 100000, chunks = 50, little = bigUn / chunks; const char tn[] = " cuban prime"; cout << "The first " << cutOff << tn << "s:" << endl; int c = 0; bool showEach = true; long long u = 0, v = 1; auto st = chrono::system_clock::now(); for (long long i = 1; i <= LLONG_MAX; i++) { bool found = false; long long mx = (long long)(ceil(sqrt(v += (u += 6)))); for (long long item : primes) { if (item > mx) break; if (v % item == 0) { found = true; break; } } if (!found) { c += 1; if (showEach) { for (long long z = primes.back() + 2; z <= v - 2; z += 2) { bool fnd = false; for (long long item : primes) { if (item > mx) break; if (z % item == 0) { fnd = true; break; } } if (!fnd) primes.push_back(z); } primes.push_back(v); cout.width(11); cout << v; if (c % 10 == 0) cout << endl; if (c == cutOff) { showEach = false; cout << "\nProgress to the " << bigUn << "th" << tn << ": "; } } if (c % little == 0) { cout << "."; if (c == bigUn) break; } } } cout << "\nThe " << c << "th" << tn << " is " << v; chrono::duration<double> elapsed_seconds = chrono::system_clock::now() - st; cout << "\nComputation time was " << elapsed_seconds.count() << " seconds" << endl; return 0; }
c724
#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 ; }
c725
#include <iostream> int main() { int i; for (i = 1; i<=10 ; i++){ std::cout << i; if (i < 10) std::cout << ", "; } return 0; }
c726
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); std::cout << "The 10,001st prime is " << primesieve::nth_prime(10001) << ".\n"; }
c727
#include <algorithm> #include <cmath> #include <iostream> #include <tuple> #include <vector> int gcd(int a, int b) { int rem = 1, dividend, divisor; std::tie(divisor, dividend) = std::minmax(a, b); while (rem != 0) { rem = dividend % divisor; if (rem != 0) { dividend = divisor; divisor = rem; } } return divisor; } struct Triangle { int a; int b; int c; }; int perimeter(const Triangle& triangle) { return triangle.a + triangle.b + triangle.c; } double area(const Triangle& t) { double p_2 = perimeter(t) / 2.; double area_sq = p_2 * ( p_2 - t.a ) * ( p_2 - t.b ) * ( p_2 - t.c ); return sqrt(area_sq); } std::vector<Triangle> 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) { Triangle t{a, b, c}; double t_area = area(t); if(t_area == 0) continue; if( std::floor(t_area) == std::ceil(t_area) && gcd(a, gcd(b, c)) == 1) result.push_back(t); } return result; } bool compare(const Triangle& lhs, const Triangle& rhs) { return std::make_tuple(area(lhs), perimeter(lhs), std::max(lhs.a, std::max(lhs.b, lhs.c))) < std::make_tuple(area(rhs), perimeter(rhs), std::max(rhs.a, std::max(rhs.b, rhs.c))); } struct area_compare { bool operator()(const Triangle& t, int i) { return area(t) < i; } bool operator()(int i, const Triangle& t) { return i < area(t); } }; 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 << area(tri[i]) << '\t' << perimeter(tri[i]) << "\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 << area(*it) << '\t' << perimeter(*it) << "\t\t" << it->a << 'x' << it->b << 'x' << it->c << '\n'; }
c728
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_category, point, point>; double distance(point l, point r) { return std::hypot(l.x - r.x, l.y - r.y); } result_t find_circles(point p1, point p2, double r) { point ans1 { 1/0., 1/0.}, ans2 { 1/0., 1/0.}; if (p1 == p2) { if(r == 0.) return std::make_tuple(ONE_COINCEDENT, p1, p2 ); else return std::make_tuple(INFINITE, ans1, ans2); } point center { p1.x/2 + p2.x/2, p1.y/2 + p2.y/2}; double half_distance = distance(center, p1); if(half_distance > r) return std::make_tuple(NONE, ans1, ans2); if(half_distance - r == 0) return std::make_tuple(ONE_DIAMETER, center, ans2); double root = std::hypot(r, half_distance) / distance(p1, p2); ans1.x = center.x + root * (p1.y - p2.y); ans1.y = center.y + root * (p2.x - p1.x); ans2.x = center.x - root * (p1.y - p2.y); ans2.y = center.y - root * (p2.x - p1.x); return std::make_tuple(TWO, ans1, ans2); } void print(result_t result, std::ostream& out = std::cout) { point r1, r2; result_category res; std::tie(res, r1, r2) = result; switch(res) { case NONE: out << "There are no solutions, points are too far away\n"; break; case ONE_COINCEDENT: case ONE_DIAMETER: out << "Only one solution: " << r1.x << ' ' << r1.y << '\n'; break; case INFINITE: out << "Infinitely many circles can be drawn\n"; break; case TWO: out << "Two solutions: " << r1.x << ' ' << r1.y << " and " << r2.x << ' ' << r2.y << '\n'; break; } } int main() { constexpr int size = 5; const point points[size*2] = { {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345}, {0.1234, 0.9876}, {0.1234, 0.9876} }; const double radius[size] = {2., 1., 2., .5, 0.}; for(int i = 0; i < size; ++i) print(find_circles(points[i*2], points[i*2 + 1], radius[i])); }
c729
#include <iostream> #include <string> #include <vector> void print_vector(const std::vector<int> &pos, const std::vector<std::string> &str) { for (size_t i = 1; i < pos.size(); ++i) printf("%s\t", str[pos[i]].c_str()); printf("\n"); } void combination_with_repetiton(int n, int k, const std::vector<std::string> &str) { std::vector<int> pos(k + 1, 0); while (true) { for (int i = k; i > 0; i -= 1) { if (pos[i] > n - 1) { pos[i - 1] += 1; for (int j = i; j <= k; j += 1) pos[j] = pos[j - 1]; } } if (pos[0] > 0) break; print_vector(pos, str); pos[k] += 1; } } int main() { std::vector<std::string> str{"iced", "jam", "plain"}; combination_with_repetiton(3, 2, str); return 0; }
c730
#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; }
c731
#include <iterator> #include <utility> #include <algorithm> #include <list> #include <iostream> template<typename T> struct referring { referring(T const& t): value(t) {} template<typename Iter> bool operator()(std::pair<Iter, int> const& p) const { return *p.first == value; } T const& value; }; template<typename FwdIterator, typename OutIterator> void mode(FwdIterator first, FwdIterator last, OutIterator result) { typedef typename std::iterator_traits<FwdIterator>::value_type value_type; typedef std::list<std::pair<FwdIterator, int> > count_type; typedef typename count_type::iterator count_iterator; count_type counts; while (first != last) { count_iterator element = std::find_if(counts.begin(), counts.end(), referring<value_type>(*first)); if (element == counts.end()) counts.push_back(std::make_pair(first, 1)); else ++element->second; ++first; } int max = 0; for (count_iterator i = counts.begin(); i != counts.end(); ++i) if (i->second > max) max = i->second; for (count_iterator i = counts.begin(); i != counts.end(); ++i) if (i->second == max) *result++ = *i->first; } int main() { int values[] = { 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6 }; median(values, values + sizeof(values)/sizeof(int), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0; }
c733
#include <boost/date_time/gregorian/gregorian.hpp> #include <iostream> int main( ) { using namespace boost::gregorian ; std::cout << "Yuletide holidays must be allowed in the following years:\n" ; for ( int i = 2008 ; i < 2121 ; i++ ) { greg_year gy = i ; date d ( gy, Dec , 25 ) ; if ( d.day_of_week( ) == Sunday ) { std::cout << i << std::endl ; } } std::cout << "\n" ; return 0 ; }
c734
#include <iostream> using namespace std; template<class T = double> class Quaternion { public: T w, x, y, z; Quaternion(const T &w, const T &x, const T &y, const T &z): w(w), x(x), y(y), z(z) {}; Quaternion(const T &x, const T &y, const T &z): w(T()), x(x), y(y), z(z) {}; Quaternion(const T &r): w(r), x(T()), y(T()), z(T()) {}; Quaternion(): w(T()), x(T()), y(T()), z(T()) {}; Quaternion(const Quaternion &q): w(q.w), x(q.x), y(q.y), z(q.z) {}; Quaternion& operator=(const Quaternion &q) { w=q.w; x=q.x; y=q.y; z=q.z; return *this; } Quaternion operator-() const { return Quaternion(-w, -x, -y, -z); } Quaternion operator~() const { return Quaternion(w, -x, -y, -z); } T normSquared() const { return w*w + x*x + y*y + z*z; } Quaternion& operator+=(const T &r) { w += r; return *this; } Quaternion& operator+=(const Quaternion &q) { w += q.w; x += q.x; y += q.y; z += q.z; return *this; } Quaternion& operator-=(const T &r) { w -= r; return *this; } Quaternion& operator-=(const Quaternion &q) { w -= q.w; x -= q.x; y -= q.y; z -= q.z; return *this; } Quaternion& operator*=(const T &r) { w *= r; x *= r; y *= r; z *= r; return *this; } Quaternion& operator*=(const Quaternion &q) { T oldW(w), oldX(x), oldY(y), oldZ(z); w = oldW*q.w - oldX*q.x - oldY*q.y - oldZ*q.z; x = oldW*q.x + oldX*q.w + oldY*q.z - oldZ*q.y; y = oldW*q.y + oldY*q.w + oldZ*q.x - oldX*q.z; z = oldW*q.z + oldZ*q.w + oldX*q.y - oldY*q.x; return *this; } Quaternion& operator/=(const T &r) { w /= r; x /= r; y /= r; z /= r; return *this; } Quaternion& operator/=(const Quaternion &q) { T oldW(w), oldX(x), oldY(y), oldZ(z), n(q.normSquared()); w = (oldW*q.w + oldX*q.x + oldY*q.y + oldZ*q.z) / n; x = (oldX*q.w - oldW*q.x + oldY*q.z - oldZ*q.y) / n; y = (oldY*q.w - oldW*q.y + oldZ*q.x - oldX*q.z) / n; z = (oldZ*q.w - oldW*q.z + oldX*q.y - oldY*q.x) / n; return *this; } Quaternion operator+(const T &r) const { return Quaternion(*this) += r; } Quaternion operator+(const Quaternion &q) const { return Quaternion(*this) += q; } Quaternion operator-(const T &r) const { return Quaternion(*this) -= r; } Quaternion operator-(const Quaternion &q) const { return Quaternion(*this) -= q; } Quaternion operator*(const T &r) const { return Quaternion(*this) *= r; } Quaternion operator*(const Quaternion &q) const { return Quaternion(*this) *= q; } Quaternion operator/(const T &r) const { return Quaternion(*this) /= r; } Quaternion operator/(const Quaternion &q) const { return Quaternion(*this) /= q; } bool operator==(const Quaternion &q) const { return (w == q.w) && (x == q.x) && (y == q.y) && (z == q.z); } bool operator!=(const Quaternion &q) const { return !operator==(q); } template<class T> friend Quaternion<T> operator+(const T &r, const Quaternion<T> &q); template<class T> friend Quaternion<T> operator-(const T &r, const Quaternion<T> &q); template<class T> friend Quaternion<T> operator*(const T &r, const Quaternion<T> &q); template<class T> friend Quaternion<T> operator/(const T &r, const Quaternion<T> &q); template<class T> friend ostream& operator<<(ostream &io, const Quaternion<T> &q); }; template<class T> Quaternion<T> operator+(const T &r, const Quaternion<T> &q) { return q+r; } template<class T> Quaternion<T> operator-(const T &r, const Quaternion<T> &q) { return Quaternion<T>(r-q.w, q.x, q.y, q.z); } template<class T> Quaternion<T> operator*(const T &r, const Quaternion<T> &q) { return q*r; } template<class T> Quaternion<T> operator/(const T &r, const Quaternion<T> &q) { T n(q.normSquared()); return Quaternion(r*q.w/n, -r*q.x/n, -r*q.y/n, -r*q.z/n); } template<class T> ostream& operator<<(ostream &io, const Quaternion<T> &q) { io << q.w; (q.x < T()) ? (io << " - " << (-q.x) << "i") : (io << " + " << q.x << "i"); (q.y < T()) ? (io << " - " << (-q.y) << "j") : (io << " + " << q.y << "j"); (q.z < T()) ? (io << " - " << (-q.z) << "k") : (io << " + " << q.z << "k"); return io; }
c735
#include<iostream> #include<math.h> #include<stdlib.h> #include<time.h> using namespace std; int main(){ int jmax=1000; int imax=1000; double x,y; int hit; srand(time(0)); for (int j=0;j<jmax;j++){ hit=0; x=0; y=0; for(int i=0;i<imax;i++){ x=double(rand())/double(RAND_MAX); y=double(rand())/double(RAND_MAX); if(y<=sqrt(1-pow(x,2))) hit+=1; } cout<<""<<4*double(hit)/double(imax)<<endl; } }
c736
#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; }
c737
#include <iostream> #include <windows.h> const int EL_COUNT = 77, LLEN = 11; class cocktailSort { public: void sort( int* arr, int len ) { bool notSorted = true; while( notSorted ) { notSorted = false; for( int a = 0; a < len - 1; a++ ) { if( arr[a] > arr[a + 1] ) { sSwap( arr[a], arr[a + 1] ); notSorted = true; } } if( !notSorted ) break; notSorted = false; for( int a = len - 1; a > 0; a-- ) { if( arr[a - 1] > arr[a] ) { sSwap( arr[a], arr[a - 1] ); notSorted = true; } } } } private: void sSwap( int& a, int& b ) { int t = a; a = b; b = t; } }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); cocktailSort cs; int arr[EL_COUNT]; for( int x = 0; x < EL_COUNT; x++ ) arr[x] = rand() % EL_COUNT + 1; std::cout << "Original: " << std::endl << "==========" << std::endl; for( int x = 0; x < EL_COUNT; x += LLEN ) { for( int s = x; s < x + LLEN; s++ ) std::cout << arr[s] << ", "; std::cout << std::endl; } cs.sort( arr, EL_COUNT ); std::cout << std::endl << std::endl << "Sorted: " << std::endl << "========" << std::endl; for( int x = 0; x < EL_COUNT; x += LLEN ) { for( int s = x; s < x + LLEN; s++ ) std::cout << arr[s] << ", "; std::cout << std::endl; } std::cout << std::endl << std::endl << std::endl << std::endl; return 0; }
c738
#include <math.h> #include <numbers> #include <stdio.h> #include <vector> std::vector<double> CalculateCoefficients(int numCoeff) { std::vector<double> c(numCoeff); double k1_factrl = 1.0; c[0] = sqrt(2.0 * std::numbers::pi); for(size_t k=1; k < numCoeff; k++) { c[k] = exp(numCoeff-k) * pow(numCoeff-k, k-0.5) / k1_factrl; k1_factrl *= -(double)k; } return c; } double Gamma(const std::vector<double>& coeffs, double x) { const size_t numCoeff = coeffs.size(); double accm = coeffs[0]; for(size_t k=1; k < numCoeff; k++) { accm += coeffs[k] / ( x + k ); } accm *= exp(-(x+numCoeff)) * pow(x+numCoeff, x+0.5); return accm/x; } int main() { const auto coeff1 = CalculateCoefficients(1); const auto coeff4 = CalculateCoefficients(4); const auto coeff10 = CalculateCoefficients(10); const auto inputs = std::vector<double>{ 0.001, 0.01, 0.1, 0.5, 1.0, 1.461632145, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100, 150 }; printf("%16s%16s%16s%16s%16s\n", "gamma( x ) =", "Spouge 1", "Spouge 4", "Spouge 10", "built-in"); for(auto x : inputs) { printf("gamma(%7.3f) = %16.10g %16.10g %16.10g %16.10g\n", x, Gamma(coeff1, x), Gamma(coeff4, x), Gamma(coeff10, x), std::tgamma(x)); } }
c739
#include <iostream> #include <string> #include <vector> std::vector<std::string> makeList(std::string separator) { auto counter = 0; auto makeItem = [&](std::string item) { return std::to_string(++counter) + separator + item; }; return {makeItem("first"), makeItem("second"), makeItem("third")}; } int main() { for (auto item : makeList(". ")) std::cout << item << "\n"; }
c740
#include <iostream> #include <iomanip> #include <vector> using uint = unsigned int; std::vector<uint> divisors(uint n) { std::vector<uint> divs; for (uint d=1; d<=n/2; d++) { if (n % d == 0) divs.push_back(d); } return divs; } uint reverse(uint n) { uint r; for (r = 0; n; n /= 10) r = (r*10) + (n%10); return r; } bool special(uint n) { for (uint d : divisors(n)) if (reverse(n) % reverse(d) != 0) return false; return true; } int main() { for (uint n=1, c=0; n < 200; n++) { if (special(n)) { std::cout << std::setw(4) << n; if (++c == 10) { c = 0; std::cout << std::endl; } } } std::cout << std::endl; return 0; }
c741
#include <iostream> #include <cmath> int main() { int n = 1; int count = 0; int sq; int cr; for (; count < 30; ++n) { sq = n * n; cr = cbrt(sq); if (cr * cr * cr != sq) { count++; std::cout << sq << '\n'; } else { std::cout << sq << " is square and cube\n"; } } return 0; }
c742
#include <iostream> int main() { std::cout << "\a"; return 0; }
c743
#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; }
c744
double NthRoot(double m_nValue, double index, double guess, double pc) { double result = guess; double result_next; do { result_next = (1.0/index)*((index-1.0)*result+(m_nValue)/(pow(result,(index-1.0)))); result = result_next; pc--; }while(pc>1); return result; };
c745
#include <iostream> #include <boost/filesystem.hpp> using namespace boost::filesystem; int main(int argc, char *argv[]) { for (int i = 1; i < argc; ++i) { path p(argv[i]); if (exists(p) && is_directory(p)) std::cout << "'" << argv[i] << "' is" << (!is_empty(p) ? " not" : "") << " empty\n"; else std::cout << "dir '" << argv[i] << "' could not be found\n"; } }
c746
#include <filesystem> #include <iostream> namespace fs = std::filesystem; int main(int argc, char* argv[]) { if(argc != 2) { std::cout << "usage: mkdir <path>\n"; return -1; } fs::path pathToCreate(argv[1]); if (fs::exists(pathToCreate)) return 0; if (fs::create_directories(pathToCreate)) return 0; else { std::cout << "couldn't create directory: " << pathToCreate.string() << std::endl; return -1; } }
c747
#if _WIN32 #include <io.h> #define ISATTY _isatty #define FILENO _fileno #else #include <unistd.h> #define ISATTY isatty #define FILENO fileno #endif #include <iostream> int main() { if (ISATTY(FILENO(stdout))) { std::cout << "stdout is a tty\n"; } else { std::cout << "stdout is not a tty\n"; } return 0; }
c748
#include <algorithm> #include <string> constexpr bool is_palindrome(std::string_view s) { return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin()); }
c749
#include <iostream> const int WIDTH = 81; const int HEIGHT = 5; char lines[WIDTH*HEIGHT]; void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); } int main() { for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; } cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); } return 0; }
c750
#if !defined(__cplusplus) || __cplusplus < 201103L #pragma error("The following code requires at least C++11.") #else #endif
c751
bool isOdd(int x) { return x % 2; } bool isEven(int x) { return !(x % 2); }
c752
#include <vector> #include <utility> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <cmath> bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) { std::ostringstream numberstream ; numberstream << number ; std::string numberstring( numberstream.str( ) ) ; std::sort ( numberstring.begin( ) , numberstring.end( ) ) ; int fanglength = numberstring.length( ) / 2 ; long start = static_cast<long>( std::pow( 10 , fanglength - 1 ) ) ; long end = sqrt(number) ; for ( long i = start ; i <= end ; i++ ) { if ( number % i == 0 ) { long quotient = number / i ; if ( ( i % 10 == 0 ) && ( quotient % 10 == 0 ) ) continue ; numberstream.str( "" ) ; numberstream << i << quotient ; std::string divisorstring ( numberstream.str( ) ) ; std::sort ( divisorstring.begin( ) , divisorstring.end( ) ) ; if ( divisorstring == numberstring ) { std::pair<long , long> divisors = std::make_pair( i, quotient ) ; solution.push_back( divisors ) ; } } } return !solution.empty( ) ; } void printOut( const std::pair<long, long> & solution ) { std::cout << "[ " << solution.first << " , " << solution.second << " ]" ; } int main( ) { int vampireNumbersFound = 0 ; std::vector<std::pair<long , long> > solutions ; double i = 1.0 ; while ( vampireNumbersFound < 25 ) { long start = static_cast<long>( std::pow( 10 , i ) ) ; long end = start * 10 ; for ( long num = start ; num < end ; num++ ) { if ( isVampireNumber( num , solutions ) ) { vampireNumbersFound++ ; std::cout << vampireNumbersFound << " :" << num << " is a vampire number! These are the fangs:\n" ; std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ; std::cout << "\n_______________" << std::endl ; solutions.clear( ) ; if ( vampireNumbersFound == 25 ) break ; } } i += 2.0 ; } std::vector<long> testnumbers ; testnumbers.push_back( 16758243290880 ) ; testnumbers.push_back( 24959017348650 ) ; testnumbers.push_back( 14593825548650 ) ; for ( std::vector<long>::const_iterator svl = testnumbers.begin( ) ; svl != testnumbers.end( ) ; svl++ ) { if ( isVampireNumber( *svl , solutions ) ) { std::cout << *svl << " is a vampire number! The fangs:\n" ; std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ; std::cout << std::endl ; solutions.clear( ) ; } else { std::cout << *svl << " is not a vampire number!" << std::endl ; } } return 0 ; }
c753
#include <iostream> #include <complex> int main() { std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl; return 0; }
c754
#include <array> #include <cstdlib> #include <ctime> #include <iostream> #include <string> int main() { constexpr std::array<const char*, 20> answers = { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful." }; std::string input; std::srand(std::time(nullptr)); while (true) { std::cout << "\n? : "; std::getline(std::cin, input); if (input.empty()) { break; } std::cout << answers[std::rand() % answers.size()] << '\n'; } }
c755
#include <iostream> enum class Mode { ENCRYPT, DECRYPT, }; const std::string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; const std::string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; std::string exec(std::string text, Mode mode, bool showSteps = false) { auto left = L_ALPHABET; auto right = R_ALPHABET; auto eText = new char[text.size() + 1]; auto temp = new char[27]; memset(eText, 0, text.size() + 1); memset(temp, 0, 27); for (size_t i = 0; i < text.size(); i++) { if (showSteps) std::cout << left << ' ' << right << '\n'; size_t index; if (mode == Mode::ENCRYPT) { index = right.find(text[i]); eText[i] = left[index]; } else { index = left.find(text[i]); eText[i] = right[index]; } if (i == text.size() - 1) break; for (int j = index; j < 26; ++j) temp[j - index] = left[j]; for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j]; auto store = temp[1]; for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; left = temp; for (int j = index; j < 26; ++j) temp[j - index] = right[j]; for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j]; store = temp[0]; for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j]; temp[25] = store; store = temp[2]; for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; right = temp; } return eText; } int main() { auto plainText = "WELLDONEISBETTERTHANWELLSAID"; std::cout << "The original plaintext is : " << plainText << "\n\n"; std::cout << "The left and right alphabets after each permutation during encryption are :\n"; auto cipherText = exec(plainText, Mode::ENCRYPT, true); std::cout << "\nThe ciphertext is : " << cipherText << '\n'; auto plainText2 = exec(cipherText, Mode::DECRYPT); std::cout << "\nThe recovered plaintext is : " << plainText2 << '\n'; return 0; }