_id stringlengths 2 5 | text stringlengths 7 10.9k | title stringclasses 1
value |
|---|---|---|
c450 | #include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
template<typename I>
void mark_composites(I start, I end)
{
std::fill(start, end, 0);
for (auto it = start + 1; it != end; ++it)
{
if (*it == 0)
{
auto prime = std::distance(start, it) + 1;
auto multiple_it = it;
while (std::distance(multiple_it, end) > prime)
{
std::advance(multiple_it, prime);
*multiple_it = 1;
}
}
}
}
template <typename I, typename O>
O sieve_primes(I start, I end, O out)
{
mark_composites(start, end);
for (auto it = start + 1; it != end; ++it)
{
if (*it == 0)
{
*out = std::distance(start, it) + 1;
++out;
}
}
return out;
}
int main()
{
std::vector<uint8_t> is_composite(1000);
sieve_primes(is_composite.begin(), is_composite.end(), std::ostream_iterator<int>(std::cout, " "));
}
| |
c451 | #include <iterator>
#include <algorithm>
#include <functional>
template<typename T>
T median(T t1, T t2, T t3)
{
if (t1 < t2)
{
if (t2 < t3)
return t2;
else if (t1 < t3)
return t3;
else
return t1;
}
else
{
if (t1 < t3)
return t1;
else if (t2 < t3)
return t3;
else
return t2;
}
}
template<typename Order> struct non_strict_op:
public std::binary_function<typename Order::second_argument_type,
typename Order::first_argument_type,
bool>
{
non_strict_op(Order o): order(o) {}
bool operator()(typename Order::second_argument_type arg1,
typename Order::first_argument_type arg2) const
{
return !order(arg2, arg1);
}
private:
Order order;
};
template<typename Order> non_strict_op<Order> non_strict(Order o)
{
return non_strict_op<Order>(o);
}
template<typename RandomAccessIterator,
typename Order>
void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order)
{
if (first != last && first+1 != last)
{
typedef typename std::iterator_traits<RandomAccessIterator>::value_type value_type;
RandomAccessIterator mid = first + (last - first)/2;
value_type pivot = median(*first, *mid, *(last-1));
RandomAccessIterator split1 = std::partition(first, last, std::bind2nd(order, pivot));
RandomAccessIterator split2 = std::partition(split1, last, std::bind2nd(non_strict(order), pivot));
quicksort(first, split1, order);
quicksort(split2, last, order);
}
}
template<typename RandomAccessIterator>
void quicksort(RandomAccessIterator first, RandomAccessIterator last)
{
quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
| |
c452 | #include <string>
using std::string;
int main()
{
string s = "Hello, world!";
string::size_type length = s.length();
string::size_type size = s.size();
string::size_type bytes = s.length() * sizeof(string::value_type);
}
| |
c453 | #include <iomanip>
#include <iostream>
#include <utility>
auto min_max_prime_factors(unsigned int n) {
unsigned int min_factor = 1;
unsigned int max_factor = 1;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
min_factor = 2;
max_factor = 2;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
if (min_factor == 1)
min_factor = p;
max_factor = p;
}
}
if (n > 1) {
if (min_factor == 1)
min_factor = n;
max_factor = n;
}
return std::make_pair(min_factor, max_factor);
}
int main() {
std::cout << "Product of smallest and greatest prime factors of n for 1 to "
"100:\n";
for (unsigned int n = 1; n <= 100; ++n) {
auto p = min_max_prime_factors(n);
std::cout << std::setw(4) << p.first * p.second
<< (n % 10 == 0 ? '\n' : ' ');
}
}
| |
c454 |
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
using namespace Poco::Net;
int main (int argc, char **argv)
{
try
{
MailMessage msg;
msg.addRecipient (MailRecipient (MailRecipient::PRIMARY_RECIPIENT,
"alice@example.com",
"Alice Moralis"));
msg.addRecipient (MailRecipient (MailRecipient::CC_RECIPIENT,
"pat@example.com",
"Patrick Kilpatrick"));
msg.addRecipient (MailRecipient (MailRecipient::BCC_RECIPIENT,
"mike@example.com",
"Michael Carmichael"));
msg.setSender ("Roy Kilroy <roy@example.com>");
msg.setSubject ("Rosetta Code");
msg.setContent ("Sending mail from C++ using POCO C++ Libraries");
SMTPClientSession smtp ("mail.example.com");
smtp.login ();
smtp.sendMessage (msg);
smtp.close ();
std::cerr << "Sent mail successfully!" << std::endl;
}
catch (std::exception &e)
{
std::cerr << "failed to send mail: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| |
c455 | #include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
double result;
double capacity = 15;
int NumberOfItems;
int number;
struct items
{
char name[32];
double weight;
double price;
double m;
} item[256];
bool cmp(items a,items b)
{
return a.price/a.weight > b.price/b.weight;
}
int main()
{
NumberOfItems=9;
strcpy(item[1].name,"beef");
item[1].weight=3.8;
item[1].price=36;
strcpy(item[2].name,"pork");
item[2].weight=5.4;
item[2].price=43;
strcpy(item[3].name,"ham");
item[3].weight=3.6;
item[3].price=90;
strcpy(item[4].name,"greaves");
item[4].weight=2.4;
item[4].price=45;
strcpy(item[5].name,"flitch");
item[5].weight=4.0;
item[5].price=30;
strcpy(item[6].name,"brawn");
item[6].weight=2.5;
item[6].price=56;
strcpy(item[7].name,"welt");
item[7].weight=3.7;
item[7].price=67;
strcpy(item[8].name,"salami");
item[8].weight=3.0;
item[8].price=95;
strcpy(item[9].name,"sausage");
item[9].weight=5.9;
item[9].price=98;
sort(item+1,item+NumberOfItems+1,cmp);
number = 1;
while(capacity>0&&number<=NumberOfItems)
{
if(item[number].weight<=capacity)
{
result+=item[number].price;
capacity-=item[number].weight;
item[number].m=1;
}
else
{
result+=(item[number].price)*(capacity/item[number].weight);
item[number].m=(capacity/item[number].weight);
capacity=0;
}
++number;
}
cout<<"Total Value = "<<result<<'\n';
cout<<"Total Weight = "<<(double)15-capacity<<'\n';
cout<<"Items Used:\n";
for(int i=1;i<=NumberOfItems;++i)
if(item[i].m)
{
cout<<"We took "<<item[i].m*item[i].weight<<"kg of \""<<item[i].name<<"\" and the value it brought is "<<item[i].price*item[i].m<<"\n";
}
return 0;
}
| |
c456 | int* pointer2(&var);
| |
c457 | #include <iostream>
#include <vector>
#ifdef HAVE_BOOST
#include <boost/multiprecision/cpp_int.hpp>
typedef boost::multiprecision::cpp_int integer;
#else
typedef unsigned int integer;
#endif
auto make_bell_triangle(int n) {
std::vector<std::vector<integer>> bell(n);
for (int i = 0; i < n; ++i)
bell[i].assign(i + 1, 0);
bell[0][0] = 1;
for (int i = 1; i < n; ++i) {
std::vector<integer>& row = bell[i];
std::vector<integer>& prev_row = bell[i - 1];
row[0] = prev_row[i - 1];
for (int j = 1; j <= i; ++j)
row[j] = row[j - 1] + prev_row[j - 1];
}
return bell;
}
int main() {
#ifdef HAVE_BOOST
const int size = 50;
#else
const int size = 15;
#endif
auto bell(make_bell_triangle(size));
const int limit = 15;
std::cout << "First " << limit << " Bell numbers:\n";
for (int i = 0; i < limit; ++i)
std::cout << bell[i][0] << '\n';
#ifdef HAVE_BOOST
std::cout << "\n50th Bell number is " << bell[49][0] << "\n\n";
#endif
std::cout << "First 10 rows of the Bell triangle:\n";
for (int i = 0; i < 10; ++i) {
std::cout << bell[i][0];
for (int j = 1; j <= i; ++j)
std::cout << ' ' << bell[i][j];
std::cout << '\n';
}
return 0;
}
| |
c458 | #include <iostream>
bool gapful(int n) {
int m = n;
while (m >= 10)
m /= 10;
return n % ((n % 10) + 10 * (m % 10)) == 0;
}
void show_gapful_numbers(int n, int count) {
std::cout << "First " << count << " gapful numbers >= " << n << ":\n";
for (int i = 0; i < count; ++n) {
if (gapful(n)) {
if (i != 0)
std::cout << ", ";
std::cout << n;
++i;
}
}
std::cout << '\n';
}
int main() {
show_gapful_numbers(100, 30);
show_gapful_numbers(1000000, 15);
show_gapful_numbers(1000000000, 10);
return 0;
}
| |
c459 | #include <sstream>
using namespace std;
bool isNumeric( const char* pszInput, int nNumberBase )
{
istringstream iss( pszInput );
if ( nNumberBase == 10 )
{
double dTestSink;
iss >> dTestSink;
}
else if ( nNumberBase == 8 || nNumberBase == 16 )
{
int nTestSink;
iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink;
}
else
return false;
if ( ! iss )
return false;
return ( iss.rdbuf()->in_avail() == 0 );
}
| |
c460 | #include <windows.h>
#include <sstream>
#include <ctime>
const float PI = 3.1415926536f, TWO_PI = 2.f * PI;
class vector2
{
public:
vector2( float a = 0, float b = 0 ) { set( a, b ); }
void set( float a, float b ) { x = a; y = b; }
void rotate( float r ) {
float _x = x, _y = y,
s = sinf( r ), c = cosf( r ),
a = _x * c - _y * s, b = _x * s + _y * c;
x = a; y = b;
}
vector2 add( const vector2& v ) {
x += v.x; y += v.y;
return *this;
}
float x, y;
};
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap(){
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h ){
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ){
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ){
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ){
clr = c; createPen();
}
void setPenWidth( int w ){
wid = w; createPen();
}
void saveBitmap( std::string path ){
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen(){
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
myBitmap bmp;
bmp.create( 600, 600 ); bmp.clear();
HDC dc = bmp.getDC();
float fs = ( TWO_PI ) / 100.f;
int index = 0;
std::string a = "f:
float ang, len;
vector2 p1, p2;
for( float step = 0.1f; step < 5.1f; step += .05f ) {
ang = 0; len = 2;
p1.set( 300, 300 );
bmp.setPenColor( RGB( rand() % 50 + 200, rand() % 300 + 220, rand() % 50 + 200 ) );
for( float xx = 0; xx < TWO_PI; xx += fs ) {
MoveToEx( dc, (int)p1.x, (int)p1.y, NULL );
p2.set( 0, len ); p2.rotate( ang ); p2.add( p1 );
LineTo( dc, (int)p2.x, (int)p2.y );
p1 = p2; ang += step; len += step;
}
std::ostringstream ss; ss << index++;
b = a + ss.str() + ".bmp";
bmp.saveBitmap( b );
bmp.clear();
}
return 0;
}
| |
c461 | #include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
std::string word;
while (is >> word)
{
*dest = word;
}
}
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
std::string line;
while (std::getline(is, line))
{
*dest = line;
}
}
int main()
{
read_words(std::cin,
std::ostream_iterator<std::string>(std::cout, " "));
std::vector<std::string> v;
read_lines(std::cin, std::back_inserter(v));
return 0;
}
| |
c462 | #include <fstream>
#include <iterator>
#include <boost/regex.hpp>
#include <string>
#include <iostream>
int main( int argc , char *argv[ ] ) {
boost::regex to_be_replaced( "Goodbye London\\s*!" ) ;
std::string replacement( "Hello New York!" ) ;
for ( int i = 1 ; i < argc ; i++ ) {
std::ifstream infile ( argv[ i ] ) ;
if ( infile ) {
std::string filetext( (std::istreambuf_iterator<char>( infile )) ,
std::istreambuf_iterator<char>( ) ) ;
std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ;
infile.close( ) ;
std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ;
if ( outfile.is_open( ) ) {
outfile << changed ;
outfile.close( ) ;
}
}
else
std::cout << "Can't find file " << argv[ i ] << " !\n" ;
}
return 0 ;
}
| |
c463 | #include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
std::ostream& operator<<(std::ostream& os, const std::string& s) {
return os << s.c_str();
}
std::string linearCombo(const std::vector<int>& c) {
std::stringstream ss;
for (size_t i = 0; i < c.size(); i++) {
int n = c[i];
if (n < 0) {
if (ss.tellp() == 0) {
ss << '-';
} else {
ss << " - ";
}
} else if (n > 0) {
if (ss.tellp() != 0) {
ss << " + ";
}
} else {
continue;
}
int av = abs(n);
if (av != 1) {
ss << av << '*';
}
ss << "e(" << i + 1 << ')';
}
if (ss.tellp() == 0) {
return "0";
}
return ss.str();
}
int main() {
using namespace std;
vector<vector<int>> combos{
{1, 2, 3},
{0, 1, 2, 3},
{1, 0, 3, 4},
{1, 2, 0},
{0, 0, 0},
{0},
{1, 1, 1},
{-1, -1, -1},
{-1, -2, 0, -3},
{-1},
};
for (auto& c : combos) {
stringstream ss;
ss << c;
cout << setw(15) << ss.str() << " -> ";
cout << linearCombo(c) << '\n';
}
return 0;
}
| |
c464 | #include <complex>
#include <iostream>
#include <valarray>
const double PI = 3.141592653589793238460;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
void fft(CArray& x)
{
const size_t N = x.size();
if (N <= 1) return;
CArray even = x[std::slice(0, N/2, 2)];
CArray odd = x[std::slice(1, N/2, 2)];
fft(even);
fft(odd);
for (size_t k = 0; k < N/2; ++k)
{
Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
x[k ] = even[k] + t;
x[k+N/2] = even[k] - t;
}
}
void fft(CArray &x)
{
unsigned int N = x.size(), k = N, n;
double thetaT = 3.14159265358979323846264338328L / N;
Complex phiT = Complex(cos(thetaT), -sin(thetaT)), T;
while (k > 1)
{
n = k;
k >>= 1;
phiT = phiT * phiT;
T = 1.0L;
for (unsigned int l = 0; l < k; l++)
{
for (unsigned int a = l; a < N; a += n)
{
unsigned int b = a + k;
Complex t = x[a] - x[b];
x[a] += x[b];
x[b] = t * T;
}
T *= phiT;
}
}
unsigned int m = (unsigned int)log2(N);
for (unsigned int a = 0; a < N; a++)
{
unsigned int b = a;
b = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1));
b = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2));
b = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4));
b = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8));
b = ((b >> 16) | (b << 16)) >> (32 - m);
if (b > a)
{
Complex t = x[a];
x[a] = x[b];
x[b] = t;
}
}
}
void ifft(CArray& x)
{
x = x.apply(std::conj);
fft( x );
x = x.apply(std::conj);
x /= x.size();
}
int main()
{
const Complex test[] = { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0 };
CArray data(test, 8);
fft(data);
std::cout << "fft" << std::endl;
for (int i = 0; i < 8; ++i)
{
std::cout << data[i] << std::endl;
}
ifft(data);
std::cout << std::endl << "ifft" << std::endl;
for (int i = 0; i < 8; ++i)
{
std::cout << data[i] << std::endl;
}
return 0;
}
| |
c465 | #include <iostream>
#include <vector>
int main() {
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(1);
a.push_back(3);
a.push_back(2);
std::vector<int> b;
b.push_back(1);
b.push_back(2);
b.push_back(0);
b.push_back(4);
b.push_back(4);
b.push_back(0);
b.push_back(0);
b.push_back(0);
std::cout << std::boolalpha << (a < b) << std::endl;
return 0;
}
| |
c466 |
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
#include <iostream>
#include <vector>
typedef boost::rational<boost::multiprecision::int1024_t> rational;
rational bernoulli(size_t n) {
auto out = std::vector<rational>();
for (size_t m = 0; m <= n; m++) {
out.emplace_back(1, (m + 1));
for (size_t j = m; j >= 1; j--) {
out[j - 1] = rational(j) * (out[j - 1] - out[j]);
}
}
return out[0];
}
int main() {
for (size_t n = 0; n <= 60; n += n >= 2 ? 2 : 1) {
auto b = bernoulli(n);
std::cout << "B(" << std::right << std::setw(2) << n << ") = ";
std::cout << std::right << std::setw(44) << b.numerator();
std::cout << " / " << b.denominator() << std::endl;
}
return 0;
}
| |
c467 | #include <vector>
#include <iostream>
#include <stdexcept>
using namespace std;
typedef std::pair<double, double> TriPoint;
inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3)
{
return +p1.first*(p2.second-p3.second)
+p2.first*(p3.second-p1.second)
+p3.first*(p1.second-p2.second);
}
void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed)
{
double detTri = Det2D(p1, p2, p3);
if(detTri < 0.0)
{
if (allowReversed)
{
TriPoint a = p3;
p3 = p2;
p2 = a;
}
else throw std::runtime_error("triangle has wrong winding direction");
}
}
bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)
{
return Det2D(p1, p2, p3) < eps;
}
bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)
{
return Det2D(p1, p2, p3) <= eps;
}
bool TriTri2D(TriPoint *t1,
TriPoint *t2,
double eps = 0.0, bool allowReversed = false, bool onBoundary = true)
{
CheckTriWinding(t1[0], t1[1], t1[2], allowReversed);
CheckTriWinding(t2[0], t2[1], t2[2], allowReversed);
bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL;
if(onBoundary)
chkEdge = BoundaryCollideChk;
else
chkEdge = BoundaryDoesntCollideChk;
for(int i=0; i<3; i++)
{
int j=(i+1)%3;
if (chkEdge(t1[i], t1[j], t2[0], eps) &&
chkEdge(t1[i], t1[j], t2[1], eps) &&
chkEdge(t1[i], t1[j], t2[2], eps))
return false;
}
for(int i=0; i<3; i++)
{
int j=(i+1)%3;
if (chkEdge(t2[i], t2[j], t1[0], eps) &&
chkEdge(t2[i], t2[j], t1[1], eps) &&
chkEdge(t2[i], t2[j], t1[2], eps))
return false;
}
return true;
}
int main()
{
{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};
TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)};
cout << TriTri2D(t1, t2) << "," << true << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};
TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};
cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};
TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)};
cout << TriTri2D(t1, t2) << "," << false << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)};
TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)};
cout << TriTri2D(t1, t2) << "," << true << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};
TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)};
cout << TriTri2D(t1, t2) << "," << false << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};
TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)};
cout << TriTri2D(t1, t2) << "," << false << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};
TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};
cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};
TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};
cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;}
}
| |
c468 | #include <afx.h>
| |
c469 | #include <iostream>
#include <random>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cmath>
void printStars ( int number ) {
if ( number > 0 ) {
for ( int i = 0 ; i < number + 1 ; i++ )
std::cout << '*' ;
}
std::cout << '\n' ;
}
int main( int argc , char *argv[] ) {
const int numberOfRandoms = std::atoi( argv[1] ) ;
std::random_device rd ;
std::mt19937 gen( rd( ) ) ;
std::uniform_real_distribution<> distri( 0.0 , 1.0 ) ;
std::vector<double> randoms ;
for ( int i = 0 ; i < numberOfRandoms + 1 ; i++ )
randoms.push_back ( distri( gen ) ) ;
std::sort ( randoms.begin( ) , randoms.end( ) ) ;
double start = 0.0 ;
for ( int i = 0 ; i < 9 ; i++ ) {
double to = start + 0.1 ;
int howmany = std::count_if ( randoms.begin( ) , randoms.end( ),
[&start , &to] ( double c ) { return c >= start
&& c < to ; } ) ;
if ( start == 0.0 )
std::cout << "0.0" << " - " << to << ": " ;
else
std::cout << start << " - " << to << ": " ;
if ( howmany > 50 )
howmany = howmany / ( howmany / 50 ) ;
printStars ( howmany ) ;
start += 0.1 ;
}
double mean = std::accumulate( randoms.begin( ) , randoms.end( ) , 0.0 ) / randoms.size( ) ;
double sum = 0.0 ;
for ( double num : randoms )
sum += std::pow( num - mean , 2 ) ;
double stddev = std::pow( sum / randoms.size( ) , 0.5 ) ;
std::cout << "The mean is " << mean << " !" << std::endl ;
std::cout << "Standard deviation is " << stddev << " !" << std::endl ;
return 0 ;
}
| |
c470 | #include <algorithm>
#include <iostream>
#include <vector>
std::vector<uint64_t> primes;
std::vector<uint64_t> smallPrimes;
template <typename T>
std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
for (; it != end; it = std::next(it)) {
os << ", " << *it;
}
return os << ']';
}
bool isPrime(uint64_t value) {
if (value < 2) return false;
if (value % 2 == 0) return value == 2;
if (value % 3 == 0) return value == 3;
if (value % 5 == 0) return value == 5;
if (value % 7 == 0) return value == 7;
if (value % 11 == 0) return value == 11;
if (value % 13 == 0) return value == 13;
if (value % 17 == 0) return value == 17;
if (value % 19 == 0) return value == 19;
if (value % 23 == 0) return value == 23;
uint64_t t = 29;
while (t * t < value) {
if (value % t == 0) return false;
value += 2;
if (value % t == 0) return false;
value += 4;
}
return true;
}
void init() {
primes.push_back(2);
smallPrimes.push_back(2);
uint64_t i = 3;
while (i <= 521) {
if (isPrime(i)) {
primes.push_back(i);
if (i <= 29) {
smallPrimes.push_back(i);
}
}
i += 2;
}
}
std::vector<uint64_t> nSmooth(uint64_t n, size_t size) {
if (n < 2 || n>521) {
throw std::runtime_error("n must be between 2 and 521");
}
if (size <= 1) {
throw std::runtime_error("size must be at least 1");
}
uint64_t bn = n;
if (primes.cend() == std::find(primes.cbegin(), primes.cend(), bn)) {
throw std::runtime_error("n must be a prime number");
}
std::vector<uint64_t> ns(size, 0);
ns[0] = 1;
std::vector<uint64_t> next;
for (auto prime : primes) {
if (prime > bn) {
break;
}
next.push_back(prime);
}
std::vector<size_t> indicies(next.size(), 0);
for (size_t m = 1; m < size; m++) {
ns[m] = *std::min_element(next.cbegin(), next.cend());
for (size_t i = 0; i < indicies.size(); i++) {
if (ns[m] == next[i]) {
indicies[i]++;
next[i] = primes[i] * ns[indicies[i]];
}
}
}
return ns;
}
int main() {
init();
for (auto i : smallPrimes) {
std::cout << "The first " << i << "-smooth numbers are:\n";
std::cout << nSmooth(i, 25) << '\n';
std::cout << '\n';
}
for (size_t i = 0; i < smallPrimes.size(); i++) {
if (i < 1) continue;
auto p = smallPrimes[i];
auto v = nSmooth(p, 3002);
v.erase(v.begin(), v.begin() + 2999);
std::cout << "The 30,000th to 30,019th " << p << "-smooth numbers are:\n";
std::cout << v << '\n';
std::cout << '\n';
}
return 0;
}
| |
c471 | #include <string>
#include <regex>
#include <algorithm>
#include <numeric>
#include <sstream>
bool CheckFormat(const std::string& isin)
{
std::regex isinRegEpx(R"([A-Z]{2}[A-Z0-9]{9}[0-9])");
std::smatch match;
return std::regex_match(isin, match, isinRegEpx);
}
std::string CodeISIN(const std::string& isin)
{
std::string coded;
int offset = 'A' - 10;
for (auto ch : isin)
{
if (ch >= 'A' && ch <= 'Z')
{
std::stringstream ss;
ss << static_cast<int>(ch) - offset;
coded += ss.str();
}
else
{
coded.push_back(ch);
}
}
return std::move(coded);
}
bool CkeckISIN(const std::string& isin)
{
if (!CheckFormat(isin))
return false;
std::string coded = CodeISIN(isin);
return luhn(coded);
}
#include <iomanip>
#include <iostream>
int main()
{
std::string isins[] = { "US0378331005", "US0373831005", "U50378331005",
"US03378331005", "AU0000XVGZA3", "AU0000VXGZA3",
"FR0000988040" };
for (const auto& isin : isins)
{
std::cout << isin << std::boolalpha << " - " << CkeckISIN(isin) <<std::endl;
}
return 0;
}
| |
c472 | #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
| |
c473 | #include <iostream>
#include <cmath>
#ifdef M_E
static double euler_e = M_E;
#else
static double euler_e = std::exp(1);
#endif
#ifdef M_PI
static double pi = M_PI;
#else
static double pi = std::acos(-1);
#endif
int main()
{
std::cout << "e = " << euler_e
<< "\npi = " << pi
<< "\nsqrt(2) = " << std::sqrt(2.0)
<< "\nln(e) = " << std::log(euler_e)
<< "\nlg(100) = " << std::log10(100.0)
<< "\nexp(3) = " << std::exp(3.0)
<< "\n|-4.5| = " << std::abs(-4.5)
<< "\nfloor(4.5) = " << std::floor(4.5)
<< "\nceiling(4.5) = " << std::ceil(4.5)
<< "\npi^2 = " << std::pow(pi,2.0) << std::endl;
}
| |
c474 | #include <algorithm>
#include <vector>
#include <iostream>
#include <string>
typedef unsigned char byte;
class world {
public:
world( int x, int y ) : _wid( x ), _hei( y ) {
int s = _wid * _hei * sizeof( byte );
_cells = new byte[s];
memset( _cells, 0, s );
}
~world() {
delete [] _cells;
}
int wid() const {
return _wid;
}
int hei() const {
return _hei;
}
byte at( int x, int y ) const {
return _cells[x + y * _wid];
}
void set( int x, int y, byte c ) {
_cells[x + y * _wid] = c;
}
void swap( world* w ) {
memcpy( _cells, w->_cells, _wid * _hei * sizeof( byte ) );
}
private:
int _wid, _hei;
byte* _cells;
};
class rule {
public:
rule( world* w ) : wrd( w ) {
wid = wrd->wid();
hei = wrd->hei();
wrdT = new world( wid, hei );
}
~rule() {
if( wrdT ) delete wrdT;
}
bool hasLivingCells() {
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( wrd->at( x, y ) ) return true;
std::cout << "*** All cells are dead!!! ***\n\n";
return false;
}
void swapWrds() {
wrd->swap( wrdT );
}
void setRuleB( std::vector<int>& birth ) {
_birth = birth;
}
void setRuleS( std::vector<int>& stay ) {
_stay = stay;
}
void applyRules() {
int n;
for( int y = 0; y < hei; y++ ) {
for( int x = 0; x < wid; x++ ) {
n = neighbours( x, y );
if( wrd->at( x, y ) ) {
wrdT->set( x, y, inStay( n ) ? 1 : 0 );
} else {
wrdT->set( x, y, inBirth( n ) ? 1 : 0 );
}
}
}
}
private:
int neighbours( int xx, int yy ) {
int n = 0, nx, ny;
for( int y = -1; y < 2; y++ ) {
for( int x = -1; x < 2; x++ ) {
if( !x && !y ) continue;
nx = ( wid + xx + x ) % wid;
ny = ( hei + yy + y ) % hei;
n += wrd->at( nx, ny ) > 0 ? 1 : 0;
}
}
return n;
}
bool inStay( int n ) {
return( _stay.end() != find( _stay.begin(), _stay.end(), n ) );
}
bool inBirth( int n ) {
return( _birth.end() != find( _birth.begin(), _birth.end(), n ) );
}
int wid, hei;
world *wrd, *wrdT;
std::vector<int> _stay, _birth;
};
class cellular {
public:
cellular( int w, int h ) : rl( 0 ) {
wrd = new world( w, h );
}
~cellular() {
if( rl ) delete rl;
delete wrd;
}
void start( int r ) {
rl = new rule( wrd );
gen = 1;
std::vector<int> t;
switch( r ) {
case 1:
t.push_back( 2 ); t.push_back( 3 ); rl->setRuleS( t );
t.clear(); t.push_back( 3 ); rl->setRuleB( t );
break;
case 2:
t.push_back( 1 ); t.push_back( 3 ); t.push_back( 5 ); t.push_back( 8 ); rl->setRuleS( t );
t.clear(); t.push_back( 3 ); t.push_back( 5 ); t.push_back( 7 ); rl->setRuleB( t );
break;
case 3:
t.push_back( 3 ); t.push_back( 4 ); rl->setRuleS( t );
rl->setRuleB( t );
break;
case 4:
t.push_back( 1 ); t.push_back( 2 ); t.push_back( 3 ); t.push_back( 4 ); t.push_back( 5 ); rl->setRuleS( t );
t.clear(); t.push_back( 3 ); rl->setRuleB( t );
break;
}
wrd->set( 6, 1, 1 ); wrd->set( 7, 2, 1 );
wrd->set( 5, 3, 1 ); wrd->set( 6, 3, 1 );
wrd->set( 7, 3, 1 );
wrd->set( 1, 3, 1 ); wrd->set( 2, 3, 1 );
wrd->set( 3, 3, 1 );
generation();
}
private:
void display() {
system( "cls" );
int wid = wrd->wid(),
hei = wrd->hei();
std::cout << "+" << std::string( wid, '-' ) << "+\n";
for( int y = 0; y < hei; y++ ) {
std::cout << "|";
for( int x = 0; x < wid; x++ ) {
if( wrd->at( x, y ) ) std::cout << "#";
else std::cout << ".";
}
std::cout << "|\n";
}
std::cout << "+" << std::string( wid, '-' ) << "+\n";
std::cout << "Generation: " << gen << "\n\nPress [RETURN] for the next generation...";
std::cin.get();
}
void generation() {
do {
display();
rl->applyRules();
rl->swapWrds();
gen++;
}
while ( rl->hasLivingCells() );
}
rule* rl;
world* wrd;
int gen;
};
int main( int argc, char* argv[] ) {
cellular c( 20, 12 );
std::cout << "\n\t*** CELLULAR AUTOMATA ***" << "\n\n Which one you want to run?\n\n\n";
std::cout << " [1]\tConway's Life\n [2]\tAmoeba\n [3]\tLife 34\n [4]\tMaze\n\n > ";
int o;
do {
std::cin >> o;
}
while( o < 1 || o > 4 );
std::cin.ignore();
c.start( o );
return system( "pause" );
}
| |
c475 | #include <stdint.h>
#include <string>
#include <memory>
#include <iostream>
#include <deque>
#include <unordered_map>
#include <algorithm>
#include <iterator>
using namespace std;
class LCS {
protected:
class Pair {
public:
uint32_t index1;
uint32_t index2;
shared_ptr<Pair> next;
Pair(uint32_t index1, uint32_t index2, shared_ptr<Pair> next = nullptr)
: index1(index1), index2(index2), next(next) {
}
static shared_ptr<Pair> Reverse(const shared_ptr<Pair> pairs) {
shared_ptr<Pair> head = nullptr;
for (auto next = pairs; next != nullptr; next = next->next)
head = make_shared<Pair>(next->index1, next->index2, head);
return head;
}
};
typedef deque<shared_ptr<Pair>> PAIRS;
typedef deque<uint32_t> THRESHOLD;
typedef deque<uint32_t> INDEXES;
typedef unordered_map<char, INDEXES> CHAR_TO_INDEXES_MAP;
typedef deque<INDEXES*> MATCHES;
uint32_t FindLCS(MATCHES& indexesOf2MatchedByIndex1, shared_ptr<Pair>* pairs) {
auto traceLCS = pairs != nullptr;
PAIRS chains;
THRESHOLD threshold;
uint32_t index1 = 0;
for (const auto& it1 : indexesOf2MatchedByIndex1) {
if (!it1->empty()) {
auto dq2 = *it1;
auto limit = threshold.end();
for (auto it2 = dq2.rbegin(); it2 != dq2.rend(); it2++) {
auto index2 = *it2;
limit = lower_bound(threshold.begin(), limit, index2);
auto index3 = distance(threshold.begin(), limit);
auto preferNextIndex2 = next(it2) != dq2.rend() &&
(limit == threshold.begin() || *prev(limit) < *next(it2));
if (preferNextIndex2) continue;
if (limit == threshold.end()) {
threshold.push_back(index2);
limit = prev(threshold.end());
if (traceLCS) {
auto prefix = index3 > 0 ? chains[index3 - 1] : nullptr;
auto last = make_shared<Pair>(index1, index2, prefix);
chains.push_back(last);
}
}
else if (index2 < *limit) {
*limit = index2;
if (traceLCS) {
auto prefix = index3 > 0 ? chains[index3 - 1] : nullptr;
auto last = make_shared<Pair>(index1, index2, prefix);
chains[index3] = last;
}
}
}
}
index1++;
}
if (traceLCS) {
auto last = chains.size() > 0 ? chains.back() : nullptr;
*pairs = Pair::Reverse(last);
}
auto length = threshold.size();
return length;
}
void Match(CHAR_TO_INDEXES_MAP& indexesOf2MatchedByChar, MATCHES& indexesOf2MatchedByIndex1,
const string& s1, const string& s2) {
uint32_t index = 0;
for (const auto& it : s2)
indexesOf2MatchedByChar[it].push_back(index++);
for (const auto& it : s1) {
auto& dq2 = indexesOf2MatchedByChar[it];
indexesOf2MatchedByIndex1.push_back(&dq2);
}
}
string Select(shared_ptr<Pair> pairs, uint32_t length,
bool right, const string& s1, const string& s2) {
string buffer;
buffer.reserve(length);
for (auto next = pairs; next != nullptr; next = next->next) {
auto c = right ? s2[next->index2] : s1[next->index1];
buffer.push_back(c);
}
return buffer;
}
public:
string Correspondence(const string& s1, const string& s2) {
CHAR_TO_INDEXES_MAP indexesOf2MatchedByChar;
MATCHES indexesOf2MatchedByIndex1;
Match(indexesOf2MatchedByChar, indexesOf2MatchedByIndex1, s1, s2);
shared_ptr<Pair> pairs;
auto length = FindLCS(indexesOf2MatchedByIndex1, &pairs);
return Select(pairs, length, false, s1, s2);
}
};
| |
c476 | #include <iostream>
#include <string>
void all_characters_are_the_same(const std::string& str) {
size_t len = str.length();
std::cout << "input: \"" << str << "\", length: " << len << '\n';
if (len > 0) {
char ch = str[0];
for (size_t i = 1; i < len; ++i) {
if (str[i] != ch) {
std::cout << "Not all characters are the same.\n";
std::cout << "Character '" << str[i]
<< "' (hex " << std::hex << static_cast<unsigned int>(str[i])
<< ") at position " << std::dec << i + 1
<< " is not the same as '" << ch << "'.\n\n";
return;
}
}
}
std::cout << "All characters are the same.\n\n";
}
int main() {
all_characters_are_the_same("");
all_characters_are_the_same(" ");
all_characters_are_the_same("2");
all_characters_are_the_same("333");
all_characters_are_the_same(".55");
all_characters_are_the_same("tttTTT");
all_characters_are_the_same("4444 444k");
return 0;
}
| |
c477 | #include <fstream>
#include <iostream>
#include <numeric>
#include <unistd.h>
#include <vector>
std::vector<size_t> get_cpu_times() {
std::ifstream proc_stat("/proc/stat");
proc_stat.ignore(5, ' ');
std::vector<size_t> times;
for (size_t time; proc_stat >> time; times.push_back(time));
return times;
}
bool get_cpu_times(size_t &idle_time, size_t &total_time) {
const std::vector<size_t> cpu_times = get_cpu_times();
if (cpu_times.size() < 4)
return false;
idle_time = cpu_times[3];
total_time = std::accumulate(cpu_times.begin(), cpu_times.end(), 0);
return true;
}
int main(int, char *[]) {
size_t previous_idle_time=0, previous_total_time=0;
for (size_t idle_time, total_time; get_cpu_times(idle_time, total_time); sleep(1)) {
const float idle_time_delta = idle_time - previous_idle_time;
const float total_time_delta = total_time - previous_total_time;
const float utilization = 100.0 * (1.0 - idle_time_delta / total_time_delta);
std::cout << utilization << '%' << std::endl;
previous_idle_time = idle_time;
previous_total_time = total_time;
}
}
| |
c478 | #include <windows.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
cout <<
" ______ ______ " << endl <<
" _____ _____|\\ \\ _____|\\ \\ " << endl <<
" _____\\ \\_ / / | | / / | |" << endl <<
" / /| || |/ /|| |/ /|" << endl <<
" / / /____/|| |\\____/ || |\\____/ |" << endl <<
"| | |____|/ |\\ \\ | / |\\ \\ | / " << endl <<
"| | _____ | \\ \\___|/ | \\ \\___|/ " << endl <<
"|\\ \\|\\ \\ | \\ \\ | \\ \\ " << endl <<
"| \\_____\\| | \\ \\_____\\ \\ \\_____\\ " << endl <<
"| | /____/| \\ | | \\ | | " << endl <<
" \\|_____| || \\|_____| \\|_____| " << endl <<
" |____|/ ";
cout << endl << endl << endl;
system( "pause" );
return 0;
}
| |
c479 | #include <cassert>
#include <cmath>
#include <iostream>
#include <valarray>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns) {
elements_.resize(rows * columns);
}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(value, rows * columns) {}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& at(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[index(row, column)];
}
scalar_type& at(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[index(row, column)];
}
matrix& operator+=(scalar_type e) {
elements_ += e;
return *this;
}
matrix& operator-=(scalar_type e) {
elements_ -= e;
return *this;
}
matrix& operator*=(scalar_type e) {
elements_ *= e;
return *this;
}
matrix& operator/=(scalar_type e) {
elements_ /= e;
return *this;
}
matrix& operator+=(const matrix& other) {
assert(rows_ == other.rows_);
assert(columns_ == other.columns_);
elements_ += other.elements_;
return *this;
}
matrix& operator-=(const matrix& other) {
assert(rows_ == other.rows_);
assert(columns_ == other.columns_);
elements_ -= other.elements_;
return *this;
}
matrix& operator*=(const matrix& other) {
assert(rows_ == other.rows_);
assert(columns_ == other.columns_);
elements_ *= other.elements_;
return *this;
}
matrix& operator/=(const matrix& other) {
assert(rows_ == other.rows_);
assert(columns_ == other.columns_);
elements_ /= other.elements_;
return *this;
}
matrix& negate() {
for (scalar_type& element : elements_)
element = -element;
return *this;
}
matrix& invert() {
for (scalar_type& element : elements_)
element = 1 / element;
return *this;
}
friend matrix pow(const matrix& a, scalar_type b) {
return matrix(a.rows_, a.columns_, std::pow(a.elements_, b));
}
friend matrix pow(const matrix& a, const matrix& b) {
assert(a.rows_ == b.rows_);
assert(a.columns_ == b.columns_);
return matrix(a.rows_, a.columns_, std::pow(a.elements_, b.elements_));
}
private:
matrix(size_t rows, size_t columns, std::valarray<scalar_type>&& values)
: rows_(rows), columns_(columns), elements_(std::move(values)) {}
size_t index(size_t row, size_t column) const {
return row * columns_ + column;
}
size_t rows_;
size_t columns_;
std::valarray<scalar_type> elements_;
};
template <typename scalar_type>
matrix<scalar_type> operator+(const matrix<scalar_type>& a, scalar_type b) {
matrix<scalar_type> c(a);
c += b;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator-(const matrix<scalar_type>& a, scalar_type b) {
matrix<scalar_type> c(a);
c -= b;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator*(const matrix<scalar_type>& a, scalar_type b) {
matrix<scalar_type> c(a);
c *= b;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator/(const matrix<scalar_type>& a, scalar_type b) {
matrix<scalar_type> c(a);
c /= b;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator+(scalar_type a, const matrix<scalar_type>& b) {
matrix<scalar_type> c(b);
c += a;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator-(scalar_type a, const matrix<scalar_type>& b) {
matrix<scalar_type> c(b);
c.negate() += a;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator*(scalar_type a, const matrix<scalar_type>& b) {
matrix<scalar_type> c(b);
c *= a;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator/(scalar_type a, const matrix<scalar_type>& b) {
matrix<scalar_type> c(b);
c.invert() *= a;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator+(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
matrix<scalar_type> c(a);
c += b;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator-(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
matrix<scalar_type> c(a);
c -= b;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator*(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
matrix<scalar_type> c(a);
c *= b;
return c;
}
template <typename scalar_type>
matrix<scalar_type> operator/(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
matrix<scalar_type> c(a);
c /= b;
return c;
}
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& matrix) {
out << '[';
size_t rows = matrix.rows(), columns = matrix.columns();
for (size_t row = 0; row < rows; ++row) {
if (row > 0)
out << ", ";
out << '[';
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ", ";
out << matrix.at(row, column);
}
out << ']';
}
out << "]\n";
}
void test_matrix_matrix() {
const size_t rows = 3, columns = 2;
matrix<double> a(rows, columns);
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < columns; ++j)
a.at(i, j) = double(columns * i + j + 1);
}
matrix<double> b(a);
std::cout << "a + b:\n";
print(std::cout, a + b);
std::cout << "\na - b:\n";
print(std::cout, a - b);
std::cout << "\na * b:\n";
print(std::cout, a * b);
std::cout << "\na / b:\n";
print(std::cout, a / b);
std::cout << "\npow(a, b):\n";
print(std::cout, pow(a, b));
}
void test_matrix_scalar() {
const size_t rows = 3, columns = 4;
matrix<double> a(rows, columns);
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < columns; ++j)
a.at(i, j) = double(columns * i + j + 1);
}
std::cout << "a + 10:\n";
print(std::cout, a + 10.0);
std::cout << "\na - 10:\n";
print(std::cout, a - 10.0);
std::cout << "\n10 - a:\n";
print(std::cout, 10.0 - a);
std::cout << "\na * 10:\n";
print(std::cout, a * 10.0);
std::cout << "\na / 10:\n";
print(std::cout, a / 10.0);
std::cout << "\npow(a, 0.5):\n";
print(std::cout, pow(a, 0.5));
}
int main() {
test_matrix_matrix();
std::cout << '\n';
test_matrix_scalar();
return 0;
}
| |
c480 | #include <windows.h>
#include <list>
#include <iostream>
using namespace std;
class point
{
public:
int x, y;
point() { x = y = 0; }
point( int a, int b ) { x = a; y = b; }
void set( int a, int b ) { x = a; y = b; }
};
class rndCircle
{
public:
void draw()
{
createPoints();
drawPoints();
}
private:
void createPoints()
{
point pt;
for( int x = 0; x < 200; x++ )
{
int a, b, c;
while( true )
{
a = rand() % 31 - 15;
b = rand() % 31 - 15;
c = a * a + b * b;
if( c >= 100 && c <= 225 ) break;
}
pt.set( a, b );
_ptList.push_back( pt );
}
}
void drawPoints()
{
HDC dc = GetDC( GetConsoleWindow() );
for( list<point>::iterator it = _ptList.begin(); it != _ptList.end(); it++ )
SetPixel( dc, 300 + 10 * ( *it ).x, 300 + 10 * ( *it ).y, RGB( 255, 255, 0 ) );
}
list<point> _ptList;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
srand( GetTickCount() );
rndCircle c;
c.draw();
system( "pause" );
return 0;
}
| |
c481 | #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
| |
c482 | #include <vector>
#include <iostream>
#include <cmath>
#include <utility>
#include <map>
#include <iomanip>
bool isPrime( int i ) {
int stop = std::sqrt( static_cast<double>( i ) ) ;
for ( int d = 2 ; d <= stop ; d++ )
if ( i % d == 0 )
return false ;
return true ;
}
class Compare {
public :
Compare( ) {
}
bool operator( ) ( const std::pair<int , int> & a , const std::pair<int, int> & b ) {
if ( a.first != b.first )
return a.first < b.first ;
else
return a.second < b.second ;
}
};
int main( ) {
std::vector<int> primes {2} ;
int current = 3 ;
while ( primes.size( ) < 1000000 ) {
if ( isPrime( current ) )
primes.push_back( current ) ;
current += 2 ;
}
Compare myComp ;
std::map<std::pair<int, int>, int , Compare> conspiracy (myComp) ;
for ( int i = 0 ; i < primes.size( ) -1 ; i++ ) {
int a = primes[i] % 10 ;
int b = primes[ i + 1 ] % 10 ;
std::pair<int , int> numbers { a , b} ;
conspiracy[numbers]++ ;
}
std::cout << "1000000 first primes. Transitions prime % 10 → next-prime % 10.\n" ;
for ( auto it = conspiracy.begin( ) ; it != conspiracy.end( ) ; it++ ) {
std::cout << (it->first).first << " -> " << (it->first).second << " count:" ;
int frequency = it->second ;
std::cout << std::right << std::setw( 15 ) << frequency << " frequency: " ;
std::cout.setf(std::ios::fixed, std::ios::floatfield ) ;
std::cout.precision( 2 ) ;
std::cout << (static_cast<double>(frequency) / 1000000.0) * 100 << " %\n" ;
}
return 0 ;
}
| |
c483 | #include <iostream>
using namespace std;
template<class T>
class Generator
{
public:
virtual T operator()() = 0;
};
template<class T, T P>
class PowersGenerator: Generator<T> {};
template<int P>
class PowersGenerator<int, P>: Generator<int>
{
public:
int i;
PowersGenerator() { i = 1; }
virtual int operator()()
{
int o = 1;
for(int j = 0; j < P; ++j) o *= i;
++i;
return o;
}
};
template<class T, class G, class F>
class Filter: Generator<T>
{
public:
G gen;
F filter;
T lastG, lastF;
Filter() { lastG = gen(); lastF = filter(); }
virtual T operator()()
{
while(lastG >= lastF)
{
if(lastG == lastF)
lastG = gen();
lastF = filter();
}
T out = lastG;
lastG = gen();
return out;
}
};
int main()
{
Filter<int, PowersGenerator<int, 2>, PowersGenerator<int, 3>> gen;
for(int i = 0; i < 20; ++i)
gen();
for(int i = 20; i < 30; ++i)
cout << i << ": " << gen() << endl;
}
| |
c484 | #include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlsave.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>
#ifndef LIBXML_TREE_ENABLED
# error libxml was not configured with DOM tree support
#endif
#ifndef LIBXML_OUTPUT_ENABLED
# error libxml was not configured with serialization support
#endif
template <typename F>
class [[nodiscard]] scope_exit
{
public:
constexpr explicit scope_exit(F&& f) :
f_{std::move(f)}
{}
~scope_exit()
{
f_();
}
scope_exit(scope_exit const&) = delete;
scope_exit(scope_exit&&) = delete;
auto operator=(scope_exit const&) -> scope_exit& = delete;
auto operator=(scope_exit&&) -> scope_exit& = delete;
private:
F f_;
};
class libxml_error : public std::runtime_error
{
public:
libxml_error() : libxml_error(std::string{}) {}
explicit libxml_error(std::string message) :
std::runtime_error{make_message_(std::move(message))}
{}
private:
static auto make_message_(std::string message) -> std::string
{
if (auto const last_error = ::xmlGetLastError(); last_error)
{
if (not message.empty())
message += ": ";
message += last_error->message;
}
return message;
}
};
auto add_text(::xmlNode* node, ::xmlChar const* content)
{
auto const text_node = ::xmlNewText(content);
if (not text_node)
throw libxml_error{"failed to create text node"};
if (auto const res = ::xmlAddChild(node, text_node); not res)
{
::xmlFreeNode(text_node);
throw libxml_error{"failed to add text node"};
}
return text_node;
}
auto main() -> int
{
constexpr auto no_xml_declaration = false;
try
{
::xmlInitParser();
LIBXML_TEST_VERSION
auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};
auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8"1.0"));
if (not doc)
throw libxml_error{"failed to create document"};
auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};
auto root = ::xmlNewNode(nullptr,
reinterpret_cast<::xmlChar const*>(u8"root"));
if (not root)
throw libxml_error{"failed to create root element"};
::xmlDocSetRootElement(doc, root);
add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n "));
if (auto const res = ::xmlNewTextChild(root, nullptr,
reinterpret_cast<::xmlChar const*>(u8"element"),
reinterpret_cast<::xmlChar const*>(
u8"\n Some text here\n "));
not res)
throw libxml_error{"failed to create child text element"};
add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n"));
if constexpr (no_xml_declaration)
{
auto const save_context = ::xmlSaveToFilename("-", nullptr,
XML_SAVE_NO_DECL);
auto const save_context_cleanup = scope_exit{[save_context] {
::xmlSaveClose(save_context); }};
if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)
throw libxml_error{"failed to write tree to stdout"};
}
else
{
if (auto const res = ::xmlSaveFile("-", doc); res == -1)
throw libxml_error{"failed to write tree to stdout"};
}
}
catch (std::exception const& x)
{
std::cerr << "ERROR: " << x.what() << '\n';
return EXIT_FAILURE;
}
}
| |
c485 | #include <iostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& c) {
auto it = c.cbegin();
auto end = c.cend();
out << '[';
if (it != end) {
out << *it;
it = std::next(it);
}
while (it != end) {
out << ", " << *it;
it = std::next(it);
}
return out << ']';
}
void fourDim() {
using namespace std;
vector<vector<vector<vector<int>>>> arr;
int cnt = 0;
arr.push_back(vector<vector<vector<int>>>{});
arr[0].push_back(vector<vector<int>>{});
arr[0][0].push_back(vector<int>{});
arr[0][0][0].push_back(cnt++);
arr[0][0][0].push_back(cnt++);
arr[0][0][0].push_back(cnt++);
arr[0][0][0].push_back(cnt++);
arr[0].push_back(vector<vector<int>>{});
arr[0][1].push_back(vector<int>{});
arr[0][1][0].push_back(cnt++);
arr[0][1][0].push_back(cnt++);
arr[0][1][0].push_back(cnt++);
arr[0][1][0].push_back(cnt++);
arr[0][1].push_back(vector<int>{});
arr[0][1][1].push_back(cnt++);
arr[0][1][1].push_back(cnt++);
arr[0][1][1].push_back(cnt++);
arr[0][1][1].push_back(cnt++);
arr.push_back(vector<vector<vector<int>>>{});
arr[1].push_back(vector<vector<int>>{});
arr[1][0].push_back(vector<int>{});
arr[1][0][0].push_back(cnt++);
arr[1][0][0].push_back(cnt++);
arr[1][0][0].push_back(cnt++);
arr[1][0][0].push_back(cnt++);
cout << arr << '\n';
}
int main() {
fourDim();
return 0;
}
| |
c486 | #include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns,
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>
matrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
size_t arows = a.rows();
size_t acolumns = a.columns();
size_t brows = b.rows();
size_t bcolumns = b.columns();
matrix<scalar_type> c(arows * brows, acolumns * bcolumns);
for (size_t i = 0; i < arows; ++i)
for (size_t j = 0; j < acolumns; ++j)
for (size_t k = 0; k < brows; ++k)
for (size_t l = 0; l < bcolumns; ++l)
c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);
return c;
}
template <typename scalar_type>
void print(std::wostream& out, const matrix<scalar_type>& a) {
const wchar_t* box_top_left = L"\x250c";
const wchar_t* box_top_right = L"\x2510";
const wchar_t* box_bottom_left = L"\x2514";
const wchar_t* box_bottom_right = L"\x2518";
const wchar_t* box_vertical = L"\x2502";
const wchar_t nl = L'\n';
const wchar_t space = L' ';
const int width = 2;
size_t rows = a.rows(), columns = a.columns();
std::wstring spaces((width + 1) * columns, space);
out << box_top_left << spaces << box_top_right << nl;
for (size_t row = 0; row < rows; ++row) {
out << box_vertical;
for (size_t column = 0; column < columns; ++column)
out << std::setw(width) << a(row, column) << space;
out << box_vertical << nl;
}
out << box_bottom_left << spaces << box_bottom_right << nl;
}
void test1() {
matrix<int> matrix1(2, 2, {{1,2}, {3,4}});
matrix<int> matrix2(2, 2, {{0,5}, {6,7}});
std::wcout << L"Test case 1:\n";
print(std::wcout, kronecker_product(matrix1, matrix2));
}
void test2() {
matrix<int> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});
matrix<int> matrix2(3, 4, {{1,1,1,1}, {1,0,0,1}, {1,1,1,1}});
std::wcout << L"Test case 2:\n";
print(std::wcout, kronecker_product(matrix1, matrix2));
}
int main() {
std::wcout.imbue(std::locale(""));
test1();
test2();
return 0;
}
| |
c487 | #include <iostream>
#include <sstream>
int main(int argc, char *argv[]) {
using namespace std;
#if _WIN32
if (argc != 5) {
cout << "Usage : " << argv[0] << " (type) (id) (source string) (description>)\n";
cout << " Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n";
} else {
stringstream ss;
ss << "EventCreate /t " << argv[1] << " /id " << argv[2] << " /l APPLICATION /so " << argv[3] << " /d \"" << argv[4] << "\"";
system(ss.str().c_str());
}
#else
cout << "Not implemented for *nix, only windows.\n";
#endif
return 0;
}
| |
c488 | #include <random>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
random_device seed;
mt19937 engine(seed());
normal_distribution<double> dist(1.0, 0.5);
auto rnd = bind(dist, engine);
vector<double> v(1000);
generate(v.begin(), v.end(), rnd);
return 0;
}
| |
c489 | #if !defined __ALGORITHMS_H__
#define __ALGORITHMS_H__
namespace rosetta
{
namespace catalanNumbers
{
namespace detail
{
class Factorial
{
public:
unsigned long long operator()(unsigned n)const;
};
class BinomialCoefficient
{
public:
unsigned long long operator()(unsigned n, unsigned k)const;
};
}
class CatalanNumbersDirectFactorial
{
public:
CatalanNumbersDirectFactorial();
unsigned long long operator()(unsigned n)const;
private:
detail::Factorial factorial;
};
class CatalanNumbersDirectBinomialCoefficient
{
public:
CatalanNumbersDirectBinomialCoefficient();
unsigned long long operator()(unsigned n)const;
private:
detail::BinomialCoefficient binomialCoefficient;
};
class CatalanNumbersRecursiveSum
{
public:
CatalanNumbersRecursiveSum();
unsigned long long operator()(unsigned n)const;
};
class CatalanNumbersRecursiveFraction
{
public:
CatalanNumbersRecursiveFraction();
unsigned long long operator()(unsigned n)const;
};
}
}
#endif
| |
c490 | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(size_t limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (size_t i = 4; i < limit; i += 2)
sieve[i] = false;
for (size_t p = 3; ; p += 2) {
size_t q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
size_t inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
void strange_unique_prime_triplets(int limit, bool verbose) {
std::vector<bool> sieve = prime_sieve(limit * 3);
std::vector<int> primes;
for (int p = 3; p < limit; p += 2) {
if (sieve[p])
primes.push_back(p);
}
size_t n = primes.size();
size_t count = 0;
if (verbose)
std::cout << "Strange unique prime triplets < " << limit << ":\n";
for (size_t i = 0; i + 2 < n; ++i) {
for (size_t j = i + 1; j + 1 < n; ++j) {
for (size_t k = j + 1; k < n; ++k) {
int sum = primes[i] + primes[j] + primes[k];
if (sieve[sum]) {
++count;
if (verbose) {
std::cout << std::setw(2) << primes[i] << " + "
<< std::setw(2) << primes[j] << " + "
<< std::setw(2) << primes[k] << " = " << sum
<< '\n';
}
}
}
}
}
std::cout << "\nCount of strange unique prime triplets < " << limit
<< " is " << count << ".\n";
}
int main() {
strange_unique_prime_triplets(30, true);
strange_unique_prime_triplets(1000, false);
return 0;
}
| |
c491 | #include <chrono>
#include <iostream>
#include <sstream>
#include <utility>
#include <primesieve.hpp>
#include <gmpxx.h>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
class prime_fibonacci_generator {
public:
prime_fibonacci_generator();
std::pair<uint64_t, big_int> next();
private:
big_int next_fibonacci();
primesieve::iterator p_;
big_int f0_ = 0;
big_int f1_ = 1;
uint64_t n_ = 0;
};
prime_fibonacci_generator::prime_fibonacci_generator() {
for (int i = 0; i < 2; ++i)
p_.next_prime();
}
std::pair<uint64_t, big_int> prime_fibonacci_generator::next() {
for (;;) {
if (n_ > 4) {
uint64_t p = p_.next_prime();
for (; p > n_; ++n_)
next_fibonacci();
}
++n_;
big_int f = next_fibonacci();
if (is_probably_prime(f))
return {n_ - 1, f};
}
}
big_int prime_fibonacci_generator::next_fibonacci() {
big_int result = f0_;
big_int f = f0_ + f1_;
f0_ = f1_;
f1_ = f;
return result;
}
std::string to_string(const big_int& n) {
std::string str = n.get_str();
if (str.size() > 40) {
std::ostringstream os;
os << str.substr(0, 20) << "..." << str.substr(str.size() - 20) << " ("
<< str.size() << " digits)";
return os.str();
}
return str;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
prime_fibonacci_generator gen;
for (int i = 1; i <= 26; ++i) {
auto [n, f] = gen.next();
std::cout << i << ": F(" << n << ") = " << to_string(f) << '\n';
}
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> ms(finish - start);
std::cout << "elapsed time: " << ms.count() << " seconds\n";
}
| |
c492 | #include <iostream>
#include <map>
#include <random>
std::default_random_engine generator;
std::uniform_int_distribution<int> dice(1, 6);
int rollDice() {
return dice(generator);
}
const bool sixesThrowAgain = true;
const std::map<int, int> snl{
{4, 14},
{9, 31},
{17, 7},
{20, 38},
{28, 84},
{40, 59},
{51, 67},
{54, 34},
{62, 19},
{63, 81},
{64, 60},
{71, 91},
{87, 24},
{93, 73},
{95, 75},
{99, 78},
};
template <template<class, class, class...> class C, typename K, typename V, typename... Args>
V GetWithDef(const C<K, V, Args...>& m, K const& key, const V & defval) {
typename C<K, V, Args...>::const_iterator it = m.find(key);
if (it == m.end())
return defval;
return it->second;
}
int turn(int player, int square) {
while (true) {
int roll = rollDice();
printf("Player %d, on square %d, rolls a %d", player, square, roll);
if (square + roll > 100) {
printf(" but cannot move.\n");
} else {
square += roll;
printf(" and moves to square %d\n", square);
if (square == 100) return 100;
int next = GetWithDef(snl, square, square);
if (square < next) {
printf("Yay! Landed on a ladder. Climb up to %d.\n", next);
square = next;
} else if (next < square) {
printf("Oops! landed on a snake. Slither down to %d.\n", next);
square = next;
}
}
if (roll < 6 || !sixesThrowAgain)return square;
printf("Rolled a 6 so roll again.\n");
}
}
int main() {
int players[] = { 1, 1, 1 };
while (true) {
for (int i = 0; i < sizeof(players) / sizeof(int); ++i) {
int ns = turn(i + 1, players[i]);
if (ns == 100) {
printf("Player %d wins!\n", i + 1);
goto out;
}
players[i] = ns;
printf("\n");
}
}
out:
return 0;
}
| |
c493 | #include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
const char logfilename[] = "mlijobs.txt";
std::ifstream logfile(logfilename);
if (!logfile.is_open())
{
std::cerr << "Error opening: " << logfilename << "\n";
return -1;
}
int license = 0, max_license = 0;
std::vector<std::string> max_timestamp;
for (std::string logline; std::getline(logfile, logline); )
{
std::string action(logline.substr(8,3));
if (action == "OUT")
{
if (++license >= max_license)
{
if (license > max_license)
{
max_license = license;
max_timestamp.clear();
}
max_timestamp.push_back(logline.substr(14, 19));
}
}
else if (action == "IN ")
{
--license;
}
}
std::cout << "License count at log end: " << license
<< "\nMaximum simultaneous license: " << max_license
<< "\nMaximum license time(s):\n";
std::copy(max_timestamp.begin(), max_timestamp.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
| |
c494 | #include <sstream>
const int TABLE[][10] = {
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
};
using std::string;
bool damm(string s) {
int interim = 0;
for (char c : s) {
interim = TABLE[interim][c - '0'];
}
return interim == 0;
}
int main() {
auto numbers = { 5724, 5727, 112946, 112949 };
for (int num : numbers) {
using std::stringstream;
stringstream ss;
ss << num;
bool isValid = damm(ss.str());
if (isValid) {
printf("%6d is valid\n", num);
} else {
printf("%6d is invalid\n", num);
}
}
return 0;
}
| |
c495 |
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class unsigned_lah_numbers {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, integer> cache_;
};
integer unsigned_lah_numbers::get(int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n)
return 0;
auto p = std::make_pair(n, k);
auto i = cache_.find(p);
if (i != cache_.end())
return i->second;
integer result = (n - 1 + k) * get(n - 1, k) + get(n - 1, k - 1);
cache_.emplace(p, result);
return result;
}
void print_lah_numbers(unsigned_lah_numbers& uln, int n) {
std::cout << "Unsigned Lah numbers up to L(12,12):\nn/k";
for (int j = 1; j <= n; ++j)
std::cout << std::setw(11) << j;
std::cout << '\n';
for (int i = 1; i <= n; ++i) {
std::cout << std::setw(2) << i << ' ';
for (int j = 1; j <= i; ++j)
std::cout << std::setw(11) << uln.get(i, j);
std::cout << '\n';
}
}
int main() {
unsigned_lah_numbers uln;
print_lah_numbers(uln, 12);
std::cout << "Maximum value of L(n,k) where n == 100:\n";
integer max = 0;
for (int k = 0; k <= 100; ++k)
max = std::max(max, uln.get(100, k));
std::cout << max << '\n';
return 0;
}
| |
c496 | #include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class hSolver
{
public:
hSolver()
{
dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1;
dy[0] = -1; dy[1] = -1; dy[2] = -1; dy[3] = 0; dy[4] = 0; dy[5] = 1; dy[6] = 1; dy[7] = 1;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = 0;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
weHave = new bool[len + 1]; memset( weHave, 0, len + 1 );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
if( arr[c].val > 0 ) weHave[arr[c].val] = true;
if( max < arr[c].val ) max = arr[c].val;
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
delete [] weHave;
}
private:
bool search( int x, int y, int w )
{
if( w == max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
if( weHave[w] )
{
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << d ) )
{
int a = x + dx[d], b = y + dy[d];
if( arr[a + b * wid].val == w )
if( search( a, b, w + 1 ) ) return true;
}
}
return false;
}
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << d ) )
{
int a = x + dx[d], b = y + dy[d];
if( arr[a + b * wid].val == 0 )
{
arr[a + b * wid].val = w;
if( search( a, b, w + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int m = -1, a, b;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( !yy && !xx ) continue;
m++; a = x + xx, b = y + yy;
if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;
if( arr[a + b * wid].val > -1 ) c |= ( 1 << m );
}
return c;
}
void solveIt()
{
int x, y; findStart( x, y );
if( x < 0 ) { cout << "\nCan't find start point!\n"; return; }
search( x, y, 2 );
}
void findStart( int& x, int& y )
{
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val == 1 ) { x = a; y = b; return; }
x = y = -1;
}
int wid, hei, max, dx[8], dy[8];
node* arr;
bool* weHave;
};
int main( int argc, char* argv[] )
{
int wid;
string p = ". 33 35 . . * * * . . 24 22 . * * * . . . 21 . . * * . 26 . 13 40 11 * * 27 . . . 9 . 1 * * * . . 18 . . * * * * * . 7 . . * * * * * * 5 ."; wid = 8;
istringstream iss( p ); vector<string> puzz;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );
hSolver s; s.solve( puzz, wid );
int c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| |
c497 | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
static void printVerse(const std::string& name) {
std::string x = name;
std::transform(x.begin(), x.end(), x.begin(), ::tolower);
x[0] = toupper(x[0]);
std::string y;
switch (x[0]) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
y = x;
std::transform(y.begin(), y.end(), y.begin(), ::tolower);
break;
default:
y = x.substr(1);
break;
}
std::string b("b" + y);
std::string f("f" + y);
std::string m("m" + y);
switch (x[0]) {
case 'B':
b = y;
break;
case 'F':
f = y;
break;
case 'M':
m = y;
break;
default:
break;
}
printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str());
printf("Banana-fana fo-%s\n", f.c_str());
printf("Fee-fi-mo-%s\n", m.c_str());
printf("%s!\n\n", x.c_str());
}
int main() {
using namespace std;
vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" };
for (auto& name : nameList) {
printVerse(name);
}
return 0;
}
| |
c498 | #include <algorithm>
#include <complex>
#include <iomanip>
#include <iostream>
std::complex<double> inv(const std::complex<double>& c) {
double denom = c.real() * c.real() + c.imag() * c.imag();
return std::complex<double>(c.real() / denom, -c.imag() / denom);
}
class QuaterImaginary {
public:
QuaterImaginary(const std::string& s) : b2i(s) {
static std::string base("0123.");
if (b2i.empty()
|| std::any_of(s.cbegin(), s.cend(), [](char c) { return base.find(c) == std::string::npos; })
|| std::count(s.cbegin(), s.cend(), '.') > 1) {
throw std::runtime_error("Invalid base 2i number");
}
}
QuaterImaginary& operator=(const QuaterImaginary& q) {
b2i = q.b2i;
return *this;
}
std::complex<double> toComplex() const {
int pointPos = b2i.find('.');
int posLen = (pointPos != std::string::npos) ? pointPos : b2i.length();
std::complex<double> sum(0.0, 0.0);
std::complex<double> prod(1.0, 0.0);
for (int j = 0; j < posLen; j++) {
double k = (b2i[posLen - 1 - j] - '0');
if (k > 0.0) {
sum += prod * k;
}
prod *= twoI;
}
if (pointPos != -1) {
prod = invTwoI;
for (size_t j = posLen + 1; j < b2i.length(); j++) {
double k = (b2i[j] - '0');
if (k > 0.0) {
sum += prod * k;
}
prod *= invTwoI;
}
}
return sum;
}
friend std::ostream& operator<<(std::ostream&, const QuaterImaginary&);
private:
const std::complex<double> twoI{ 0.0, 2.0 };
const std::complex<double> invTwoI = inv(twoI);
std::string b2i;
};
std::ostream& operator<<(std::ostream& os, const QuaterImaginary& q) {
return os << q.b2i;
}
QuaterImaginary toQuaterImaginary(const std::complex<double>& c) {
if (c.real() == 0.0 && c.imag() == 0.0) return QuaterImaginary("0");
int re = (int)c.real();
int im = (int)c.imag();
int fi = -1;
std::stringstream ss;
while (re != 0) {
int rem = re % -4;
re /= -4;
if (rem < 0) {
rem = 4 + rem;
re++;
}
ss << rem << 0;
}
if (im != 0) {
double f = (std::complex<double>(0.0, c.imag()) / std::complex<double>(0.0, 2.0)).real();
im = (int)ceil(f);
f = -4.0 * (f - im);
size_t index = 1;
while (im != 0) {
int rem = im % -4;
im /= -4;
if (rem < 0) {
rem = 4 + rem;
im++;
}
if (index < ss.str().length()) {
ss.str()[index] = (char)(rem + 48);
} else {
ss << 0 << rem;
}
index += 2;
}
fi = (int)f;
}
auto r = ss.str();
std::reverse(r.begin(), r.end());
ss.str("");
ss.clear();
ss << r;
if (fi != -1) ss << '.' << fi;
r = ss.str();
r.erase(r.begin(), std::find_if(r.begin(), r.end(), [](char c) { return c != '0'; }));
if (r[0] == '.')r = "0" + r;
return QuaterImaginary(r);
}
int main() {
using namespace std;
for (int i = 1; i <= 16; i++) {
complex<double> c1(i, 0);
QuaterImaginary qi = toQuaterImaginary(c1);
complex<double> c2 = qi.toComplex();
cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << " ";
c1 = -c1;
qi = toQuaterImaginary(c1);
c2 = qi.toComplex();
cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << endl;
}
cout << endl;
for (int i = 1; i <= 16; i++) {
complex<double> c1(0, i);
QuaterImaginary qi = toQuaterImaginary(c1);
complex<double> c2 = qi.toComplex();
cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << " ";
c1 = -c1;
qi = toQuaterImaginary(c1);
c2 = qi.toComplex();
cout << setw(8) << c1 << " -> " << setw(8) << qi << " -> " << setw(8) << c2 << endl;
}
return 0;
}
| |
c499 |
#include <vector>
#include <iostream>
#include <iomanip>
#include <thread>
#include <future>
static void print(const std::vector<int> &pos)
{
for (int i = 0; i < pos.size(); i++) {
std::cout << std::setw(3) << char('a' + i);
}
std::cout << '\n';
for (int row = 0; row < pos.size(); row++) {
int col = pos[row];
std::cout << row + 1 << std::setw(3 * col + 3) << " # ";
std::cout << '\n';
}
std::cout << "\n\n";
}
static bool threatens(int row_a, int col_a, int row_b, int col_b)
{
return row_a == row_b
or col_a == col_b
or std::abs(row_a - row_b) == std::abs(col_a - col_b);
}
static bool good(const std::vector<int> &pos, int end_idx)
{
for (int row_a = 0; row_a < end_idx; row_a++) {
for (int row_b = row_a + 1; row_b < end_idx; row_b++) {
int col_a = pos[row_a];
int col_b = pos[row_b];
if (threatens(row_a, col_a, row_b, col_b)) {
return false;
}
}
}
return true;
}
static std::mutex print_count_mutex;
static int n_sols = 0;
static void n_queens(std::vector<int> &pos, int index)
{
if (index >= pos.size()) {
if (good(pos, index)) {
std::lock_guard<std::mutex> lock(print_count_mutex);
print(pos);
n_sols++;
}
return;
}
if (not good(pos, index)) {
return;
}
if (index == 0) {
std::vector<std::future<void>> fts;
for (int col = 0; col < pos.size(); col++) {
pos[index] = col;
auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); });
fts.push_back(std::move(ft));
}
for (const auto &ft : fts) {
ft.wait();
}
} else {
for (int col = 0; col < pos.size(); col++) {
pos[index] = col;
n_queens(pos, index + 1);
}
}
}
int main()
{
std::vector<int> start(12);
n_queens(start, 0);
std::cout << n_sols << " solutions found.\n";
return 0;
}
| |
c500 | #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
| |
c501 | #include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
int main()
{
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumbers, myColors};
auto myMap = std::map<int, decltype(myArray)> {{3, myArray}, {7, myArray}};
auto mapCopy = myMap;
mapCopy[3][0][1] = "2";
mapCopy[7][1][2] = "purple";
std::cout << "the original values:\n";
std::cout << myMap[3][0][1] << "\n";
std::cout << myMap[7][1][2] << "\n\n";
std::cout << "the modified copy:\n";
std::cout << mapCopy[3][0][1] << "\n";
std::cout << mapCopy[7][1][2] << "\n";
}
| |
c502 | #include <iostream>
typedef unsigned long long bigInt;
using namespace std;
class m35
{
public:
void doIt( bigInt i )
{
bigInt sum = 0;
for( bigInt a = 1; a < i; a++ )
if( !( a % 3 ) || !( a % 5 ) ) sum += a;
cout << "Sum is " << sum << " for n = " << i << endl << endl;
}
void doIt_b( bigInt i )
{
bigInt sum = 0;
for( bigInt a = 0; a < 28; a++ )
{
if( !( a % 3 ) || !( a % 5 ) )
{
sum += a;
for( bigInt s = 30; s < i; s += 30 )
if( a + s < i ) sum += ( a + s );
}
}
cout << "Sum is " << sum << " for n = " << i << endl << endl;
}
};
int main( int argc, char* argv[] )
{
m35 m; m.doIt( 1000 );
return system( "pause" );
}
| |
c503 | #include <iomanip>
#include <iostream>
#include <tuple>
typedef std::tuple<double,double> coeff_t;
typedef coeff_t (*func_t)(int);
double calc(func_t func, int n)
{
double a, b, temp = 0;
for (; n > 0; --n) {
std::tie(a, b) = func(n);
temp = b / (a + temp);
}
std::tie(a, b) = func(0);
return a + temp;
}
coeff_t sqrt2(int n)
{
return coeff_t(n > 0 ? 2 : 1, 1);
}
coeff_t napier(int n)
{
return coeff_t(n > 0 ? n : 2, n > 1 ? n - 1 : 1);
}
coeff_t pi(int n)
{
return coeff_t(n > 0 ? 6 : 3, (2 * n - 1) * (2 * n - 1));
}
int main()
{
std::streamsize old_prec = std::cout.precision(15);
std::cout
<< calc(sqrt2, 20) << '\n'
<< calc(napier, 15) << '\n'
<< calc(pi, 10000) << '\n'
<< std::setprecision(old_prec);
}
| |
c505 | #include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
double arcLength(double radius, double angle1, double angle2) {
return (360.0 - abs(angle2 - angle1)) * M_PI * radius / 180.0;
}
int main() {
auto al = arcLength(10.0, 10.0, 120.0);
std::cout << "arc length: " << al << '\n';
return 0;
}
| |
c506 | #include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>
#include <sstream>
std::array<std::string, 6> games{ "12", "13", "14", "23", "24", "34" };
std::string results = "000000";
int fromBase3(std::string num) {
int out = 0;
for (auto c : num) {
int d = c - '0';
out = 3 * out + d;
}
return out;
}
std::string toBase3(int num) {
std::stringstream ss;
while (num > 0) {
int rem = num % 3;
num /= 3;
ss << rem;
}
auto str = ss.str();
std::reverse(str.begin(), str.end());
return str;
}
bool nextResult() {
if (results == "222222") {
return false;
}
auto res = fromBase3(results);
std::stringstream ss;
ss << std::setw(6) << std::setfill('0') << toBase3(res + 1);
results = ss.str();
return true;
}
int main() {
std::array<std::array<int, 10>, 4> points;
for (auto &row : points) {
std::fill(row.begin(), row.end(), 0);
}
do {
std::array<int, 4> records {0, 0, 0, 0 };
for (size_t i = 0; i < games.size(); i++) {
switch (results[i]) {
case '2':
records[games[i][0] - '1'] += 3;
break;
case '1':
records[games[i][0] - '1']++;
records[games[i][1] - '1']++;
break;
case '0':
records[games[i][1] - '1'] += 3;
break;
default:
break;
}
}
std::sort(records.begin(), records.end());
for (size_t i = 0; i < records.size(); i++) {
points[i][records[i]]++;
}
} while (nextResult());
std::cout << "POINTS 0 1 2 3 4 5 6 7 8 9\n";
std::cout << "-------------------------------------------------------------\n";
std::array<std::string, 4> places{ "1st", "2nd", "3rd", "4th" };
for (size_t i = 0; i < places.size(); i++) {
std::cout << places[i] << " place";
for (size_t j = 0; j < points[i].size(); j++) {
std::cout << std::setw(5) << points[3 - i][j];
}
std::cout << '\n';
}
return 0;
}
| |
c507 | #include <fstream>
#include <iostream>
#include <set>
#include <string>
int main() {
std::ifstream input("unixdict.txt");
if (input) {
std::set<std::string> words;
std::string word;
size_t count = 0;
while (input >> word) {
std::string drow(word.rbegin(), word.rend());
if (words.find(drow) == words.end()) {
words.insert(word);
} else {
if (count++ < 5)
std::cout << word << ' ' << drow << '\n';
}
}
std::cout << "\nSemordnilap pairs: " << count << '\n';
return 0;
} else
return 1;
}
| |
c508 | #include <boost/iterator/counting_iterator.hpp>
#include <algorithm>
int factorial(int n)
{
return std::accumulate(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n+1), 1, std::multiplies<int>());
}
| |
c509 | include <vector>
#include <algorithm>
#include <string>
#include <iostream>
int main( ) {
std::vector<std::string> myStrings { "prepended to" , "my string" } ;
std::string prepended = std::accumulate( myStrings.begin( ) ,
myStrings.end( ) , std::string( "" ) , []( std::string a ,
std::string b ) { return a + b ; } ) ;
std::cout << prepended << std::endl ;
return 0 ;
}
| |
c510 | #include <iostream>
#include <cstdint>
#include <vector>
#include "prime_sieve.hpp"
using integer = uint32_t;
using vector = std::vector<integer>;
void print_vector(const vector& vec) {
if (!vec.empty()) {
auto i = vec.begin();
std::cout << '(' << *i;
for (++i; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << ')';
}
}
class diffs {
public:
diffs(std::initializer_list<integer> list) : diffs_(list) {}
diffs(const vector& vec) : diffs_(vec) {}
void test_group(const vector&);
size_t size() const {
return diffs_.size();
}
void print(std::ostream&);
private:
vector diffs_;
vector first_;
vector last_;
integer count_ = 0;
};
void diffs::test_group(const vector& vec) {
if (vec.size() < size() + 1)
return;
size_t start = vec.size() - size() - 1;
for (size_t i = 0, j = start + 1; i < size(); ++i, ++j) {
if (vec[j] - vec[j - 1] != diffs_[i])
return;
}
vector group(vec.begin() + start, vec.end());
if (count_ == 0)
first_ = group;
last_ = group;
++count_;
}
void diffs::print(std::ostream& out) {
print_vector(diffs_);
out << ": first group = ";
print_vector(first_);
out << ", last group = ";
print_vector(last_);
out << ", count = " << count_ << '\n';
}
int main() {
const integer limit = 1000000;
const size_t max_group_size = 4;
prime_sieve sieve(limit);
diffs d[] = { {2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2} };
vector group;
for (integer p = 0; p < limit; ++p) {
if (!sieve.is_prime(p))
continue;
if (group.size() >= max_group_size)
group.erase(group.begin());
group.push_back(p);
for (auto&& diff : d) {
diff.test_group(group);
}
}
for (auto&& diff : d) {
diff.print(std::cout);
}
return 0;
}
| |
c511 | #include <iostream>
#include <string>
#include <vector>
void print_menu(const std::vector<std::string>& terms)
{
for (size_t i = 0; i < terms.size(); i++) {
std::cout << i + 1 << ") " << terms[i] << '\n';
}
}
int parse_entry(const std::string& entry, int max_number)
{
int number = std::stoi(entry);
if (number < 1 || number > max_number) {
throw std::invalid_argument("");
}
return number;
}
std::string data_entry(const std::string& prompt, const std::vector<std::string>& terms)
{
if (terms.empty()) {
return "";
}
int choice;
while (true) {
print_menu(terms);
std::cout << prompt;
std::string entry;
std::cin >> entry;
try {
choice = parse_entry(entry, terms.size());
return terms[choice - 1];
} catch (std::invalid_argument&) {
}
}
}
int main()
{
std::vector<std::string> terms = {"fee fie", "huff and puff", "mirror mirror", "tick tock"};
std::cout << "You chose: " << data_entry("> ", terms) << std::endl;
}
| |
c512 |
#include <iostream>
using std::cout;
using std::endl;
#include <boost/array.hpp>
#include <boost/circular_buffer.hpp>
class Subtractive_generator {
private:
static const int param_i = 55;
static const int param_j = 24;
static const int initial_load = 219;
static const int mod = 1e9;
boost::circular_buffer<int> r;
public:
Subtractive_generator(int seed);
int next();
int operator()(){return next();}
};
Subtractive_generator::Subtractive_generator(int seed)
:r(param_i)
{
boost::array<int, param_i> s;
s[0] = seed;
s[1] = 1;
for(int n = 2; n < param_i; ++n){
int t = s[n-2]-s[n-1];
if (t < 0 ) t+= mod;
s[n] = t;
}
for(int n = 0; n < param_i; ++n){
int i = (34 * (n+1)) % param_i;
r.push_back(s[i]);
}
for(int n = param_i; n <= initial_load; ++n) next();
}
int Subtractive_generator::next()
{
int t = r[0]-r[31];
if (t < 0) t += mod;
r.push_back(t);
return r[param_i-1];
}
int main()
{
Subtractive_generator rg(292929);
cout << "result = " << rg() << endl;
cout << "result = " << rg() << endl;
cout << "result = " << rg() << endl;
cout << "result = " << rg() << endl;
cout << "result = " << rg() << endl;
cout << "result = " << rg() << endl;
cout << "result = " << rg() << endl;
return 0;
}
| |
c513 |
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("../include/earthquake.txt");
int count_quake = 0;
int column = 1;
string value;
double size_quake;
string row = "";
while(file >> value)
{
if(column == 3)
{
size_quake = stod(value);
if(size_quake>6.0)
{
count_quake++;
row += value + "\t";
cout << row << endl;
}
column = 1;
row = "";
}
else
{
column++;
row+=value + "\t";
}
}
cout << "\nNumber of quakes greater than 6 is " << count_quake << endl;
return 0;
}
| |
c514 |
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
#include <vector>
struct noncopyable {
noncopyable() {}
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
};
template <typename T>
class tarjan;
template <typename T>
class vertex : private noncopyable {
public:
explicit vertex(const T& t) : data_(t) {}
void add_neighbour(vertex* v) {
neighbours_.push_back(v);
}
void add_neighbours(const std::initializer_list<vertex*>& vs) {
neighbours_.insert(neighbours_.end(), vs);
}
const T& get_data() {
return data_;
}
private:
friend tarjan<T>;
T data_;
int index_ = -1;
int lowlink_ = -1;
bool on_stack_ = false;
std::vector<vertex*> neighbours_;
};
template <typename T>
class graph : private noncopyable {
public:
vertex<T>* add_vertex(const T& t) {
vertexes_.emplace_back(t);
return &vertexes_.back();
}
private:
friend tarjan<T>;
std::list<vertex<T>> vertexes_;
};
template <typename T>
class tarjan : private noncopyable {
public:
using component = std::vector<vertex<T>*>;
std::list<component> run(graph<T>& graph) {
index_ = 0;
stack_.clear();
strongly_connected_.clear();
for (auto& v : graph.vertexes_) {
if (v.index_ == -1)
strongconnect(&v);
}
return strongly_connected_;
}
private:
void strongconnect(vertex<T>* v) {
v->index_ = index_;
v->lowlink_ = index_;
++index_;
stack_.push_back(v);
v->on_stack_ = true;
for (auto w : v->neighbours_) {
if (w->index_ == -1) {
strongconnect(w);
v->lowlink_ = std::min(v->lowlink_, w->lowlink_);
}
else if (w->on_stack_) {
v->lowlink_ = std::min(v->lowlink_, w->index_);
}
}
if (v->lowlink_ == v->index_) {
strongly_connected_.push_back(component());
component& c = strongly_connected_.back();
for (;;) {
auto w = stack_.back();
stack_.pop_back();
w->on_stack_ = false;
c.push_back(w);
if (w == v)
break;
}
}
}
int index_ = 0;
std::list<vertex<T>*> stack_;
std::list<component> strongly_connected_;
};
template <typename T>
void print_vector(const std::vector<vertex<T>*>& vec) {
if (!vec.empty()) {
auto i = vec.begin();
std::cout << (*i)->get_data();
for (++i; i != vec.end(); ++i)
std::cout << ' ' << (*i)->get_data();
}
std::cout << '\n';
}
int main() {
graph<std::string> g;
auto andy = g.add_vertex("Andy");
auto bart = g.add_vertex("Bart");
auto carl = g.add_vertex("Carl");
auto dave = g.add_vertex("Dave");
auto earl = g.add_vertex("Earl");
auto fred = g.add_vertex("Fred");
auto gary = g.add_vertex("Gary");
auto hank = g.add_vertex("Hank");
andy->add_neighbour(bart);
bart->add_neighbour(carl);
carl->add_neighbour(andy);
dave->add_neighbours({bart, carl, earl});
earl->add_neighbours({dave, fred});
fred->add_neighbours({carl, gary});
gary->add_neighbour(fred);
hank->add_neighbours({earl, gary, hank});
tarjan<std::string> t;
for (auto&& s : t.run(g))
print_vector(s);
return 0;
}
| |
c515 | #include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
const double EPSILON = 1.0e-15;
unsigned long long fact = 1;
double e = 2.0, e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
}
while (fabs(e - e0) >= EPSILON);
cout << "e = " << setprecision(16) << e << endl;
return 0;
}
| |
c516 | #include <iostream>
#include <string>
#include <algorithm>
#include <ctime>
const std::string CHR[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
"0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" };
const std::string UNS = "O0l1I5S2Z";
std::string createPW( int len, bool safe ) {
std::string pw;
char t;
for( int x = 0; x < len; x += 4 ) {
for( int y = x; y < x + 4 && y < len; y++ ) {
do {
t = CHR[y % 4].at( rand() % CHR[y % 4].size() );
} while( safe && UNS.find( t ) != UNS.npos );
pw.append( 1, t );
}
}
std::random_shuffle( pw.begin(), pw.end() );
return pw;
}
void generate( int len, int count, bool safe ) {
for( int c = 0; c < count; c++ ) {
std::cout << createPW( len, safe ) << "\n";
}
std::cout << "\n\n";
}
int main( int argc, char* argv[] ){
if( argv[1][1] == '?' || argc < 5 ) {
std::cout << "Syntax: PWGEN length count safe seed /?\n"
"length:\tthe length of the password(min 4)\n"
"count:\thow many passwords should be generated\n"
"safe:\t1 will exclude visually similar characters, 0 won't\n"
"seed:\tnumber to seed the random generator or 0\n"
"/?\tthis text\n\n";
} else {
int l = atoi( argv[1] ),
c = atoi( argv[2] ),
e = atoi( argv[3] ),
s = atoi( argv[4] );
if( l < 4 ) {
std::cout << "Passwords must be at least 4 characters long.\n\n";
} else {
if (s == 0) {
std::srand( time( NULL ) );
} else {
std::srand( unsigned( s ) );
}
generate( l, c, e != 0 );
}
}
return 0;
}
| |
c517 | #include <iostream>
class U0 {};
class U1 {};
void baz(int i)
{
if (!i) throw U0();
else throw U1();
}
void bar(int i) { baz(i); }
void foo()
{
for (int i = 0; i < 2; i++)
{
try {
bar(i);
} catch(U0 e) {
std::cout<< "Exception U0 caught\n";
}
}
}
int main() {
foo();
std::cout<< "Should never get here!\n";
return 0;
}
| |
c518 | #include "Core/Core.h"
using namespace Upp;
CONSOLE_APP_MAIN
{
JsonArray a;
a << Json("name", "John")("phone", "1234567") << Json("name", "Susan")("phone", "654321");
String txt = ~a;
Cout() << txt << '\n';
Value v = ParseJSON(txt);
for(int i = 0; i < v.GetCount(); i++)
Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}
| |
c519 | #include <algorithm>
#include <string>
#include <iostream>
template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
auto i = std::unique(str.begin(), str.end(),
[ch](char_type a, char_type b) { return a == ch && b == ch; });
str.erase(i, str.end());
return str;
}
void test(const std::string& str, char ch) {
std::cout << "character: '" << ch << "'\n";
std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
std::string squeezed(squeeze(str, ch));
std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("", ' ');
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
std::string truman(" --- Harry S Truman ");
test(truman, ' ');
test(truman, '-');
test(truman, 'r');
return 0;
}
| |
c522 | #include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;
int main( ) {
string setA[] = { "John", "Bob" , "Mary", "Serena" };
string setB[] = { "Jim" , "Mary", "John", "Bob" };
set<string>
firstSet( setA , setA + 4 ),
secondSet( setB , setB + 4 ),
symdiff;
set_symmetric_difference( firstSet.begin(), firstSet.end(),
secondSet.begin(), secondSet.end(),
inserter( symdiff, symdiff.end() ) );
copy( symdiff.begin(), symdiff.end(), ostream_iterator<string>( cout , " " ) );
cout << endl;
return 0;
}
| |
c523 | void Line( float x1, float y1, float x2, float y2, const Color& color )
{
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if(steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if(x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 2.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
const int maxX = (int)x2;
for(int x=(int)x1; x<=maxX; x++)
{
if(steep)
{
SetPixel(y,x, color);
}
else
{
SetPixel(x,y, color);
}
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
}
| |
c524 | #include <iostream>
#include <vector>
#include <iterator>
class Hofstadter
{
public:
static int F(int n) {
if ( n == 0 ) return 1;
return n - M(F(n-1));
}
static int M(int n) {
if ( n == 0 ) return 0;
return n - F(M(n-1));
}
};
using namespace std;
int main()
{
int i;
vector<int> ra, rb;
for(i=0; i < 20; i++) {
ra.push_back(Hofstadter::F(i));
rb.push_back(Hofstadter::M(i));
}
copy(ra.begin(), ra.end(),
ostream_iterator<int>(cout, " "));
cout << endl;
copy(rb.begin(), rb.end(),
ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
| |
c525 | #include <iostream>
#include <vector>
class Ham {
private:
std::vector<unsigned int> _H, _hp, _hv, _x;
public:
bool operator!=(const Ham& other) const {return true;}
Ham begin() const {return *this;}
Ham end() const {return *this;}
unsigned int operator*() const {return _x.back();}
Ham(const std::vector<unsigned int> &pfs):_H(pfs),_hp(pfs.size(),0),_hv({pfs}),_x({1}){}
const Ham& operator++() {
for (int i=0; i<_H.size(); i++) for (;_hv[i]<=_x.back();_hv[i]=_x[++_hp[i]]*_H[i]);
_x.push_back(_hv[0]);
for (int i=1; i<_H.size(); i++) if (_hv[i]<_x.back()) _x.back()=_hv[i];
return *this;
}
};
| |
c526 | #include <iostream>
#include <cmath>
#include <optional>
#include <vector>
using namespace std;
template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
if(!monad.has_value())
{
return optional<remove_reference_t<decltype(*f(*monad))>>();
}
return f(*monad);
}
auto Pure(auto t)
{
return optional{t};
}
auto SafeInverse(double v)
{
if (v == 0)
{
return optional<decltype(v)>();
}
else
{
return optional(1/v);
}
}
auto SafeAcos(double v)
{
if(v < -1 || v > 1)
{
return optional<decltype(acos(v))>();
}
else
{
return optional(acos(v));
}
}
template<typename T>
ostream& operator<<(ostream& s, optional<T> v)
{
s << (v ? to_string(*v) : "nothing");
return s;
}
int main()
{
vector<double> tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5};
cout << "x -> acos(1/x) , 1/(acos(x)\n";
for(auto v : tests)
{
auto maybeMonad = Pure(v);
auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos;
auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse;
cout << v << " -> " << inverseAcos << ", " << acosInverse << "\n";
}
}
| |
c527 |
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <iostream>
#include <vector>
#include <math.h>
class Vector;
class Matrix {
public:
Matrix() : m(0), n(0), data(nullptr) {}
Matrix(int m_, int n_) : Matrix() {
m = m_;
n = n_;
allocate(m_,n_);
}
Matrix(const Matrix& mat) : Matrix(mat.m,mat.n) {
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
(*this)(i,j) = mat(i,j);
}
template<int rows, int cols>
Matrix(double (&a)[rows][cols]) : Matrix(rows,cols) {
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
(*this)(i,j) = a[i][j];
}
~Matrix() {
deallocate();
}
double& operator() (int i, int j) {
return data[i+m*j]; }
double operator() (int i, int j) const {
return data[i+m*j]; }
Matrix& operator=(const Matrix& source) {
if (this != &source) {
if ( (m*n) != (source.m * source.n) ) {
allocate(source.m,source.n);
}
std::copy(source.data, source.data + source.m*source.n, data);
}
return *this;
}
void compute_minor(const Matrix& mat, int d) {
allocate(mat.m, mat.n);
for (int i = 0; i < d; i++)
(*this)(i,i) = 1.0;
for (int i = d; i < mat.m; i++)
for (int j = d; j < mat.n; j++)
(*this)(i,j) = mat(i,j);
}
void mult(const Matrix& a, const Matrix& b) {
if (a.n != b.m) {
std::cerr << "Matrix multiplication not possible, sizes don't match !\n";
return;
}
if (a.m != m or b.n != n)
allocate(a.m, b.n);
memset(data,0,m*n*sizeof(double));
for (int i = 0; i < a.m; i++)
for (int j = 0; j < b.n; j++)
for (int k = 0; k < a.n; k++)
(*this)(i,j) += a(i,k) * b(k,j);
}
void transpose() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < i; j++) {
double t = (*this)(i,j);
(*this)(i,j) = (*this)(j,i);
(*this)(j,i) = t;
}
}
}
void extract_column(Vector& v, int c);
void allocate(int m_, int n_) {
deallocate();
m = m_;
n = n_;
data = new double[m_*n_];
memset(data,0,m_*n_*sizeof(double));
}
void deallocate() {
if (data)
delete[] data;
data = nullptr;
}
int m, n;
private:
double* data;
};
class Vector {
public:
Vector() : size(0), data(nullptr) {}
Vector(int size_) : Vector() {
size = size_;
allocate(size_);
}
~Vector() {
deallocate();
}
double& operator() (int i) {
return data[i]; }
double operator() (int i) const {
return data[i]; }
Vector& operator=(const Vector& source) {
if (this != &source) {
if ( size != (source.size) ) {
allocate(source.size);
}
std::copy(source.data, source.data + source.size, data);
}
return *this;
}
void allocate(int size_) {
deallocate();
size = size_;
data = new double[size_];
memset(data,0,size_*sizeof(double));
}
void deallocate() {
if (data)
delete[] data;
data = nullptr;
}
double norm() {
double sum = 0;
for (int i = 0; i < size; i++) sum += (*this)(i) * (*this)(i);
return sqrt(sum);
}
void rescale(double factor) {
for (int i = 0; i < size; i++) (*this)(i) /= factor;
}
void rescale_unit() {
double factor = norm();
rescale(factor);
}
int size;
private:
double* data;
};
void vmadd(const Vector& a, const Vector& b, double s, Vector& c)
{
if (c.size != a.size or c.size != b.size) {
std::cerr << "[vmadd]: vector sizes don't match\n";
return;
}
for (int i = 0; i < c.size; i++)
c(i) = a(i) + s * b(i);
}
void compute_householder_factor(Matrix& mat, const Vector& v)
{
int n = v.size;
mat.allocate(n,n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
mat(i,j) = -2 * v(i) * v(j);
for (int i = 0; i < n; i++)
mat(i,i) += 1;
}
void Matrix::extract_column(Vector& v, int c) {
if (m != v.size) {
std::cerr << "[Matrix::extract_column]: Matrix and Vector sizes don't match\n";
return;
}
for (int i = 0; i < m; i++)
v(i) = (*this)(i,c);
}
void matrix_show(const Matrix& m, const std::string& str="")
{
std::cout << str << "\n";
for(int i = 0; i < m.m; i++) {
for (int j = 0; j < m.n; j++) {
printf(" %8.3f", m(i,j));
}
printf("\n");
}
printf("\n");
}
double matrix_compare(const Matrix& A, const Matrix& B) {
if (A.m != B.m or A.n != B.n)
return std::numeric_limits<double>::max();
double res=0;
for(int i = 0; i < A.m; i++) {
for (int j = 0; j < A.n; j++) {
res += (A(i,j)-B(i,j)) * (A(i,j)-B(i,j));
}
}
res /= A.m*A.n;
return res;
}
void householder(Matrix& mat,
Matrix& R,
Matrix& Q)
{
int m = mat.m;
int n = mat.n;
std::vector<Matrix> qv(m);
Matrix z(mat);
Matrix z1;
for (int k = 0; k < n && k < m - 1; k++) {
Vector e(m), x(m);
double a;
z1.compute_minor(z, k);
z1.extract_column(x, k);
a = x.norm();
if (mat(k,k) > 0) a = -a;
for (int i = 0; i < e.size; i++)
e(i) = (i == k) ? 1 : 0;
vmadd(x, e, a, e);
e.rescale_unit();
compute_householder_factor(qv[k], e);
z.mult(qv[k], z1);
}
Q = qv[0];
for (int i = 1; i < n && i < m - 1; i++) {
z1.mult(qv[i], Q);
Q = z1;
}
R.mult(Q, mat);
Q.transpose();
}
double in[][3] = {
{ 12, -51, 4},
{ 6, 167, -68},
{ -4, 24, -41},
{ -1, 1, 0},
{ 2, 0, 3},
};
int main()
{
Matrix A(in);
Matrix Q, R;
matrix_show(A,"A");
householder(A, R, Q);
matrix_show(Q,"Q");
matrix_show(R,"R");
Matrix A_check;
A_check.mult(Q, R);
double l2 = matrix_compare(A,A_check);
matrix_show(A_check, l2 < 1e-12 ? "A == Q * R ? yes" : "A == Q * R ? no");
return EXIT_SUCCESS;
}
| |
c528 | int val = 0;
do{
val++;
std::cout << val << std::endl;
}while(val % 6 != 0);
| |
c529 | #include <cmath>
#include <iostream>
using namespace std;
double getDifference(double b1, double b2) {
double r = fmod(b2 - b1, 360.0);
if (r < -180.0)
r += 360.0;
if (r >= 180.0)
r -= 360.0;
return r;
}
int main()
{
cout << "Input in -180 to +180 range" << endl;
cout << getDifference(20.0, 45.0) << endl;
cout << getDifference(-45.0, 45.0) << endl;
cout << getDifference(-85.0, 90.0) << endl;
cout << getDifference(-95.0, 90.0) << endl;
cout << getDifference(-45.0, 125.0) << endl;
cout << getDifference(-45.0, 145.0) << endl;
cout << getDifference(-45.0, 125.0) << endl;
cout << getDifference(-45.0, 145.0) << endl;
cout << getDifference(29.4803, -88.6381) << endl;
cout << getDifference(-78.3251, -159.036) << endl;
cout << "Input in wider range" << endl;
cout << getDifference(-70099.74233810938, 29840.67437876723) << endl;
cout << getDifference(-165313.6666297357, 33693.9894517456) << endl;
cout << getDifference(1174.8380510598456, -154146.66490124757) << endl;
cout << getDifference(60175.77306795546, 42213.07192354373) << endl;
return 0;
}
| |
c530 | #include <iomanip>
#include <iostream>
#include <cmath>
bool approxEquals(double a, double b, double e) {
return fabs(a - b) < e;
}
void test(double a, double b) {
constexpr double epsilon = 1e-18;
std::cout << std::setprecision(21) << a;
std::cout << ", ";
std::cout << std::setprecision(21) << b;
std::cout << " => ";
std::cout << approxEquals(a, b, epsilon) << '\n';
}
int main() {
test(100000000000000.01, 100000000000000.011);
test(100.01, 100.011);
test(10000000000000.001 / 10000.0, 1000000000.0000001000);
test(0.001, 0.0010000001);
test(0.000000000000000000000101, 0.0);
test(sqrt(2.0) * sqrt(2.0), 2.0);
test(-sqrt(2.0) * sqrt(2.0), -2.0);
test(3.14159265358979323846, 3.14159265358979324);
return 0;
}
| |
c531 | #include <cmath>
#include <iostream>
double vdc(int n, double base = 2)
{
double vdc = 0, denom = 1;
while (n)
{
vdc += fmod(n, base) / (denom *= base);
n /= base;
}
return vdc;
}
int main()
{
for (double base = 2; base < 6; ++base)
{
std::cout << "Base " << base << "\n";
for (int n = 0; n < 10; ++n)
{
std::cout << vdc(n, base) << " ";
}
std::cout << "\n\n";
}
}
| |
c532 | #include <string>
using namespace std;
string s1="abcd";
string s2="abab";
string s3="ab";
s1.compare(0,s3.size(),s3)==0;
s1.compare(s1.size()-s3.size(),s3.size(),s3)==0;
s1.find(s2)
int loc=s2.find(s3)
loc=s2.find(s3,loc+1)
| |
c533 | #include <charconv>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <variant>
using namespace std;
string file_to_string (const string& path)
{
ifstream file {path, ios::in | ios::binary | ios::ate};
if (!file) throw (errno);
string contents;
contents.resize(file.tellg());
file.seekg(0);
file.read(contents.data(), contents.size());
return contents;
}
void string_to_file (const string& path, string contents)
{
ofstream file {path, ios::out | ios::binary};
if (!file) throw (errno);
file.write(contents.data(), contents.size());
}
template <class F>
void with_IO (string source, string destination, F&& f)
{
string input;
if (source == "stdin") getline(cin, input);
else input = file_to_string(source);
string output = invoke(forward<F>(f), input);
if (destination == "stdout") cout << output;
else string_to_file(destination, output);
}
string sanitize (string s)
{
for (auto i = 0u; i < s.size(); ++i)
{
if (s[i] == '\n') s.replace(i++, 1, "\\n");
else if (s[i] == '\\') s.replace(i++, 1, "\\\\");
}
return s;
}
class Scanner
{
public:
const char* pos;
int line = 1;
int column = 1;
Scanner (const char* source) : pos {source} {}
inline char peek () { return *pos; }
void advance ()
{
if (*pos == '\n') { ++line; column = 1; }
else ++column;
++pos;
}
char next ()
{
advance();
return peek();
}
void skip_whitespace ()
{
while (isspace(static_cast<unsigned char>(peek())))
advance();
}
};
enum class TokenName
{
OP_MULTIPLY, OP_DIVIDE, OP_MOD, OP_ADD, OP_SUBTRACT, OP_NEGATE,
OP_LESS, OP_LESSEQUAL, OP_GREATER, OP_GREATEREQUAL, OP_EQUAL, OP_NOTEQUAL,
OP_NOT, OP_ASSIGN, OP_AND, OP_OR,
LEFTPAREN, RIGHTPAREN, LEFTBRACE, RIGHTBRACE, SEMICOLON, COMMA,
KEYWORD_IF, KEYWORD_ELSE, KEYWORD_WHILE, KEYWORD_PRINT, KEYWORD_PUTC,
IDENTIFIER, INTEGER, STRING,
END_OF_INPUT, ERROR
};
using TokenVal = variant<int, string>;
struct Token
{
TokenName name;
TokenVal value;
int line;
int column;
};
const char* to_cstring (TokenName name)
{
static const char* s[] =
{
"Op_multiply", "Op_divide", "Op_mod", "Op_add", "Op_subtract", "Op_negate",
"Op_less", "Op_lessequal", "Op_greater", "Op_greaterequal", "Op_equal", "Op_notequal",
"Op_not", "Op_assign", "Op_and", "Op_or",
"LeftParen", "RightParen", "LeftBrace", "RightBrace", "Semicolon", "Comma",
"Keyword_if", "Keyword_else", "Keyword_while", "Keyword_print", "Keyword_putc",
"Identifier", "Integer", "String",
"End_of_input", "Error"
};
return s[static_cast<int>(name)];
}
string to_string (Token t)
{
ostringstream out;
out << setw(2) << t.line << " " << setw(2) << t.column << " ";
switch (t.name)
{
case (TokenName::IDENTIFIER) : out << "Identifier " << get<string>(t.value); break;
case (TokenName::INTEGER) : out << "Integer " << left << get<int>(t.value); break;
case (TokenName::STRING) : out << "String \"" << sanitize(get<string>(t.value)) << '"'; break;
case (TokenName::END_OF_INPUT) : out << "End_of_input"; break;
case (TokenName::ERROR) : out << "Error " << get<string>(t.value); break;
default : out << to_cstring(t.name);
}
out << '\n';
return out.str();
}
class Lexer
{
public:
Lexer (const char* source) : s {source}, pre_state {s} {}
bool has_more () { return s.peek() != '\0'; }
Token next_token ()
{
s.skip_whitespace();
pre_state = s;
switch (s.peek())
{
case '*' : return simply(TokenName::OP_MULTIPLY);
case '%' : return simply(TokenName::OP_MOD);
case '+' : return simply(TokenName::OP_ADD);
case '-' : return simply(TokenName::OP_SUBTRACT);
case '{' : return simply(TokenName::LEFTBRACE);
case '}' : return simply(TokenName::RIGHTBRACE);
case '(' : return simply(TokenName::LEFTPAREN);
case ')' : return simply(TokenName::RIGHTPAREN);
case ';' : return simply(TokenName::SEMICOLON);
case ',' : return simply(TokenName::COMMA);
case '&' : return expect('&', TokenName::OP_AND);
case '|' : return expect('|', TokenName::OP_OR);
case '<' : return follow('=', TokenName::OP_LESSEQUAL, TokenName::OP_LESS);
case '>' : return follow('=', TokenName::OP_GREATEREQUAL, TokenName::OP_GREATER);
case '=' : return follow('=', TokenName::OP_EQUAL, TokenName::OP_ASSIGN);
case '!' : return follow('=', TokenName::OP_NOTEQUAL, TokenName::OP_NOT);
case '/' : return divide_or_comment();
case '\'' : return char_lit();
case '"' : return string_lit();
default : if (is_id_start(s.peek())) return identifier();
if (is_digit(s.peek())) return integer_lit();
return error("Unrecognized character '", s.peek(), "'");
case '\0' : return make_token(TokenName::END_OF_INPUT);
}
}
private:
Scanner s;
Scanner pre_state;
static const map<string, TokenName> keywords;
template <class... Args>
Token error (Args&&... ostream_args)
{
string code {pre_state.pos, (string::size_type) s.column - pre_state.column};
ostringstream msg;
(msg << ... << forward<Args>(ostream_args)) << '\n'
<< string(28, ' ') << "(" << s.line << ", " << s.column << "): " << code;
if (s.peek() != '\0') s.advance();
return make_token(TokenName::ERROR, msg.str());
}
inline Token make_token (TokenName name, TokenVal value = 0)
{
return {name, value, pre_state.line, pre_state.column};
}
Token simply (TokenName name)
{
s.advance();
return make_token(name);
}
Token expect (char expected, TokenName name)
{
if (s.next() == expected) return simply(name);
else return error("Unrecognized character '", s.peek(), "'");
}
Token follow (char expected, TokenName ifyes, TokenName ifno)
{
if (s.next() == expected) return simply(ifyes);
else return make_token(ifno);
}
Token divide_or_comment ()
{
if (s.next() != '*') return make_token(TokenName::OP_DIVIDE);
while (s.next() != '\0')
{
if (s.peek() == '*' && s.next() == '/')
{
s.advance();
return next_token();
}
}
return error("End-of-file in comment. Closing comment characters not found.");
}
Token char_lit ()
{
int n = s.next();
if (n == '\'') return error("Empty character constant");
if (n == '\\') switch (s.next())
{
case 'n' : n = '\n'; break;
case '\\' : n = '\\'; break;
default : return error("Unknown escape sequence \\", s.peek());
}
if (s.next() != '\'') return error("Multi-character constant");
s.advance();
return make_token(TokenName::INTEGER, n);
}
Token string_lit ()
{
string text = "";
while (s.next() != '"')
switch (s.peek())
{
case '\\' : switch (s.next())
{
case 'n' : text += '\n'; continue;
case '\\' : text += '\\'; continue;
default : return error("Unknown escape sequence \\", s.peek());
}
case '\n' : return error("End-of-line while scanning string literal."
" Closing string character not found before end-of-line.");
case '\0' : return error("End-of-file while scanning string literal."
" Closing string character not found.");
default : text += s.peek();
}
s.advance();
return make_token(TokenName::STRING, text);
}
static inline bool is_id_start (char c) { return isalpha(static_cast<unsigned char>(c)) || c == '_'; }
static inline bool is_id_end (char c) { return isalnum(static_cast<unsigned char>(c)) || c == '_'; }
static inline bool is_digit (char c) { return isdigit(static_cast<unsigned char>(c)); }
Token identifier ()
{
string text (1, s.peek());
while (is_id_end(s.next())) text += s.peek();
auto i = keywords.find(text);
if (i != keywords.end()) return make_token(i->second);
return make_token(TokenName::IDENTIFIER, text);
}
Token integer_lit ()
{
while (is_digit(s.next()));
if (is_id_start(s.peek()))
return error("Invalid number. Starts like a number, but ends in non-numeric characters.");
int n;
auto r = from_chars(pre_state.pos, s.pos, n);
if (r.ec == errc::result_out_of_range) return error("Number exceeds maximum value");
return make_token(TokenName::INTEGER, n);
}
};
const map<string, TokenName> Lexer::keywords =
{
{"else", TokenName::KEYWORD_ELSE},
{"if", TokenName::KEYWORD_IF},
{"print", TokenName::KEYWORD_PRINT},
{"putc", TokenName::KEYWORD_PUTC},
{"while", TokenName::KEYWORD_WHILE}
};
int main (int argc, char* argv[])
{
string in = (argc > 1) ? argv[1] : "stdin";
string out = (argc > 2) ? argv[2] : "stdout";
with_IO(in, out, [](string input)
{
Lexer lexer {input.data()};
string s = "Location Token name Value\n"
"--------------------------------------\n";
while (lexer.has_more()) s += to_string(lexer.next_token());
return s;
});
}
| |
c534 | #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
| |
c535 | #include <iostream>
#include <fstream>
#include <vector>
typedef unsigned char byte;
using namespace std;
const unsigned m1 = 63 << 18, m2 = 63 << 12, m3 = 63 << 6;
class base64
{
public:
base64() { char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; }
string encode( vector<byte> v )
{
string res;
unsigned d, a = 0, l = static_cast<unsigned>( v.size() );
while( l > 2 )
{
d = v[a++] << 16 | v[a++] << 8 | v[a++];
res.append( 1, char_set.at( ( d & m1 ) >> 18 ) );
res.append( 1, char_set.at( ( d & m2 ) >> 12 ) );
res.append( 1, char_set.at( ( d & m3 ) >> 6 ) );
res.append( 1, char_set.at( d & 63 ) );
l -= 3;
}
if( l == 2 )
{
d = v[a++] << 16 | v[a++] << 8;
res.append( 1, char_set.at( ( d & m1 ) >> 18 ) );
res.append( 1, char_set.at( ( d & m2 ) >> 12 ) );
res.append( 1, char_set.at( ( d & m3 ) >> 6 ) );
res.append( 1, '=' );
}
else if( l == 1 )
{
d = v[a++] << 16;
res.append( 1, char_set.at( ( d & m1 ) >> 18 ) );
res.append( 1, char_set.at( ( d & m2 ) >> 12 ) );
res.append( "==", 2 );
}
return res;
}
private:
string char_set;
};
int main( int argc, char* argv[] )
{
base64 b;
basic_ifstream<byte> f( "favicon.ico", ios::binary );
string r = b.encode( vector<byte>( ( istreambuf_iterator<byte>( f ) ), istreambuf_iterator<byte>() ) );
copy( r.begin(), r.end(), ostream_iterator<char>( cout ) );
return 0;
}
| |
c536 | #include <iostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <cstdlib>
#include <string>
std::string rot13(std::string s)
{
static std::string const
lcalph = "abcdefghijklmnopqrstuvwxyz",
ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string result;
std::string::size_type pos;
result.reserve(s.length());
for (std::string::iterator it = s.begin(); it != s.end(); ++it)
{
if ( (pos = lcalph.find(*it)) != std::string::npos )
result.push_back(lcalph[(pos+13) % 26]);
else if ( (pos = ucalph.find(*it)) != std::string::npos )
result.push_back(ucalph[(pos+13) % 26]);
else
result.push_back(*it);
}
return result;
}
int rot13_stream(std::istream& is)
{
std::string line;
while (std::getline(is, line))
{
if (!(std::cout << rot13(line) << "\n"))
return false;
}
return is.eof();
}
int main(int argc, char* argv[])
{
if (argc == 1)
return rot13_stream(std::cin)? EXIT_SUCCESS : EXIT_FAILURE;
std::ifstream file;
for (int i = 1; i < argc; ++i)
{
file.open(argv[i], std::ios::in);
if (!file)
{
std::cerr << argv[0] << ": could not open for reading: " << argv[i] << "\n";
return EXIT_FAILURE;
}
if (!rot13_stream(file))
{
if (file.eof())
std::cerr << argv[0] << ": error writing to stdout\n";
else
std::cerr << argv[0] << ": error reading from " << argv[i] << "\n";
return EXIT_FAILURE;
}
file.clear();
file.close();
if (!file)
std::cerr << argv[0] << ": warning: closing failed for " << argv[i] << "\n";
}
return EXIT_SUCCESS;
}
| |
c537 | #include <iostream>
#include <string>
#include <vector>
const std::vector<std::pair<std::string, std::string>> conditions = {
{"Printer prints", "NNNNYYYY"},
{"A red light is flashing", "YYNNYYNN"},
{"Printer is recognized by computer", "NYNYNYNY"}
};
const std::vector<std::pair<std::string, std::string>> actions = {
{"Check the power cable", "NNYNNNNN"},
{"Check the printer-computer cable", "YNYNNNNN"},
{"Ensure printer software is installed", "YNYNYNYN"},
{"Check/replace ink", "YYNNNYNN"},
{"Check for paper jam", "NYNYNNNN"},
};
int main() {
const size_t nc = conditions.size();
const size_t na = actions.size();
const size_t nr = conditions[0].second.size();
const int np = 7;
auto answers = new bool[nc];
std::string input;
std::cout << "Please answer the following questions with a y or n:\n";
for (size_t c = 0; c < nc; c++) {
char ans;
do {
std::cout << conditions[c].first << "? ";
std::getline(std::cin, input);
ans = std::toupper(input[0]);
} while (ans != 'Y' && ans != 'N');
answers[c] = ans == 'Y';
}
std::cout << "Recommended action(s)\n";
for (size_t r = 0; r < nr; r++) {
for (size_t c = 0; c < nc; c++) {
char yn = answers[c] ? 'Y' : 'N';
if (conditions[c].second[r] != yn) {
goto outer;
}
}
if (r == np) {
std::cout << " None (no problem detected)\n";
} else {
for (auto action : actions) {
if (action.second[r] == 'Y') {
std::cout << " " << action.first << '\n';
}
}
}
break;
outer: {}
}
delete[] answers;
return 0;
}
| |
c538 | #include <iostream>
#include <string>
using namespace std;
class Vigenere
{
public:
string key;
Vigenere(string key)
{
for(int i = 0; i < key.size(); ++i)
{
if(key[i] >= 'A' && key[i] <= 'Z')
this->key += key[i];
else if(key[i] >= 'a' && key[i] <= 'z')
this->key += key[i] + 'A' - 'a';
}
}
string encrypt(string text)
{
string out;
for(int i = 0, j = 0; i < text.length(); ++i)
{
char c = text[i];
if(c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if(c < 'A' || c > 'Z')
continue;
out += (c + key[j] - 2*'A') % 26 + 'A';
j = (j + 1) % key.length();
}
return out;
}
string decrypt(string text)
{
string out;
for(int i = 0, j = 0; i < text.length(); ++i)
{
char c = text[i];
if(c >= 'a' && c <= 'z')
c += 'A' - 'a';
else if(c < 'A' || c > 'Z')
continue;
out += (c - key[j] + 26) % 26 + 'A';
j = (j + 1) % key.length();
}
return out;
}
};
int main()
{
Vigenere cipher("VIGENERECIPHER");
string original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
string encrypted = cipher.encrypt(original);
string decrypted = cipher.decrypt(encrypted);
cout << original << endl;
cout << "Encrypted: " << encrypted << endl;
cout << "Decrypted: " << decrypted << endl;
}
| |
c539 | #include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
int main( ) {
boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
std::cout << to_simple_string( t ) << std::endl ;
return 0 ;
}
| |
c540 | #include <time.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <deque>
class riffle
{
public:
void shuffle( std::deque<int>* v, int tm )
{
std::deque<int> tmp;
bool fl;
size_t len;
std::deque<int>::iterator it;
copyTo( v, &tmp );
for( int t = 0; t < tm; t++ )
{
std::deque<int> lHand( rand() % ( tmp.size() / 3 ) + ( tmp.size() >> 1 ) ), rHand( tmp.size() - lHand.size() );
std::copy( tmp.begin(), tmp.begin() + lHand.size(), lHand.begin() );
std::copy( tmp.begin() + lHand.size(), tmp.end(), rHand.begin() );
tmp.clear();
while( lHand.size() && rHand.size() )
{
fl = rand() % 10 < 5;
if( fl )
len = 1 + lHand.size() > 3 ? rand() % 3 + 1 : rand() % ( lHand.size() ) + 1;
else
len = 1 + rHand.size() > 3 ? rand() % 3 + 1 : rand() % ( rHand.size() ) + 1;
while( len )
{
if( fl )
{
tmp.push_front( *lHand.begin() );
lHand.erase( lHand.begin() );
}
else
{
tmp.push_front( *rHand.begin() );
rHand.erase( rHand.begin() );
}
len--;
}
}
if( lHand.size() < 1 )
{
for( std::deque<int>::iterator x = rHand.begin(); x != rHand.end(); x++ )
tmp.push_front( *x );
}
if( rHand.size() < 1 )
{
for( std::deque<int>::iterator x = lHand.begin(); x != lHand.end(); x++ )
tmp.push_front( *x );
}
}
copyTo( &tmp, v );
}
private:
void copyTo( std::deque<int>* a, std::deque<int>* b )
{
for( std::deque<int>::iterator x = a->begin(); x != a->end(); x++ )
b->push_back( *x );
a->clear();
}
};
class overhand
{
public:
void shuffle( std::deque<int>* v, int tm )
{
std::deque<int> tmp;
bool top;
for( int t = 0; t < tm; t++ )
{
while( v->size() )
{
size_t len = rand() % ( v->size() ) + 1;
top = rand() % 10 < 5;
while( len )
{
if( top ) tmp.push_back( *v->begin() );
else tmp.push_front( *v->begin() );
v->erase( v->begin() );
len--;
}
}
for( std::deque<int>::iterator x = tmp.begin(); x != tmp.end(); x++ )
v->push_back( *x );
tmp.clear();
}
}
};
std::deque<int> cards;
void fill()
{
cards.clear();
for( int x = 0; x < 20; x++ )
cards.push_back( x + 1 );
}
void display( std::string t )
{
std::cout << t << "\n";
for( std::deque<int>::iterator x = cards.begin(); x != cards.end(); x++ )
std::cout << *x << " ";
std::cout << "\n\n";
}
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned>( time( NULL ) ) );
riffle r; overhand o;
fill(); r.shuffle( &cards, 10 ); display( "RIFFLE" );
fill(); o.shuffle( &cards, 10 ); display( "OVERHAND" );
fill(); std::random_shuffle( cards.begin(), cards.end() ); display( "STD SHUFFLE" );
return 0;
}
| |
c541 | #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
| |
c542 | #include <iostream>
#include <vector>
using namespace std;
typedef unsigned long long bigint;
class josephus
{
public:
bigint findSurvivors( bigint n, bigint k, bigint s = 0 )
{
bigint i = s + 1;
for( bigint x = i; x <= n; x++, i++ )
s = ( s + k ) % i;
return s;
}
void getExecutionList( bigint n, bigint k, bigint s = 1 )
{
cout << endl << endl << "Execution list: " << endl;
prisoners.clear();
for( bigint x = 0; x < n; x++ )
prisoners.push_back( x );
bigint index = 0;
while( prisoners.size() > s )
{
index += k - 1;
if( index >= prisoners.size() ) index %= prisoners.size();
cout << prisoners[static_cast<unsigned int>( index )] << ", ";
vector<bigint>::iterator it = prisoners.begin() + static_cast<unsigned int>( index );
prisoners.erase( it );
}
}
private:
vector<bigint> prisoners;
};
int main( int argc, char* argv[] )
{
josephus jo;
bigint n, k, s;
while( true )
{
system( "cls" );
cout << "Number of prisoners( 0 to QUIT ): "; cin >> n;
if( !n ) return 0;
cout << "Execution step: "; cin >> k;
cout << "How many survivors: "; cin >> s;
cout << endl << "Survivor";
if( s == 1 )
{
cout << ": " << jo.findSurvivors( n, k );
jo.getExecutionList( n, k );
}
else
{
cout << "s: ";
for( bigint x = 0; x < s; x++ )
cout << jo.findSurvivors( n, k, x ) << ", ";
jo.getExecutionList( n, k, s );
}
cout << endl << endl;
system( "pause" );
}
return 0;
}
| |
c543 | #include <thread>
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
int main()
{
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<> dist(1,1000);
std::vector<std::thread> threads;
for(const auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) {
std::chrono::milliseconds duration(dist(eng));
threads.emplace_back([str, duration](){
std::this_thread::sleep_for(duration);
std::cout << str;
});
}
for(auto& t: threads) t.join();
return 0;
}
| |
c544 | #include <time.h>
#include <iostream>
#include <vector>
using namespace std;
class cSort
{
public:
void doIt( vector<unsigned> s )
{
sq = s; display(); c_sort();
cout << "writes: " << wr << endl; display();
}
private:
void display()
{
copy( sq.begin(), sq.end(), ostream_iterator<unsigned>( std::cout, " " ) );
cout << endl;
}
void c_sort()
{
wr = 0;
unsigned it, p, vlen = static_cast<unsigned>( sq.size() );
for( unsigned c = 0; c < vlen - 1; c++ )
{
it = sq[c];
p = c;
for( unsigned d = c + 1; d < vlen; d++ )
if( sq[d] < it ) p++;
if( c == p ) continue;
doSwap( p, it );
while( c != p )
{
p = c;
for( unsigned e = c + 1; e < vlen; e++ )
if( sq[e] < it ) p++;
doSwap( p, it );
}
}
}
void doSwap( unsigned& p, unsigned& it )
{
while( sq[p] == it ) p++;
swap( it, sq[p] );
wr++;
}
vector<unsigned> sq;
unsigned wr;
};
int main(int argc, char ** argv)
{
srand( static_cast<unsigned>( time( NULL ) ) );
vector<unsigned> s;
for( int x = 0; x < 20; x++ )
s.push_back( rand() % 100 + 21 );
cSort c; c.doIt( s );
return 0;
}
| |
c545 | #include <vector>
#include <iostream>
using namespace std;
void Filter(const vector<float> &b, const vector<float> &a, const vector<float> &in, vector<float> &out)
{
out.resize(0);
out.resize(in.size());
for(int i=0; i < in.size(); i++)
{
float tmp = 0.;
int j=0;
out[i] = 0.f;
for(j=0; j < b.size(); j++)
{
if(i - j < 0) continue;
tmp += b[j] * in[i-j];
}
for(j=1; j < a.size(); j++)
{
if(i - j < 0) continue;
tmp -= a[j]*out[i-j];
}
tmp /= a[0];
out[i] = tmp;
}
}
int main()
{
vector<float> sig = {-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973,-1.00700480494,\
-0.404707073677,0.800482325044,0.743500089861,1.01090520172,0.741527555207,\
0.277841675195,0.400833448236,-0.2085993586,-0.172842103641,-0.134316096293,\
0.0259303398477,0.490105989562,0.549391221511,0.9047198589};
vector<float> a = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17};
vector<float> b = {0.16666667, 0.5, 0.5, 0.16666667};
vector<float> result;
Filter(b, a, sig, result);
for(size_t i=0;i<result.size();i++)
cout << result[i] << ",";
cout << endl;
return 0;
}
| |
c546 | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_map>
#include <vector>
int main(int ac, char** av) {
std::ios::sync_with_stdio(false);
int head = (ac > 1) ? std::atoi(av[1]) : 10;
std::istreambuf_iterator<char> it(std::cin), eof;
std::filebuf file;
if (ac > 2) {
if (file.open(av[2], std::ios::in), file.is_open()) {
it = std::istreambuf_iterator<char>(&file);
} else return std::cerr << "file " << av[2] << " open failed\n", 1;
}
auto alpha = [](unsigned c) { return c-'A' < 26 || c-'a' < 26; };
auto lower = [](unsigned c) { return c | '\x20'; };
std::unordered_map<std::string, int> counts;
std::string word;
for (; it != eof; ++it) {
if (alpha(*it)) {
word.push_back(lower(*it));
} else if (!word.empty()) {
++counts[word];
word.clear();
}
}
if (!word.empty()) ++counts[word];
std::vector<std::pair<const std::string,int> const*> out;
for (auto& count : counts) out.push_back(&count);
std::partial_sort(out.begin(),
out.size() < head ? out.end() : out.begin() + head,
out.end(), [](auto const* a, auto const* b) {
return a->second > b->second;
});
if (out.size() > head) out.resize(head);
for (auto const& count : out) {
std::cout << count->first << ' ' << count->second << '\n';
}
return 0;
}
| |
c547 | #include <iostream>
bool isSemiPrime( int c )
{
int a = 2, b = 0;
while( b < 3 && c != 1 )
{
if( !( c % a ) )
{ c /= a; b++; }
else a++;
}
return b == 2;
}
int main( int argc, char* argv[] )
{
for( int x = 2; x < 100; x++ )
if( isSemiPrime( x ) )
std::cout << x << " ";
return 0;
}
| |
c548 | #include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/regex.hpp>
int main()
{
boost::asio::ip::tcp::iostream s("tycho.usno.navy.mil", "http");
if(!s)
std::cout << "Could not connect to tycho.usno.navy.mil\n";
s << "GET /cgi-bin/timer.pl HTTP/1.0\r\n"
<< "Host: tycho.usno.navy.mil\r\n"
<< "Accept: */*\r\n"
<< "Connection: close\r\n\r\n" ;
for(std::string line; getline(s, line); )
{
boost::smatch matches;
if(regex_search(line, matches, boost::regex("<BR>(.+\\s+UTC)") ) )
{
std::cout << matches[1] << '\n';
break;
}
}
}
| |
c549 |
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
#define _(STR) STR
class Model
{
public:
static const int GOAL = 21;
static const int NUMBER_OF_PLAYERS = 2;
static const int MIN_MOVE = 1;
static const int MAX_MOVE = 3;
int bestMove();
bool update(const char* player, int move);
bool isGameBegin();
bool isGameOver();
protected:
friend class View;
View* view = nullptr;
const char* player = nullptr;
int oldTotal = 0;
int newTotal = 0;
int lastMove = 0;
};
class View
{
protected:
Model* model;
public:
View(Model* model);
void init(const char* player);
void update();
};
class Controller
{
protected:
Model* model;
View* view;
public:
Controller(Model* model, View* view);
int input();
void clear();
void run();
};
int Model::bestMove()
{
int move = MIN_MOVE;
for (int i = MIN_MOVE; i <= MAX_MOVE; i++)
if ((newTotal + i - 1) % (MAX_MOVE + 1) == 0)
move = i;
for (int i = MIN_MOVE; i <= MAX_MOVE; i++)
if (newTotal + i == GOAL)
move = i;
return move;
}
bool Model::update(const char* player, int move)
{
if (move >= MIN_MOVE && move <= MAX_MOVE && newTotal + move <= GOAL)
{
this->player = player;
oldTotal = newTotal;
newTotal = oldTotal + move;
lastMove = move;
view->update();
return true;
}
else
return false;
}
bool Model::isGameBegin()
{
return oldTotal == 0;
}
bool Model::isGameOver()
{
return newTotal == GOAL;
}
View::View(Model* model)
{
this->model = model;
model->view = this;
}
void View::init(const char* player)
{
if (model->newTotal == 0)
cout << _("----NEW GAME----\n\n")
<< _("The running total is currently zero.\n")
<< _("The first move is ") << player << _(" move.\n\n");
}
void View::update()
{
cout << setw(8) << model->player << ": " << model->newTotal << " = "
<< model->oldTotal << " + " << model->lastMove << endl << endl;
if (model->isGameOver())
cout << endl << _("The winner is ") << model->player << _(".\n\n\n");
}
Controller::Controller(Model* model, View* view)
{
this->model = model;
this->view = view;
}
void Controller::run()
{
if (rand() % Model::NUMBER_OF_PLAYERS == 0)
{
view->init("AI");
model->update("AI", model->bestMove());
}
else
view->init("human");
while (!model->isGameOver())
{
while (!model->update("human", input()))
clear();
model->update("AI", model->bestMove());
}
}
int Controller::input()
{
int value;
cout << _("enter a valid number to play (or enter 0 to exit game): ");
cin >> value;
cout << endl;
if (!cin.fail())
{
if (value == 0)
exit(EXIT_SUCCESS);
else
return value;
}
else
return model->MIN_MOVE - 1;
}
void Controller::clear()
{
cout << _("Your answer is not a valid choice.") << endl;
cin.clear();
cin.ignore((streamsize)numeric_limits<int>::max, '\n');
}
int main(int argc, char* argv)
{
srand(time(NULL));
cout << _(
"21 Game \n"
" \n"
"21 is a two player game, the game is played by choosing a number \n"
"(1, 2, or 3) to be added to the running total. The game is won by\n"
"the player whose chosen number causes the running total to reach \n"
"exactly 21. The running total starts at zero. \n\n");
while (true)
{
Model* model = new Model();
View* view = new View(model);
Controller* controler = new Controller(model, view);
controler->run();
delete controler;
delete model;
delete view;
}
return EXIT_SUCCESS;
}
| |
c550 | #include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
#include <cstdlib>
int main( int argc , char* argv[ ] ) {
using namespace boost::gregorian ;
greg_month months[ ] = { Jan , Feb , Mar , Apr , May , Jun , Jul ,
Aug , Sep , Oct , Nov , Dec } ;
greg_year gy = atoi( argv[ 1 ] ) ;
for ( int i = 0 ; i < 12 ; i++ ) {
last_day_of_the_week_in_month lwdm ( Friday , months[ i ] ) ;
date d = lwdm.get_date( gy ) ;
std::cout << d << std::endl ;
}
return 0 ;
}
| |
c551 |
#include <cmath>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
queue<unsigned> suspected;
vector<unsigned> primes;
bool isPrime(unsigned n)
{
if (n == 2)
{
return true;
}
if (n == 1 || n % 2 == 0)
{
return false;
}
unsigned root = sqrt(n);
for (unsigned k = 3; k <= root; k += 2)
{
if (n % k == 0)
{
return false;
}
}
return true;
}
int main(int argc, char argv[])
{
for (unsigned k = 1; k <= 9; k++)
{
suspected.push(k);
}
while (!suspected.empty())
{
int n = suspected.front();
suspected.pop();
if (isPrime(n))
{
primes.push_back(n);
}
for (unsigned k = n % 10 + 1; k <= 9; k++)
{
suspected.push(n * 10 + k);
}
}
copy(primes.begin(), primes.end(), ostream_iterator<unsigned>(cout, " "));
return EXIT_SUCCESS;
}
| |
c552 |
#include "gmp.h"
void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {
mpf_add (out1, in1, in2);
mpf_div_ui (out1, out1, 2);
mpf_mul (out2, in1, in2);
mpf_sqrt (out2, out2);
}
int main (void) {
mpf_set_default_prec (65568);
mpf_t x0, y0, resA, resB;
mpf_init_set_ui (y0, 1);
mpf_init_set_d (x0, 0.5);
mpf_sqrt (x0, x0);
mpf_init (resA);
mpf_init (resB);
for(int i=0; i<7; i++){
agm(x0, y0, resA, resB);
agm(resA, resB, x0, y0);
}
gmp_printf ("%.20000Ff\n", x0);
gmp_printf ("%.20000Ff\n\n", y0);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.