_id stringlengths 2 5 | text stringlengths 7 10.9k | title stringclasses 1
value |
|---|---|---|
c946 | #include <iostream>
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n';
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
std::cout << "a shl b: " << (a << b) << '\n';
std::cout << "a shr b: " << (a >> b) << '\n';
unsigned int ua = a;
std::cout << "a lsr b: " << (ua >> b) << '\n';
std::cout << "a rol b: " << std::rotl(ua, b) << '\n';
std::cout << "a ror b: " << std::rotr(ua, b) << '\n';
}
| |
c947 | #include <windows.h>
#include <iostream>
using namespace std;
const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c )
{
clr = c; createPen();
}
void setPenWidth( int w )
{
wid = w; createPen();
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class dragonC
{
public:
dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }
void draw( int iterations ) { generate( iterations ); draw(); }
private:
void generate( int it )
{
generator.push_back( 1 );
string temp;
for( int y = 0; y < it - 1; y++ )
{
temp = generator; temp.push_back( 1 );
for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )
temp.push_back( !( *x ) );
generator = temp;
}
}
void draw()
{
HDC dc = bmp.getDC();
unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };
int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;
for( int t = 0; t < 4; t++ )
{
int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];
MoveToEx( dc, a, b, NULL );
bmp.setPenColor( clr[t] );
for( string::iterator x = generator.begin(); x < generator.end(); x++ )
{
switch( dir )
{
case NORTH:
if( *x ) { a += LEN; dir = EAST; }
else { a -= LEN; dir = WEST; }
break;
case EAST:
if( *x ) { b += LEN; dir = SOUTH; }
else { b -= LEN; dir = NORTH; }
break;
case SOUTH:
if( *x ) { a -= LEN; dir = WEST; }
else { a += LEN; dir = EAST; }
break;
case WEST:
if( *x ) { b -= LEN; dir = NORTH; }
else { b += LEN; dir = SOUTH; }
}
LineTo( dc, a, b );
}
}
bmp.saveBitmap( "f:/rc/dragonCpp.bmp" );
}
int dir;
myBitmap bmp;
string generator;
};
int main( int argc, char* argv[] )
{
dragonC d; d.draw( 17 );
return system( "pause" );
}
| |
c948 | #include <fstream>
#include <string>
#include <iostream>
int main( int argc , char** argv ) {
int linecount = 0 ;
std::string line ;
std::ifstream infile( argv[ 1 ] ) ;
if ( infile ) {
while ( getline( infile , line ) ) {
std::cout << linecount << ": "
<< line << '\n' ;
linecount++ ;
}
}
infile.close( ) ;
return 0 ;
}
| |
c949 | template <typename T>
void insert_after(Node<T>* N, T&& data)
{
auto node = new Node<T>{N, N->next, std::forward(data)};
if(N->next != nullptr)
N->next->prev = node;
N->next = node;
}
| |
c950 | #include <iostream>
#include <cstdint>
using integer = uint32_t;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 + next_prime_digit_number(n/10) * 10;
}
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };
integer p = 7;
for (;;) {
for (integer w : wheel) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += w;
}
}
}
int main() {
std::cout.imbue(std::locale(""));
const integer limit = 1000000000;
integer n = 0, max = 0;
std::cout << "First 25 SPDS primes:\n";
for (int i = 0; n < limit; ) {
n = next_prime_digit_number(n);
if (!is_prime(n))
continue;
if (i < 25) {
if (i > 0)
std::cout << ' ';
std::cout << n;
}
else if (i == 25)
std::cout << '\n';
++i;
if (i == 100)
std::cout << "Hundredth SPDS prime: " << n << '\n';
else if (i == 1000)
std::cout << "Thousandth SPDS prime: " << n << '\n';
else if (i == 10000)
std::cout << "Ten thousandth SPDS prime: " << n << '\n';
max = n;
}
std::cout << "Largest SPDS prime less than " << limit << ": " << max << '\n';
return 0;
}
| |
c951 | #include <algorithm>
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));
std::cout << a[i];
if (i < 9) std::cout << ", ";
}
std::cout << std::endl;
return 0;
}
| |
c952 | #include <string>
#include <cstdlib>
#include <algorithm>
#include <cassert>
std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
std::string to_base(unsigned long num, int base)
{
if (num == 0)
return "0";
std::string result;
while (num > 0) {
std::ldiv_t temp = std::div(num, (long)base);
result += digits[temp.rem];
num = temp.quot;
}
std::reverse(result.begin(), result.end());
return result;
}
unsigned long from_base(std::string const& num_str, int base)
{
unsigned long result = 0;
for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)
result = result * base + digits.find(num_str[pos]);
return result;
}
| |
c953 | #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
| |
c954 | UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)
{
UINT_64 N;
N = N1;
N = (N<<32)|N2;
return UINT_64(N);
}
UINT_32 TGost::ReplaceBlock(UINT_32 x)
{
register i;
UINT_32 res = 0UL;
for(i=7;i>=0;i--)
{
ui4_0 = x>>(i*4);
ui4_0 = BS[ui4_0][i];
res = (res<<4)|ui4_0;
}
return res;
}
UINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)
{
UINT_32 N1,N2,S=0UL;
N1=UINT_32(N);
N2=N>>32;
S = N1 + X % 0x4000000000000;
S = ReplaceBlock(S);
S = (S<<11)|(S>>21);
S ^= N2;
N2 = N1;
N1 = S;
return SWAP32(N2,N1);
}
| |
c955 | #include <algorithm>
#include <iostream>
#include <string>
#include <array>
#include <vector>
template<typename T>
T unique(T&& src)
{
T retval(std::move(src));
std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());
retval.erase(std::unique(retval.begin(), retval.end()), retval.end());
return retval;
}
#define USE_FAKES 1
auto states = unique(std::vector<std::string>({
#if USE_FAKES
"Slender Dragon", "Abalamara",
#endif
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
}));
struct counted_pair
{
std::string name;
std::array<int, 26> count{};
void count_characters(const std::string& s)
{
for (auto&& c : s) {
if (c >= 'a' && c <= 'z') count[c - 'a']++;
if (c >= 'A' && c <= 'Z') count[c - 'A']++;
}
}
counted_pair(const std::string& s1, const std::string& s2)
: name(s1 + " + " + s2)
{
count_characters(s1);
count_characters(s2);
}
};
bool operator<(const counted_pair& lhs, const counted_pair& rhs)
{
auto lhs_size = lhs.name.size();
auto rhs_size = rhs.name.size();
return lhs_size == rhs_size
? std::lexicographical_compare(lhs.count.begin(),
lhs.count.end(),
rhs.count.begin(),
rhs.count.end())
: lhs_size < rhs_size;
}
bool operator==(const counted_pair& lhs, const counted_pair& rhs)
{
return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;
}
int main()
{
const int n_states = states.size();
std::vector<counted_pair> pairs;
for (int i = 0; i < n_states; i++) {
for (int j = 0; j < i; j++) {
pairs.emplace_back(counted_pair(states[i], states[j]));
}
}
std::sort(pairs.begin(), pairs.end());
auto start = pairs.begin();
while (true) {
auto match = std::adjacent_find(start, pairs.end());
if (match == pairs.end()) {
break;
}
auto next = match + 1;
std::cout << match->name << " => " << next->name << "\n";
start = next;
}
}
| |
c956 | #include <algorithm>
#include <array>
#include <cstdint>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <string>
std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept
{
auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};
struct byte_checksum
{
std::uint_fast32_t operator()() noexcept
{
auto checksum = static_cast<std::uint_fast32_t>(n++);
for (auto i = 0; i < 8; ++i)
checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);
return checksum;
}
unsigned n = 0;
};
auto table = std::array<std::uint_fast32_t, 256>{};
std::generate(table.begin(), table.end(), byte_checksum{});
return table;
}
template <typename InputIterator>
std::uint_fast32_t crc(InputIterator first, InputIterator last)
{
static auto const table = generate_crc_lookup_table();
return std::uint_fast32_t{0xFFFFFFFFuL} &
~std::accumulate(first, last,
~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},
[](std::uint_fast32_t checksum, std::uint_fast8_t value)
{ return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });
}
int main()
{
auto const s = std::string{"The quick brown fox jumps over the lazy dog"};
std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n';
}
| |
c957 | #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!\n" ;
std::cout << csvToHTML( text ) ;
return 0 ;
}
std::string csvToHTML( const std::string & csvtext ) {
std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
const char* replacements [ 5 ] = { "<" , ">" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ;
boost::regex e1( regexes[ 0 ] ) ;
std::string tabletext = boost::regex_replace( csvtext , e1 ,
replacements[ 0 ] , boost::match_default | boost::format_all ) ;
for ( int i = 1 ; i < 5 ; i++ ) {
e1.assign( regexes[ i ] ) ;
tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
}
tabletext = std::string( "<TABLE>\n" ) + tabletext ;
tabletext.append( "</TABLE>\n" ) ;
return tabletext ;
}
| |
c958 | PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
OPTION PARSE FALSE
'---The class does the declaring for you
CLASS Books
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1 = Books()
'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567
PRINT "Book title : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
| |
c959 | #include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <utility>
long string2long( const std::string & s ) {
long result ;
std::istringstream( s ) >> result ;
return result ;
}
bool isKaprekar( long number ) {
long long squarenumber = ((long long)number) * number ;
std::ostringstream numberbuf ;
numberbuf << squarenumber ;
std::string numberstring = numberbuf.str( ) ;
for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {
std::string firstpart = numberstring.substr( 0 , i ) ,
secondpart = numberstring.substr( i ) ;
if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) {
return false ;
}
if ( string2long( firstpart ) + string2long( secondpart ) == number ) {
return true ;
}
}
return false ;
}
int main( ) {
std::vector<long> kaprekarnumbers ;
kaprekarnumbers.push_back( 1 ) ;
for ( int i = 2 ; i < 1000001 ; i++ ) {
if ( isKaprekar( i ) )
kaprekarnumbers.push_back( i ) ;
}
std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;
std::cout << "Kaprekar numbers up to 10000: \n" ;
while ( *svi < 10000 ) {
std::cout << *svi << " " ;
svi++ ;
}
std::cout << '\n' ;
std::cout << "All the Kaprekar numbers up to 1000000 :\n" ;
std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,
std::ostream_iterator<long>( std::cout , "\n" ) ) ;
std::cout << "There are " << kaprekarnumbers.size( )
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}
| |
c960 | #include <string>
#include <map>
template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result) {
int dictSize = 256;
std::map<std::string,int> dictionary;
for (int i = 0; i < 256; i++)
dictionary[std::string(1, i)] = i;
std::string w;
for (std::string::const_iterator it = uncompressed.begin();
it != uncompressed.end(); ++it) {
char c = *it;
std::string wc = w + c;
if (dictionary.count(wc))
w = wc;
else {
*result++ = dictionary[w];
dictionary[wc] = dictSize++;
w = std::string(1, c);
}
}
if (!w.empty())
*result++ = dictionary[w];
return result;
}
template <typename Iterator>
std::string decompress(Iterator begin, Iterator end) {
int dictSize = 256;
std::map<int,std::string> dictionary;
for (int i = 0; i < 256; i++)
dictionary[i] = std::string(1, i);
std::string w(1, *begin++);
std::string result = w;
std::string entry;
for ( ; begin != end; begin++) {
int k = *begin;
if (dictionary.count(k))
entry = dictionary[k];
else if (k == dictSize)
entry = w + w[0];
else
throw "Bad compressed k";
result += entry;
dictionary[dictSize++] = w + entry[0];
w = entry;
}
return result;
}
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> compressed;
compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed));
copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
std::string decompressed = decompress(compressed.begin(), compressed.end());
std::cout << decompressed << std::endl;
return 0;
}
| |
c961 | #include <iomanip>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
while (list->size() > target_size) list->pop_back();
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
int m = max(*r.rbegin(), *s.rbegin());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
return 0;
}
| |
c962 | #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
class MagicSquare
{
public:
MagicSquare(int d) : sqr(d*d,0), sz(d)
{
assert(d&1);
fillSqr();
}
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr;
cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ )
{
int yy = y * sz;
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr()
{
int sx = sz / 2, sy = 0, c = 0;
while( c < sz * sz )
{
if( !sqr[sx + sy * sz] )
{
sqr[sx + sy * sz]= c + 1;
inc( sx ); dec( sy );
c++;
}
else
{
dec( sx ); inc( sy ); inc( sy );
}
}
}
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a )
{ if( ++a == sz ) a = 0; }
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
vector<int> sqr;
int sz;
};
int main()
{
MagicSquare s(7);
s.display();
return 0;
}
| |
c963 | #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(n1_, n_) == 1
&& std::gcd(n2_, n_) > 1); ++n_) {}
}
sequence_.insert(n_);
for (;;) {
auto it = sequence_.find(min_);
if (it == sequence_.end())
break;
sequence_.erase(it);
++min_;
}
return n_;
}
private:
std::set<integer> sequence_;
integer min_ = 1;
integer n_ = 0;
integer n1_ = 0;
integer n2_ = 0;
};
int main() {
std::cout << "First 30 Yellowstone numbers:\n";
yellowstone_generator<unsigned int> ygen;
std::cout << ygen.next();
for (int i = 1; i < 30; ++i)
std::cout << ' ' << ygen.next();
std::cout << '\n';
return 0;
}
| |
c964 | #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
| |
c965 | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(mertens_numbers(max));
std::cout << "First 199 Mertens numbers:\n";
for (int i = 0, column = 0; i < 200; ++i) {
if (column > 0)
std::cout << ' ';
if (i == 0)
std::cout << " ";
else
std::cout << std::setw(2) << m[i];
++column;
if (column == 20) {
std::cout << '\n';
column = 0;
}
}
int zero = 0, cross = 0, previous = 0;
for (int i = 1; i <= max; ++i) {
if (m[i] == 0) {
++zero;
if (previous != 0)
++cross;
}
previous = m[i];
}
std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n";
std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
return 0;
}
| |
c966 | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false;
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
return !response.empty() && response.front() == 'y';
}
void PrintOrder(const vector<string>& items)
{
cout << "{ ";
for(auto& item : items) cout << item << " ";
cout << "}\n";
}
int main()
{
const vector<string> items
{
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
};
vector<string> sortedItems;
for(auto& item : items)
{
cout << "Inserting '" << item << "' into ";
PrintOrder(sortedItems);
auto spotToInsert = lower_bound(sortedItems.begin(),
sortedItems.end(), item, InteractiveCompare);
sortedItems.insert(spotToInsert, item);
}
PrintOrder(sortedItems);
return 0;
}
| |
c967 |
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
| |
c968 | #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
class bells
{
public:
void start()
{
watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First";
count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
}
private:
static DWORD WINAPI bell( LPVOID p )
{
DWORD wait = _inst->waitTime();
while( true )
{
Sleep( wait );
_inst->playBell();
wait = _inst->waitTime();
}
return 0;
}
DWORD waitTime()
{
GetLocalTime( &st );
int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
}
void playBell()
{
GetLocalTime( &st );
int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
int w = ( 60 * st.wHour + st.wMinute );
if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );
cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;
for( int x = 0, c = 1; x < b; x++, c++ )
{
cout << "\7"; Sleep( 500 );
if( !( c % 2 ) ) Sleep( 300 );
}
}
SYSTEMTIME st;
string watch[7], count[8];
static bells* _inst;
};
bells* bells::_inst = 0;
int main( int argc, char* argv[] )
{
bells b; b.start();
while( 1 );
return 0;
}
| |
c969 | double fib(double n)
{
if(n < 0)
{
throw "Invalid argument passed to fib";
}
else
{
struct actual_fib
{
static double calc(double n)
{
if(n < 2)
{
return n;
}
else
{
return calc(n-1) + calc(n-2);
}
}
};
return actual_fib::calc(n);
}
}
| |
c970 | #include <windows.h>
#include <ctime>
#include <iostream>
#include <string>
const int WID = 60, HEI = 30, MAX_LEN = 600;
enum DIR { NORTH, EAST, SOUTH, WEST };
class snake {
public:
snake() {
console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( "Snake" );
COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );
SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );
CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );
}
void play() {
std::string a;
while( 1 ) {
createField(); alive = true;
while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }
COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );
SetConsoleTextAttribute( console, 0x000b );
std::cout << "Play again [Y/N]? "; std::cin >> a;
if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;
}
}
private:
void createField() {
COORD coord = { 0, 0 }; DWORD c;
FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );
FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );
SetConsoleCursorPosition( console, coord );
int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;
for( x = 0; x < WID; x++ ) {
brd[x] = brd[x + WID * ( HEI - 1 )] = '+';
}
for( ; y < HEI; y++ ) {
brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';
}
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@';
tailIdx = 0; headIdx = 4; x = 3; y = 2;
for( int c = tailIdx; c < headIdx; c++ ) {
brd[x + WID * y] = '#';
snk[c].X = 3 + c; snk[c].Y = 2;
}
head = snk[3]; dir = EAST; points = 0;
}
void readKey() {
if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;
if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;
if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;
if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;
}
void drawField() {
COORD coord; char t;
for( int y = 0; y < HEI; y++ ) {
coord.Y = y;
for( int x = 0; x < WID; x++ ) {
t = brd[x + WID * y]; if( !t ) continue;
coord.X = x; SetConsoleCursorPosition( console, coord );
if( coord.X == head.X && coord.Y == head.Y ) {
SetConsoleTextAttribute( console, 0x002e );
std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );
continue;
}
switch( t ) {
case '#': SetConsoleTextAttribute( console, 0x002a ); break;
case '+': SetConsoleTextAttribute( console, 0x0019 ); break;
case '@': SetConsoleTextAttribute( console, 0x004c ); break;
}
std::cout << t; SetConsoleTextAttribute( console, 0x0000 );
}
}
std::cout << t; SetConsoleTextAttribute( console, 0x0007 );
COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );
std::cout << "Points: " << points;
}
void moveSnake() {
switch( dir ) {
case NORTH: head.Y--; break;
case EAST: head.X++; break;
case SOUTH: head.Y++; break;
case WEST: head.X--; break;
}
char t = brd[head.X + WID * head.Y];
if( t && t != '@' ) { alive = false; return; }
brd[head.X + WID * head.Y] = '#';
snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;
if( ++headIdx >= MAX_LEN ) headIdx = 0;
if( t == '@' ) {
points++; int x, y;
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@'; return;
}
SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';
brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;
if( ++tailIdx >= MAX_LEN ) tailIdx = 0;
}
bool alive; char brd[WID * HEI];
HANDLE console; DIR dir; COORD snk[MAX_LEN];
COORD head; int tailIdx, headIdx, points;
};
int main( int argc, char* argv[] ) {
srand( static_cast<unsigned>( time( NULL ) ) );
snake s; s.play(); return 0;
}
| |
c971 | #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
| |
c972 | #include <cmath>
#include <iostream>
#include <vector>
std::vector<int> generate_primes(int limit) {
std::vector<bool> sieve(limit >> 1, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
class legendre_prime_counter {
public:
explicit legendre_prime_counter(int limit);
int prime_count(int n);
private:
int phi(int x, int a);
std::vector<int> primes;
};
legendre_prime_counter::legendre_prime_counter(int limit) :
primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}
int legendre_prime_counter::prime_count(int n) {
if (n < 2)
return 0;
int a = prime_count(static_cast<int>(std::sqrt(n)));
return phi(n, a) + a - 1;
}
int legendre_prime_counter::phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes[a - 1];
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
int main() {
legendre_prime_counter counter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
std::cout << "10^" << i << "\t" << counter.prime_count(n) << '\n';
}
| |
c973 | #include <string>
using std::string;
extern "C" int
Query (char *Data, size_t *Length)
{
const string Message = "Here am I";
if (*Length < Message.length())
return false;
*Length = Message.length();
Message.copy(Data, *Length);
return true;
}
| |
c974 | #include <iostream>
#include <string.h>
int main()
{
std::string longLine, longestLines, newLine;
while (std::cin >> newLine)
{
auto isNewLineShorter = longLine.c_str();
auto isLongLineShorter = newLine.c_str();
while (*isNewLineShorter && *isLongLineShorter)
{
isNewLineShorter = &isNewLineShorter[1];
isLongLineShorter = &isLongLineShorter[1];
}
if(*isNewLineShorter) continue;
if(*isLongLineShorter)
{
longLine = newLine;
longestLines = newLine;
}
else
{
longestLines+=newLine;
}
longestLines+="\n";
}
std::cout << "\nLongest string:\n" << longestLines;
}
| |
c975 | #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
| |
c976 | #include <direct.h>
#include <fstream>
int main() {
std::fstream f("output.txt", std::ios::out);
f.close();
f.open("/output.txt", std::ios::out);
f.close();
_mkdir("docs");
_mkdir("/docs");
return 0;
}
| |
c977 | #include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
typedef uint32_t integer;
int count_digits(integer n) {
int digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
integer change_digit(integer n, int index, int new_digit) {
integer p = 1;
integer changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
bool unprimeable(const prime_sieve& sieve, integer n) {
if (sieve.is_prime(n))
return false;
int d = count_digits(n);
for (int i = 0; i < d; ++i) {
for (int j = 0; j <= 9; ++j) {
integer m = change_digit(n, i, j);
if (m != n && sieve.is_prime(m))
return false;
}
}
return true;
}
int main() {
const integer limit = 10000000;
prime_sieve sieve(limit);
std::cout.imbue(std::locale(""));
std::cout << "First 35 unprimeable numbers:\n";
integer n = 100;
integer lowest[10] = { 0 };
for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(sieve, n)) {
if (count < 35) {
if (count != 0)
std::cout << ", ";
std::cout << n;
}
++count;
if (count == 600)
std::cout << "\n600th unprimeable number: " << n << '\n';
int last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
for (int i = 0; i < 10; ++i)
std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
return 0;
}
| |
c978 | #include <iostream>
#include <iomanip>
inline int sign(int i) {
return i < 0 ? -1 : i > 0;
}
inline int& E(int *x, int row, int col) {
return x[row * (row + 1) / 2 + col];
}
int iter(int *v, int *diff) {
E(v, 0, 0) = 151;
E(v, 2, 0) = 40;
E(v, 4, 1) = 11;
E(v, 4, 3) = 4;
for (auto i = 1u; i < 5u; i++)
for (auto j = 0u; j <= i; j++) {
E(diff, i, j) = 0;
if (j < i)
E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
if (j)
E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
}
for (auto i = 0u; i < 4u; i++)
for (auto j = 0u; j < i; j++)
E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);
E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);
uint sum;
int e = 0;
for (auto i = sum = 0u; i < 15u; i++) {
sum += !!sign(e = diff[i]);
if (e >= 4 || e <= -4)
v[i] += e / 5;
else if (rand() < RAND_MAX / 4)
v[i] += sign(e);
}
return sum;
}
void show(int *x) {
for (auto i = 0u; i < 5u; i++)
for (auto j = 0u; j <= i; j++)
std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}
int main() {
int v[15] = { 0 }, diff[15] = { 0 };
for (auto i = 1u, s = 1u; s; i++) {
s = iter(v, diff);
std::cout << "pass " << i << ": " << s << std::endl;
}
show(v);
return 0;
}
| |
c979 | #include <gmp.h>
#include <iostream>
using namespace std;
typedef unsigned long long int u64;
bool primality_pretest(u64 k) {
if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) ||
!(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)
) {
return (k <= 23);
}
return true;
}
bool probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
bool is_chernick(int n, u64 m, mpz_t z) {
if (!primality_pretest(6 * m + 1)) {
return false;
}
if (!primality_pretest(12 * m + 1)) {
return false;
}
u64 t = 9 * m;
for (int i = 1; i <= n - 2; i++) {
if (!primality_pretest((t << i) + 1)) {
return false;
}
}
if (!probprime(6 * m + 1, z)) {
return false;
}
if (!probprime(12 * m + 1, z)) {
return false;
}
for (int i = 1; i <= n - 2; i++) {
if (!probprime((t << i) + 1, z)) {
return false;
}
}
return true;
}
int main() {
mpz_t z;
mpz_inits(z, NULL);
for (int n = 3; n <= 10; n++) {
u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;
if (n > 5) {
multiplier *= 5;
}
for (u64 k = 1; ; k++) {
u64 m = k * multiplier;
if (is_chernick(n, m, z)) {
cout << "a(" << n << ") has m = " << m << endl;
break;
}
}
}
return 0;
}
| |
c980 | #include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\n";
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
| |
c981 | #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
}
| |
c983 | #include <cstdint>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_probably_prime(const integer& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
int main() {
const unsigned int max = 20;
integer primorial = 1;
for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {
if (!is_prime(p))
continue;
primorial *= p;
++index;
if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {
if (count > 0)
std::cout << ' ';
std::cout << index;
++count;
}
}
std::cout << '\n';
return 0;
}
| |
c984 | #include <map>
#include <string>
#include <iostream>
#include <iomanip>
const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";
class DnaBase {
public:
DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {
for (auto elm : dna) {
if (count.find(elm) == count.end())
count[elm] = 0;
++count[elm];
}
}
void viewGenome() {
std::cout << "Sequence:" << std::endl;
std::cout << std::endl;
int limit = genome.size() / displayWidth;
if (genome.size() % displayWidth != 0)
++limit;
for (int i = 0; i < limit; ++i) {
int beginPos = i * displayWidth;
std::cout << std::setw(4) << beginPos << " :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;
}
std::cout << std::endl;
std::cout << "Base Count" << std::endl;
std::cout << "----------" << std::endl;
std::cout << std::endl;
int total = 0;
for (auto elm : count) {
std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl;
total += elm.second;
}
std::cout << std::endl;
std::cout << "Total: " << total << std::endl;
}
private:
std::string genome;
std::map<char, int> count;
int displayWidth;
};
int main(void) {
auto d = new DnaBase();
d->viewGenome();
delete d;
return 0;
}
| |
c985 | #include <algorithm>
#include <array>
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <string>
#include <string_view>
#include <thread>
const int timeScale = 42;
void Message(std::string_view message)
{
static std::mutex cout_mutex;
std::scoped_lock cout_lock(cout_mutex);
std::cout << message << std::endl;
}
struct Fork {
std::mutex mutex;
};
struct Dinner {
std::array<Fork, 5> forks;
~Dinner() { Message("Dinner is over"); }
};
class Philosopher
{
std::mt19937 rng{std::random_device {}()};
const std::string name;
Fork& left;
Fork& right;
std::thread worker;
void live();
void dine();
void ponder();
public:
Philosopher(std::string name_, Fork& l, Fork& r)
: name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)
{}
~Philosopher()
{
worker.join();
Message(name + " went to sleep.");
}
};
void Philosopher::live()
{
for(;;)
{
{
std::scoped_lock dine_lock(left.mutex, right.mutex);
dine();
}
ponder();
}
}
void Philosopher::dine()
{
Message(name + " started eating.");
thread_local std::array<const char*, 3> foods {"chicken", "rice", "soda"};
thread_local std::array<const char*, 3> reactions {
"I like this %s!", "This %s is good.", "Mmm, %s..."
};
thread_local std::uniform_int_distribution<> dist(1, 6);
std::shuffle( foods.begin(), foods.end(), rng);
std::shuffle(reactions.begin(), reactions.end(), rng);
constexpr size_t buf_size = 64;
char buffer[buf_size];
for(int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));
snprintf(buffer, buf_size, reactions[i], foods[i]);
Message(name + ": " + buffer);
}
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);
Message(name + " finished and left.");
}
void Philosopher::ponder()
{
static constexpr std::array<const char*, 5> topics {{
"politics", "art", "meaning of life", "source of morality", "how many straws makes a bale"
}};
thread_local std::uniform_int_distribution<> wait(1, 6);
thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);
while(dist(rng) > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is pondering about " + topics[dist(rng)] + ".");
}
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is hungry again!");
}
int main()
{
Dinner dinner;
Message("Dinner started!");
std::array<Philosopher, 5> philosophers {{
{"Aristotle", dinner.forks[0], dinner.forks[1]},
{"Democritus", dinner.forks[1], dinner.forks[2]},
{"Plato", dinner.forks[2], dinner.forks[3]},
{"Pythagoras", dinner.forks[3], dinner.forks[4]},
{"Socrates", dinner.forks[4], dinner.forks[0]},
}};
Message("It is dark outside...");
}
| |
c986 | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return sum == i;
}
private:
ulong f[12];
};
int main() {
factorion_t factorion;
for (uint b = 9u; b <= 12u; ++b) {
std::cout << "factorions for base " << b << ':';
for (uint i = 1u; i < 1500000u; ++i)
if (factorion(i, b))
std::cout << ' ' << i;
std::cout << std::endl;
}
return 0;
}
| |
c987 | #include <cmath>
#include <functional>
#include <iostream>
constexpr double K = 7.8e9;
constexpr int n0 = 27;
constexpr double actual[] = {
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,
4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,
31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,
69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,
80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,
95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,
133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,
271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652
};
double f(double r) {
double sq = 0;
constexpr size_t len = std::size(actual);
for (size_t i = 0; i < len; ++i) {
double eri = std::exp(r * i);
double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);
double diff = guess - actual[i];
sq += diff * diff;
}
return sq;
}
double solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {
for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;
delta > epsilon && guess != guess - delta;
delta *= factor) {
double nf = fn(guess - delta);
if (nf < f0) {
f0 = nf;
guess -= delta;
} else {
nf = fn(guess + delta);
if (nf < f0) {
f0 = nf;
guess += delta;
} else
factor = 0.5;
}
}
return guess;
}
int main() {
double r = solve(f);
double R0 = std::exp(12 * r);
std::cout << "r = " << r << ", R0 = " << R0 << '\n';
return 0;
}
| |
c988 | #include <list>
template <typename T>
std::list<T> strandSort(std::list<T> lst) {
if (lst.size() <= 1)
return lst;
std::list<T> result;
std::list<T> sorted;
while (!lst.empty()) {
sorted.push_back(lst.front());
lst.pop_front();
for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {
if (sorted.back() <= *it) {
sorted.push_back(*it);
it = lst.erase(it);
} else
it++;
}
result.merge(sorted);
}
return result;
}
| |
c989 | #include <iomanip>
#include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int digit_sum(unsigned int n) {
unsigned int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
int main() {
const unsigned int limit = 500;
std::cout << "Additive primes less than " << limit << ":\n";
unsigned int count = 0;
for (unsigned int n = 1; n < limit; ++n) {
if (is_prime(digit_sum(n)) && is_prime(n)) {
std::cout << std::setw(3) << n;
if (++count % 10 == 0)
std::cout << '\n';
else
std::cout << ' ';
}
}
std::cout << '\n' << count << " additive primes found.\n";
}
| |
c990 | class invertedAssign {
int data;
public:
invertedAssign(int data):data(data){}
int getData(){return data;}
void operator=(invertedAssign& other) const {
other.data = this->data;
}
};
#include <iostream>
int main(){
invertedAssign a = 0;
invertedAssign b = 42;
std::cout << a.getData() << ' ' << b.getData() << '\n';
b = a;
std::cout << a.getData() << ' ' << b.getData() << '\n';
}
| |
c991 | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
bool perfect_totient_number(const totient_calculator& tc, int n) {
int sum = 0;
for (int m = n; m > 1; ) {
int t = tc.totient(m);
sum += t;
m = t;
}
return sum == n;
}
int main() {
totient_calculator tc(10000);
int count = 0, n = 1;
std::cout << "First 20 perfect totient numbers:\n";
for (; count < 20; ++n) {
if (perfect_totient_number(tc, n)) {
if (count > 0)
std::cout << ' ';
++count;
std::cout << n;
}
}
std::cout << '\n';
return 0;
}
| |
c992 | #include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace std::tr1;
using std::tr1::function;
class IDelegate
{
public:
virtual ~IDelegate() {}
};
class IThing
{
public:
virtual ~IThing() {}
virtual std::string Thing() = 0;
};
class DelegateA : virtual public IDelegate
{
};
class DelegateB : public IThing, public IDelegate
{
std::string Thing()
{
return "delegate implementation";
}
};
class Delegator
{
public:
std::string Operation()
{
if(Delegate)
if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))
return pThing->Thing();
return "default implementation";
}
shared_ptr<IDelegate> Delegate;
};
int main()
{
shared_ptr<DelegateA> delegateA(new DelegateA());
shared_ptr<DelegateB> delegateB(new DelegateB());
Delegator delegator;
std::cout << delegator.Operation() << std::endl;
delegator.Delegate = delegateA;
std::cout << delegator.Operation() << std::endl;
delegator.Delegate = delegateB;
std::cout << delegator.Operation() << std::endl;
}
| |
c993 | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(4) << divisor_sum(n);
if (n % 10 == 0)
std::cout << '\n';
}
}
| |
c994 | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
| |
c995 | #include <iostream>
class MyOtherClass
{
public:
const int m_x;
MyOtherClass(const int initX = 0) : m_x(initX) { }
};
int main()
{
MyOtherClass mocA, mocB(7);
std::cout << mocA.m_x << std::endl;
std::cout << mocB.m_x << std::endl;
return 0;
}
| |
c996 | #include <iostream>
#include <span>
#include <vector>
struct vec2 {
float x = 0.0f, y = 0.0f;
constexpr vec2 operator+(vec2 other) const {
return vec2{x + other.x, y + other.y};
}
constexpr vec2 operator-(vec2 other) const {
return vec2{x - other.x, y - other.y};
}
};
constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }
constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }
constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }
constexpr bool is_inside(vec2 point, vec2 a, vec2 b) {
return (cross(a - b, point) + cross(b, a)) < 0.0f;
}
constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {
return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *
(1.0f / cross(a1 - a2, b1 - b2));
}
std::vector<vec2> suther_land_hodgman(
std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {
if (clip_polygon.empty() || subject_polygon.empty()) {
return {};
}
std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};
vec2 p1 = clip_polygon[clip_polygon.size() - 1];
std::vector<vec2> input;
for (vec2 p2 : clip_polygon) {
input.clear();
input.insert(input.end(), ring.begin(), ring.end());
vec2 s = input[input.size() - 1];
ring.clear();
for (vec2 e : input) {
if (is_inside(e, p1, p2)) {
if (!is_inside(s, p1, p2)) {
ring.push_back(intersection(p1, p2, s, e));
}
ring.push_back(e);
} else if (is_inside(s, p1, p2)) {
ring.push_back(intersection(p1, p2, s, e));
}
s = e;
}
p1 = p2;
}
return ring;
}
int main(int argc, char **argv) {
vec2 subject_polygon[] = {{50, 150}, {200, 50}, {350, 150},
{350, 300}, {250, 300}, {200, 250},
{150, 350}, {100, 250}, {100, 200}};
vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};
std::vector<vec2> clipped_polygon =
suther_land_hodgman(subject_polygon, clip_polygon);
std::cout << "Clipped polygon points:" << std::endl;
for (vec2 p : clipped_polygon) {
std::cout << "(" << p.x << ", " << p.y << ")" << std::endl;
}
return EXIT_SUCCESS;
}
| |
c997 | #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
| |
c998 | #include <vector>
#include <memory>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;
auto_ptr< IntTable > getSpiralArray( int dimension )
{
auto_ptr< IntTable > spiralArrayPtr( new IntTable(
dimension, IntRow( dimension ) ) );
int numConcentricSquares = static_cast< int >( ceil(
static_cast< double >( dimension ) / 2.0 ) );
int j;
int sideLen = dimension;
int currNum = 0;
for ( int i = 0; i < numConcentricSquares; i++ )
{
for ( j = 0; j < sideLen; j++ )
( *spiralArrayPtr )[ i ][ i + j ] = currNum++;
for ( j = 1; j < sideLen; j++ )
( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;
for ( j = sideLen - 2; j > -1; j-- )
( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;
for ( j = sideLen - 2; j > 0; j-- )
( *spiralArrayPtr )[ i + j ][ i ] = currNum++;
sideLen -= 2;
}
return spiralArrayPtr;
}
void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )
{
size_t dimension = spiralArrayPtr->size();
int fieldWidth = static_cast< int >( floor( log10(
static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;
size_t col;
for ( size_t row = 0; row < dimension; row++ )
{
for ( col = 0; col < dimension; col++ )
cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];
cout << endl;
}
}
int main()
{
printSpiralArray( getSpiralArray( 5 ) );
}
| |
c999 | #include <vector>
#include <algorithm>
#include <string>
template <class T>
struct sort_table_functor {
typedef bool (*CompFun)(const T &, const T &);
const CompFun ordering;
const int column;
const bool reverse;
sort_table_functor(CompFun o, int c, bool r) :
ordering(o), column(c), reverse(r) { }
bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {
const T &a = x[column],
&b = y[column];
return reverse ? ordering(b, a)
: ordering(a, b);
}
};
template <class T>
bool myLess(const T &x, const T &y) { return x < y; }
template <class T>
void sort_table(std::vector<std::vector<T> > &table,
int column = 0, bool reverse = false,
bool (*ordering)(const T &, const T &) = myLess) {
std::sort(table.begin(), table.end(),
sort_table_functor<T>(ordering, column, reverse));
}
#include <iostream>
template <class T>
void print_matrix(std::vector<std::vector<T> > &data) {
for () {
for (int j = 0; j < 3; j++)
std::cout << data[i][j] << "\t";
std::cout << std::endl;
}
}
bool desc_len_comparator(const std::string &x, const std::string &y) {
return x.length() > y.length();
}
int main() {
std::string data_array[3][3] =
{
{"a", "b", "c"},
{"", "q", "z"},
{"zap", "zip", "Zot"}
};
std::vector<std::vector<std::string> > data_orig;
for (int i = 0; i < 3; i++) {
std::vector<std::string> row;
for (int j = 0; j < 3; j++)
row.push_back(data_array[i][j]);
data_orig.push_back(row);
}
print_matrix(data_orig);
std::vector<std::vector<std::string> > data = data_orig;
sort_table(data);
print_matrix(data);
data = data_orig;
sort_table(data, 2);
print_matrix(data);
data = data_orig;
sort_table(data, 1);
print_matrix(data);
data = data_orig;
sort_table(data, 1, true);
print_matrix(data);
data = data_orig;
sort_table(data, 0, false, desc_len_comparator);
print_matrix(data);
return 0;
}
| |
c1000 | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
void *bits_ptr = nullptr;
HDC dc = GetDC(GetConsoleWindow());
bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);
if (!bmp_) return false;
hdc_ = CreateCompatibleDC(dc);
SelectObject(hdc_, bmp_);
ReleaseDC(GetConsoleWindow(), dc);
width_ = w;
height_ = h;
return true;
}
void SetPenColor(DWORD clr) {
if (pen_) DeleteObject(pen_);
pen_ = CreatePen(PS_SOLID, 1, clr);
SelectObject(hdc_, pen_);
}
bool SaveBitmap(const char* path) {
HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return false;
}
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
GetObject(bmp_, sizeof(bitmap), &bitmap);
DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory(dwp_bits, 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)dwp_bits, &infoheader, DIB_RGB_COLORS);
DWORD wb;
WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);
WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);
WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);
CloseHandle(file);
delete[] dwp_bits;
return true;
}
HDC hdc() { return hdc_; }
int width() { return width_; }
int height() { return height_; }
private:
HBITMAP bmp_;
HDC hdc_;
HPEN pen_;
int width_, height_;
};
static int DistanceSqrd(const Point& point, int x, int y) {
int xd = x - point.x;
int yd = y - point.y;
return (xd * xd) + (yd * yd);
}
class Voronoi {
public:
void Make(MyBitmap* bmp, int count) {
bmp_ = bmp;
CreatePoints(count);
CreateColors();
CreateSites();
SetSitesPoints();
}
private:
void CreateSites() {
int w = bmp_->width(), h = bmp_->height(), d;
for (int hh = 0; hh < h; hh++) {
for (int ww = 0; ww < w; ww++) {
int ind = -1, dist = INT_MAX;
for (size_t it = 0; it < points_.size(); it++) {
const Point& p = points_[it];
d = DistanceSqrd(p, ww, hh);
if (d < dist) {
dist = d;
ind = it;
}
}
if (ind > -1)
SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);
else
__asm nop
}
}
}
void SetSitesPoints() {
for (const auto& point : points_) {
int x = point.x, y = point.y;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
SetPixel(bmp_->hdc(), x + i, y + j, 0);
}
}
void CreatePoints(int count) {
const int w = bmp_->width() - 20, h = bmp_->height() - 20;
for (int i = 0; i < count; i++) {
points_.push_back({ rand() % w + 10, rand() % h + 10 });
}
}
void CreateColors() {
for (size_t i = 0; i < points_.size(); i++) {
DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);
colors_.push_back(c);
}
}
vector<Point> points_;
vector<DWORD> colors_;
MyBitmap* bmp_;
};
int main(int argc, char* argv[]) {
ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
srand(GetTickCount());
MyBitmap bmp;
bmp.Create(512, 512);
bmp.SetPenColor(0);
Voronoi v;
v.Make(&bmp, 50);
BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);
bmp.SaveBitmap("v.bmp");
system("pause");
return 0;
}
| |
c1001 | FUNCTION MULTIPLY(X, Y)
DOUBLE PRECISION MULTIPLY, X, Y
| |
c1002 | #include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <ctime>
template <typename T>
std::function<std::vector<T>(T)> s_of_n_creator(int n) {
std::vector<T> sample;
int i = 0;
return [=](T item) mutable {
i++;
if (i <= n) {
sample.push_back(item);
} else if (std::rand() % i < n) {
sample[std::rand() % n] = item;
}
return sample;
};
}
int main() {
std::srand(std::time(NULL));
int bin[10] = {0};
for (int trial = 0; trial < 100000; trial++) {
auto s_of_n = s_of_n_creator<int>(3);
std::vector<int> sample;
for (int i = 0; i < 10; i++)
sample = s_of_n(i);
for (int s : sample)
bin[s]++;
}
for (int x : bin)
std::cout << x << std::endl;
return 0;
}
| |
c1003 | #include <exception>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
class Frac {
public:
Frac() : num(0), denom(1) {}
Frac(int n, int d) {
if (d == 0) {
throw std::runtime_error("d must not be zero");
}
int sign_of_d = d < 0 ? -1 : 1;
int g = std::gcd(n, d);
num = sign_of_d * n / g;
denom = sign_of_d * d / g;
}
Frac operator-() const {
return Frac(-num, denom);
}
Frac operator+(const Frac& rhs) const {
return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);
}
Frac operator-(const Frac& rhs) const {
return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);
}
Frac operator*(const Frac& rhs) const {
return Frac(num*rhs.num, denom*rhs.denom);
}
Frac operator*(int rhs) const {
return Frac(num * rhs, denom);
}
friend std::ostream& operator<<(std::ostream&, const Frac&);
private:
int num;
int denom;
};
std::ostream & operator<<(std::ostream & os, const Frac &f) {
if (f.num == 0 || f.denom == 1) {
return os << f.num;
}
std::stringstream ss;
ss << f.num << "/" << f.denom;
return os << ss.str();
}
Frac bernoulli(int n) {
if (n < 0) {
throw std::runtime_error("n may not be negative or zero");
}
std::vector<Frac> a;
for (int m = 0; m <= n; m++) {
a.push_back(Frac(1, m + 1));
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * j;
}
}
if (n != 1) return a[0];
return -a[0];
}
int binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw std::runtime_error("parameters are invalid");
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num *= i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom *= i;
}
return num / denom;
}
std::vector<Frac> faulhaberTraingle(int p) {
std::vector<Frac> coeffs(p + 1);
Frac q{ 1, p + 1 };
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);
}
return coeffs;
}
int main() {
for (int i = 0; i < 10; i++) {
std::vector<Frac> coeffs = faulhaberTraingle(i);
for (auto frac : coeffs) {
std::cout << std::right << std::setw(5) << frac << " ";
}
std::cout << std::endl;
}
return 0;
}
| |
c1004 | #include <iostream>
int main(int argc, char* argv[])
{
std::cout << "This program is named " << argv[0] << std::endl;
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
for (int i = 1; i < argc; ++i)
std::cout << "the argument #" << i << " is " << argv[i] << std::endl;
return 0;
}
| |
c1005 | #include <array>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
class letterset {
public:
letterset() {
count_.fill(0);
}
explicit letterset(const std::string& str) {
count_.fill(0);
for (char c : str)
add(c);
}
bool contains(const letterset& set) const {
for (size_t i = 0; i < count_.size(); ++i) {
if (set.count_[i] > count_[i])
return false;
}
return true;
}
unsigned int count(char c) const {
return count_[index(c)];
}
bool is_valid() const {
return count_[0] == 0;
}
void add(char c) {
++count_[index(c)];
}
private:
static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }
std::array<unsigned int, 27> count_;
};
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
using dictionary = std::vector<std::pair<std::string, letterset>>;
dictionary load_dictionary(const std::string& filename, int min_length,
int max_length) {
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Cannot open file " + filename);
std::string word;
dictionary result;
while (getline(in, word)) {
if (word.size() < min_length)
continue;
if (word.size() > max_length)
continue;
letterset set(word);
if (set.is_valid())
result.emplace_back(word, set);
}
return result;
}
void word_wheel(const dictionary& dict, const std::string& letters,
char central_letter) {
letterset set(letters);
if (central_letter == 0 && !letters.empty())
central_letter = letters.at(letters.size()/2);
std::map<size_t, std::vector<std::string>> words;
for (const auto& pair : dict) {
const auto& word = pair.first;
const auto& subset = pair.second;
if (subset.count(central_letter) > 0 && set.contains(subset))
words[word.size()].push_back(word);
}
size_t total = 0;
for (const auto& p : words) {
const auto& v = p.second;
auto n = v.size();
total += n;
std::cout << "Found " << n << " " << (n == 1 ? "word" : "words")
<< " of length " << p.first << ": "
<< join(v.begin(), v.end(), ", ") << '\n';
}
std::cout << "Number of words found: " << total << '\n';
}
void find_max_word_count(const dictionary& dict, int word_length) {
size_t max_count = 0;
std::vector<std::pair<std::string, char>> max_words;
for (const auto& pair : dict) {
const auto& word = pair.first;
if (word.size() != word_length)
continue;
const auto& set = pair.second;
dictionary subsets;
for (const auto& p : dict) {
if (set.contains(p.second))
subsets.push_back(p);
}
letterset done;
for (size_t index = 0; index < word_length; ++index) {
char central_letter = word[index];
if (done.count(central_letter) > 0)
continue;
done.add(central_letter);
size_t count = 0;
for (const auto& p : subsets) {
const auto& subset = p.second;
if (subset.count(central_letter) > 0)
++count;
}
if (count > max_count) {
max_words.clear();
max_count = count;
}
if (count == max_count)
max_words.emplace_back(word, central_letter);
}
}
std::cout << "Maximum word count: " << max_count << '\n';
std::cout << "Words of " << word_length << " letters producing this count:\n";
for (const auto& pair : max_words)
std::cout << pair.first << " with central letter " << pair.second << '\n';
}
constexpr const char* option_filename = "filename";
constexpr const char* option_wheel = "wheel";
constexpr const char* option_central = "central";
constexpr const char* option_min_length = "min-length";
constexpr const char* option_part2 = "part2";
int main(int argc, char** argv) {
const int word_length = 9;
int min_length = 3;
std::string letters = "ndeokgelw";
std::string filename = "unixdict.txt";
char central_letter = 0;
bool do_part2 = false;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
(option_filename, po::value<std::string>(), "name of dictionary file")
(option_wheel, po::value<std::string>(), "word wheel letters")
(option_central, po::value<char>(), "central letter (defaults to middle letter of word)")
(option_min_length, po::value<int>(), "minimum word length")
(option_part2, "include part 2");
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count(option_filename))
filename = vm[option_filename].as<std::string>();
if (vm.count(option_wheel))
letters = vm[option_wheel].as<std::string>();
if (vm.count(option_central))
central_letter = vm[option_central].as<char>();
if (vm.count(option_min_length))
min_length = vm[option_min_length].as<int>();
if (vm.count(option_part2))
do_part2 = true;
auto dict = load_dictionary(filename, min_length, word_length);
word_wheel(dict, letters, central_letter);
if (do_part2) {
std::cout << '\n';
find_max_word_count(dict, word_length);
}
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| |
c1006 | #include <vector>
#include <iostream>
int main()
{
std::vector<int> a(3), b(4);
a[0] = 11; a[1] = 12; a[2] = 13;
b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;
a.insert(a.end(), b.begin(), b.end());
for (int i = 0; i < a.size(); ++i)
std::cout << "a[" << i << "] = " << a[i] << "\n";
}
| |
c1007 | #include <iostream>
#include <string>
using namespace std;
int main()
{
long int integer_input;
string string_input;
cout << "Enter an integer: ";
cin >> integer_input;
cout << "Enter a string: ";
cin >> string_input;
return 0;
}
| |
c1008 | #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
{
std::cout << "Error opening MIDI Output..." << std::endl;
device = 0;
}
}
~midi()
{
midiOutReset( device );
midiOutClose( device );
}
bool isOpen() { return device != 0; }
void setInstrument( byte i )
{
message.data[0] = 0xc0; message.data[1] = i;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void playNote( byte n, unsigned i )
{
playNote( n ); Sleep( i ); stopNote( n );
}
private:
void playNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 127; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void stopNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
HMIDIOUT device;
midi_msg message;
};
int main( int argc, char* argv[] )
{
midi m;
if( m.isOpen() )
{
byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
m.setInstrument( 42 );
for( int x = 0; x < 8; x++ )
m.playNote( notes[x], rand() % 100 + 158 );
Sleep( 1000 );
}
return 0;
}
| |
c1009 | #include <vector>
#include <string>
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <set>
int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & ,
std::set<int> & , const int ) ;
int main( ) {
std::vector<boost::tuple<std::string , int , int> > items ;
items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ;
items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ;
items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ;
items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ;
items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ;
items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ;
items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ;
items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ;
items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ;
items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ;
items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ;
items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ;
items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ;
items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ;
items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ;
items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ;
items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ;
items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ;
items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ;
items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ;
items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ;
items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ;
items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ;
const int maximumWeight = 400 ;
std::set<int> bestItems ;
int bestValue = findBestPack( items , bestItems , maximumWeight ) ;
std::cout << "The best value that can be packed in the given knapsack is " <<
bestValue << " !\n" ;
int totalweight = 0 ;
std::cout << "The following items should be packed in the knapsack:\n" ;
for ( std::set<int>::const_iterator si = bestItems.begin( ) ;
si != bestItems.end( ) ; si++ ) {
std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ;
totalweight += (items.begin( ) + *si)->get<1>( ) ;
}
std::cout << "The total weight of all items is " << totalweight << " !\n" ;
return 0 ;
}
int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {
const int n = items.size( ) ;
int bestValues [ n ][ weightlimit ] ;
std::set<int> solutionSets[ n ][ weightlimit ] ;
std::set<int> emptyset ;
for ( int i = 0 ; i < n ; i++ ) {
for ( int j = 0 ; j < weightlimit ; j++ ) {
bestValues[ i ][ j ] = 0 ;
solutionSets[ i ][ j ] = emptyset ;
}
}
for ( int i = 0 ; i < n ; i++ ) {
for ( int weight = 0 ; weight < weightlimit ; weight++ ) {
if ( i == 0 )
bestValues[ i ][ weight ] = 0 ;
else {
int itemweight = (items.begin( ) + i)->get<1>( ) ;
if ( weight < itemweight ) {
bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
} else {
if ( bestValues[ i - 1 ][ weight - itemweight ] +
(items.begin( ) + i)->get<2>( ) >
bestValues[ i - 1 ][ weight ] ) {
bestValues[ i ][ weight ] =
bestValues[ i - 1 ][ weight - itemweight ] +
(items.begin( ) + i)->get<2>( ) ;
solutionSets[ i ][ weight ] =
solutionSets[ i - 1 ][ weight - itemweight ] ;
solutionSets[ i ][ weight ].insert( i ) ;
}
else {
bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
}
}
}
}
}
bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;
return bestValues[ n - 1 ][ weightlimit - 1 ] ;
}
| |
c1010 | #include <algorithm>
#include <iostream>
#include <vector>
typedef unsigned long long integer;
std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {
std::vector<integer> result;
for (integer a = ancestor[n]; a != 0 && a != n; ) {
n = a;
a = ancestor[n];
result.push_back(n);
}
return result;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty()) {
std::cout << "none\n";
return;
}
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
for (integer p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
const size_t limit = 100;
std::vector<integer> ancestor(limit, 0);
std::vector<std::vector<integer>> descendants(limit);
for (size_t prime = 0; prime < limit; ++prime) {
if (!is_prime(prime))
continue;
descendants[prime].push_back(prime);
for (size_t i = 0; i + prime < limit; ++i) {
integer s = i + prime;
for (integer n : descendants[i]) {
integer prod = n * prime;
descendants[s].push_back(prod);
if (prod < limit)
ancestor[prod] = s;
}
}
}
size_t total_descendants = 0;
for (integer i = 1; i < limit; ++i) {
std::vector<integer> ancestors(get_ancestors(ancestor, i));
std::cout << "[" << i << "] Level: " << ancestors.size() << '\n';
std::cout << "Ancestors: ";
std::sort(ancestors.begin(), ancestors.end());
print_vector(ancestors);
std::cout << "Descendants: ";
std::vector<integer>& desc = descendants[i];
if (!desc.empty()) {
std::sort(desc.begin(), desc.end());
if (desc[0] == i)
desc.erase(desc.begin());
}
std::cout << desc.size() << '\n';
total_descendants += desc.size();
if (!desc.empty())
print_vector(desc);
std::cout << '\n';
}
std::cout << "Total descendants: " << total_descendants << '\n';
return 0;
}
| |
c1011 | #include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector<std::vector<int>>& v) {
std::cout << "{ ";
for (const auto& p : v) {
std::cout << "(";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << ") ";
}
std::cout << "}" << std::endl;
}
auto product(const std::vector<std::vector<int>>& lists) {
std::vector<std::vector<int>> result;
if (std::find_if(std::begin(lists), std::end(lists),
[](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
return result;
}
for (auto& e : lists[0]) {
result.push_back({ e });
}
for (size_t i = 1; i < lists.size(); ++i) {
std::vector<std::vector<int>> temp;
for (auto& e : result) {
for (auto f : lists[i]) {
auto e_tmp = e;
e_tmp.push_back(f);
temp.push_back(e_tmp);
}
}
result = temp;
}
return result;
}
int main() {
std::vector<std::vector<int>> prods[] = {
{ { 1, 2 }, { 3, 4 } },
{ { 3, 4 }, { 1, 2} },
{ { 1, 2 }, { } },
{ { }, { 1, 2 } },
{ { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
{ { 1, 2, 3 }, { 30 }, { 500, 100 } },
{ { 1, 2, 3 }, { }, { 500, 100 } }
};
for (const auto& p : prods) {
print(product(p));
}
std::cin.ignore();
std::cin.get();
return 0;
}
| |
c1012 | #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;
typedef function<double(double)> FunType;
vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
int main() {
vector<FunType> composedFuns;
auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};
transform(B.begin(), B.end(),
A.begin(),
back_inserter(composedFuns),
compose<double, double, double>);
for (auto num: exNums)
for (auto fun: composedFuns)
cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;
return 0;
}
| |
c1013 | #include <vector>
#include <iostream>
#include <algorithm>
std::vector<int> properDivisors ( int number ) {
std::vector<int> divisors ;
for ( int i = 1 ; i < number / 2 + 1 ; i++ )
if ( number % i == 0 )
divisors.push_back( i ) ;
return divisors ;
}
int main( ) {
std::vector<int> divisors ;
unsigned int maxdivisors = 0 ;
int corresponding_number = 0 ;
for ( int i = 1 ; i < 11 ; i++ ) {
divisors = properDivisors ( i ) ;
std::cout << "Proper divisors of " << i << ":\n" ;
for ( int number : divisors ) {
std::cout << number << " " ;
}
std::cout << std::endl ;
divisors.clear( ) ;
}
for ( int i = 11 ; i < 20001 ; i++ ) {
divisors = properDivisors ( i ) ;
if ( divisors.size( ) > maxdivisors ) {
maxdivisors = divisors.size( ) ;
corresponding_number = i ;
}
divisors.clear( ) ;
}
std::cout << "Most divisors has " << corresponding_number <<
" , it has " << maxdivisors << " divisors!\n" ;
return 0 ;
}
| |
c1014 | #include <vector>
#include <utility>
#include <iostream>
#include <boost/algorithm/string.hpp>
std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;
int main( ) {
std::vector<std::string> names , remarks ;
names.push_back( "April" ) ;
names.push_back( "Tam O'Shantor" ) ;
names.push_back ( "Emily" ) ;
remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ;
remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ;
remarks.push_back( "Short & shrift" ) ;
std::cout << "This is in XML:\n" ;
std::cout << create_xml( names , remarks ) << std::endl ;
return 0 ;
}
std::string create_xml( std::vector<std::string> & names ,
std::vector<std::string> & remarks ) {
std::vector<std::pair<std::string , std::string> > entities ;
entities.push_back( std::make_pair( "&" , "&" ) ) ;
entities.push_back( std::make_pair( "<" , "<" ) ) ;
entities.push_back( std::make_pair( ">" , ">" ) ) ;
std::string xmlstring ( "<CharacterRemarks>\n" ) ;
std::vector<std::string>::iterator vsi = names.begin( ) ;
typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;
for ( ; vsi != names.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( int i = 0 ; i < names.size( ) ; i++ ) {
xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">")
.append( remarks[ i ] ).append( "</Character>\n" ) ;
}
xmlstring.append( "</CharacterRemarks>" ) ;
return xmlstring ;
}
| |
c1015 | #include <windows.h>
#include <string>
#include <vector>
using namespace std;
const int HSTEP = 46, MWID = 40, MHEI = 471;
const float VSTEP = 2.3f;
class vector2
{
public:
vector2() { x = y = 0; }
vector2( float a, float b ) { x = a; y = b; }
void set( float a, float b ) { x = a; y = b; }
float x, y;
};
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class plot
{
public:
plot() { bmp.create( 512, 512 ); }
void draw( vector<vector2>* pairs )
{
bmp.clear( 0xff );
drawGraph( pairs );
plotIt( pairs );
HDC dc = GetDC( GetConsoleWindow() );
BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( GetConsoleWindow(), dc );
}
private:
void drawGraph( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
bmp.setPenColor( RGB( 240, 240, 240 ) );
DWORD b = 11, c = 40, x;
RECT rc; char txt[8];
for( x = 0; x < pairs->size(); x++ )
{
MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );
MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );
wsprintf( txt, "%d", ( pairs->size() - x ) * 20 );
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
wsprintf( txt, "%d", x );
SetRect( &rc, c - 8, 472, c + 8, 492 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
c += 46; b += 46;
}
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
bmp.setPenColor( 0 ); bmp.setPenWidth( 3 );
MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );
MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );
}
void plotIt( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
HBRUSH br = CreateSolidBrush( 255 );
RECT rc;
bmp.setPenColor( 255 ); bmp.setPenWidth( 2 );
vector<vector2>::iterator it = pairs->begin();
int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
MoveToEx( dc, a, b, NULL );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );
it++;
for( ; it < pairs->end(); it++ )
{
a = MWID + HSTEP * static_cast<int>( ( *it ).x );
b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );
FillRect( dc, &rc, br ); LineTo( dc, a, b );
}
DeleteObject( br );
}
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
plot pt;
vector<vector2> pairs;
pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );
pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );
pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );
pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );
pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );
pt.draw( &pairs );
system( "pause" );
return 0;
}
| |
c1016 | #include <iostream>
#include <string>
#include <iterator>
#include <regex>
int main()
{
std::regex re(".* string$");
std::string s = "Hi, I am a string";
if (std::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
std::regex re2(" a.*a");
std::smatch match;
if (std::regex_search(s, match, re2))
{
std::cout << "Matched " << match.length()
<< " characters starting at " << match.position() << ".\n";
std::cout << "Matched character sequence: \""
<< match.str() << "\"\n";
}
else
{
std::cout << "Oops - not found?\n";
}
std::string dest_string;
std::regex_replace(std::back_inserter(dest_string),
s.begin(), s.end(),
re2,
"'m now a changed");
std::cout << dest_string << std::endl;
}
| |
c1017 | #include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {
int i;
GuessNumberIterator() { }
GuessNumberIterator(int _i) : i(_i) { }
GuessNumberIterator& operator++() { ++i; return *this; }
GuessNumberIterator operator++(int) {
GuessNumberIterator tmp = *this; ++(*this); return tmp; }
bool operator==(const GuessNumberIterator& y) { return i == y.i; }
bool operator!=(const GuessNumberIterator& y) { return i != y.i; }
int operator*() {
std::cout << "Is your number less than or equal to " << i << "? ";
std::string s;
std::cin >> s;
return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;
}
GuessNumberIterator& operator--() { --i; return *this; }
GuessNumberIterator operator--(int) {
GuessNumberIterator tmp = *this; --(*this); return tmp; }
GuessNumberIterator& operator+=(int n) { i += n; return *this; }
GuessNumberIterator& operator-=(int n) { i -= n; return *this; }
GuessNumberIterator operator+(int n) {
GuessNumberIterator tmp = *this; return tmp += n; }
GuessNumberIterator operator-(int n) {
GuessNumberIterator tmp = *this; return tmp -= n; }
int operator-(const GuessNumberIterator &y) { return i - y.i; }
int operator[](int n) { return *(*this + n); }
bool operator<(const GuessNumberIterator &y) { return i < y.i; }
bool operator>(const GuessNumberIterator &y) { return i > y.i; }
bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }
bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }
};
inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }
const int lower = 0;
const int upper = 100;
int main() {
std::cout << "Instructions:\n"
<< "Think of integer number from " << lower << " (inclusive) to "
<< upper << " (exclusive) and\n"
<< "I will guess it. After each guess, I will ask you if it is less than\n"
<< "or equal to some number, and you will respond with \"yes\" or \"no\".\n";
int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;
std::cout << "Your number is " << answer << ".\n";
return 0;
}
| |
c1018 | #include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "a", "b", "c" };
std::unordered_map<std::string, std::string> hash;
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
}
| |
c1019 | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
| |
c1020 | #include <windows.h>
#include <string>
#include <math.h>
using namespace std;
const float PI = 3.1415926536f;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
void *pBits;
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 setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD* dwpBits;
DWORD wb;
HANDLE file;
GetObject( bmp, sizeof( bitmap ), &bitmap );
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 );
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() { return hdc; }
int getWidth() { return width; }
int getHeight() { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
int width, height;
};
class vector2
{
public:
vector2() { x = y = 0; }
vector2( int a, int b ) { x = a; y = b; }
void set( int a, int b ) { x = a; y = b; }
void rotate( float angle_r )
{
float _x = static_cast<float>( x ),
_y = static_cast<float>( y ),
s = sinf( angle_r ),
c = cosf( angle_r ),
a = _x * c - _y * s,
b = _x * s + _y * c;
x = static_cast<int>( a );
y = static_cast<int>( b );
}
int x, y;
};
class fractalTree
{
public:
fractalTree() { _ang = DegToRadian( 24.0f ); }
float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }
void create( myBitmap* bmp )
{
_bmp = bmp;
float line_len = 130.0f;
vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );
MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );
sp.y -= static_cast<int>( line_len );
LineTo( _bmp->getDC(), sp.x, sp.y);
drawRL( &sp, line_len, 0, true );
drawRL( &sp, line_len, 0, false );
}
private:
void drawRL( vector2* sp, float line_len, float a, bool rg )
{
line_len *= .75f;
if( line_len < 2.0f ) return;
MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );
vector2 r( 0, static_cast<int>( line_len ) );
if( rg ) a -= _ang;
else a += _ang;
r.rotate( a );
r.x += sp->x; r.y = sp->y - r.y;
LineTo( _bmp->getDC(), r.x, r.y );
drawRL( &r, line_len, a, true );
drawRL( &r, line_len, a, false );
}
myBitmap* _bmp;
float _ang;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
myBitmap bmp;
bmp.create( 640, 512 );
bmp.setPenColor( RGB( 255, 255, 0 ) );
fractalTree tree;
tree.create( &bmp );
BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );
bmp.saveBitmap( "f:
system( "pause" );
return 0;
}
| |
c1021 | #include <windows.h>
class pinstripe
{
public:
pinstripe() { createColors(); }
void setDimensions( int x, int y ) { _mw = x; _mh = y; }
void createColors()
{
colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );
colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 );
colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 );
colors[7] = RGB( 255, 255, 255 );
}
void draw( HDC dc )
{
HPEN pen;
int lh = _mh / 4, row, cp;
for( int lw = 1; lw < 5; lw++ )
{
cp = 0;
row = ( lw - 1 ) * lh;
for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )
{
pen = CreatePen( PS_SOLID, lw, colors[cp] );
++cp %= 8;
SelectObject( dc, pen );
MoveToEx( dc, x, row, NULL );
LineTo( dc, x, row + lh );
DeleteObject( pen );
}
}
}
private:
int _mw, _mh;
DWORD colors[8];
};
pinstripe pin;
void PaintWnd( HWND hWnd )
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint( hWnd, &ps );
pin.draw( hdc );
EndPaint( hWnd, &ps );
}
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_PAINT: PaintWnd( hWnd ); break;
default:
return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_CLR_PS_";
RegisterClassEx( &wcex );
return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );
}
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
srand( GetTickCount() );
HWND hwnd = InitAll( hInstance );
if( !hwnd ) return -1;
int mw = GetSystemMetrics( SM_CXSCREEN ),
mh = GetSystemMetrics( SM_CYSCREEN );
pin.setDimensions( mw, mh );
RECT rc = { 0, 0, mw, mh };
AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );
int w = rc.right - rc.left,
h = rc.bottom - rc.top;
int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),
posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );
SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );
ShowWindow( hwnd, nCmdShow );
UpdateWindow( hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_CLR_PS_", hInstance );
}
| |
c1022 | #include <iostream>
#include <cstdint>
struct Date {
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
};
constexpr bool leap(int year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const std::string& weekday(const Date& date) {
static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const std::string days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"
};
unsigned const c = date.year/100, r = date.year%100;
unsigned const s = r/12, t = r%12;
unsigned const c_anchor = (5 * (c%4) + 2) % 7;
unsigned const doom = (s + t + t/4 + c_anchor) % 7;
unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const std::string months[] = {"",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
for (const Date& d : dates) {
std::cout << months[d.month] << " " << (int)d.day << ", " << d.year;
std::cout << (d.year > 2021 ? " will be " : " was ");
std::cout << "on a " << weekday(d) << std::endl;
}
return 0;
}
| |
c1023 | #include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
template <typename iterator>
void cocktail_shaker_sort(iterator begin, iterator end) {
if (begin == end)
return;
for (--end; begin < end; ) {
iterator new_begin = end;
iterator new_end = begin;
for (iterator i = begin; i < end; ++i) {
iterator j = i + 1;
if (*j < *i) {
std::iter_swap(i, j);
new_end = i;
}
}
end = new_end;
for (iterator i = end; i > begin; --i) {
iterator j = i - 1;
if (*i < *j) {
std::iter_swap(i, j);
new_begin = i;
}
}
begin = new_begin;
}
}
template <typename iterator>
void print(iterator begin, iterator end) {
if (begin == end)
return;
std::cout << *begin++;
while (begin != end)
std::cout << ' ' << *begin++;
std::cout << '\n';
}
int main() {
std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};
std::cout << "before: ";
print(v.begin(), v.end());
cocktail_shaker_sort(v.begin(), v.end());
assert(std::is_sorted(v.begin(), v.end()));
std::cout << "after: ";
print(v.begin(), v.end());
return 0;
}
| |
c1024 | #ifndef __wxPendulumDlg_h__
#define __wxPendulumDlg_h__
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/dialog.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/timer.h>
#include <wx/dcbuffer.h>
#include <cmath>
class wxPendulumDlgApp : public wxApp
{
public:
bool OnInit();
int OnExit();
};
class wxPendulumDlg : public wxDialog
{
public:
wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);
virtual ~wxPendulumDlg();
void wxPendulumDlgPaint(wxPaintEvent& event);
void wxPendulumDlgSize(wxSizeEvent& event);
void OnTimer(wxTimerEvent& event);
private:
wxTimer *m_timer;
unsigned int m_uiLength;
double m_Angle;
double m_AngleVelocity;
enum wxIDs
{
ID_WXTIMER1 = 1001,
ID_DUMMY_VALUE_
};
void OnClose(wxCloseEvent& event);
void CreateGUIControls();
DECLARE_EVENT_TABLE()
};
#endif
| |
c1025 | #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>
uint32_t gray_encode(uint32_t b)
{
return b ^ (b >> 1);
}
uint32_t gray_decode(uint32_t g)
{
for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
{
if (g & bit) g ^= bit >> 1;
}
return g;
}
std::string to_binary(int value)
{
const std::bitset<32> bs(value);
const std::string str(bs.to_string());
const size_t pos(str.find('1'));
return pos == std::string::npos ? "0" : str.substr(pos);
}
int main()
{
std::cout << "Number\tBinary\tGray\tDecoded\n";
for (uint32_t n = 0; n < 32; ++n)
{
uint32_t g = gray_encode(n);
assert(gray_decode(g) == n);
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
}
}
| |
c1026 | #include <iostream>
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif
int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return 0;
}
| |
c1027 | #include <algorithm>
#include <iterator>
#include <iostream>
template<typename RandomAccessIterator>
void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {
std::make_heap(begin, end);
std::sort_heap(begin, end);
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
heap_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| |
c1028 | #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
enum { unique_count = pip_count * suite_count };
card(suite_type s, pip_type p): value(s + suite_count * p) {}
explicit card(unsigned char v = 0): value(v) {}
pip_type pip() { return pip_type(value / suite_count); }
suite_type suite() { return suite_type(value % suite_count); }
private:
unsigned char value;
};
const char* const pip_names[] =
{ "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"jack", "queen", "king", "ace" };
std::ostream& operator<<(std::ostream& os, card::pip_type pip)
{
return os << pip_names[pip];
}
const char* const suite_names[] =
{ "hearts", "spades", "diamonds", "clubs" };
std::ostream& operator<<(std::ostream& os, card::suite_type suite)
{
return os << suite_names[suite];
}
std::ostream& operator<<(std::ostream& os, card c)
{
return os << c.pip() << " of " << c.suite();
}
class deck
{
public:
deck()
{
for (int i = 0; i < card::unique_count; ++i) {
cards.push_back(card(i));
}
}
void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }
card deal() { card c = cards.front(); cards.pop_front(); return c; }
typedef std::deque<card>::const_iterator const_iterator;
const_iterator begin() const { return cards.cbegin(); }
const_iterator end() const { return cards.cend(); }
private:
std::deque<card> cards;
};
inline std::ostream& operator<<(std::ostream& os, const deck& d)
{
std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n"));
return os;
}
}
| |
c1029 | #include <array>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
template <typename Array>
void demonstrate(Array& array)
{
array[2] = "Three";
array.at(1) = "Two";
std::reverse(begin(array), end(array));
std::for_each(begin(array), end(array),
[](typename Array::value_type const& element)
{
std::cout << element << ' ';
});
std::cout << '\n';
}
int main()
{
auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
auto dynamic_array = std::vector<std::string>{ "One", "Four" };
dynamic_array.push_back("Eight");
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
}
| |
c1030 |
#include <cstdint>
#include <cstdlib>
#include <cstdio>
static constexpr int32_t bct_low_bits = 0x55555555;
static int32_t bct_decrement(int32_t v) {
--v;
return v ^ (v & (v>>1) & bct_low_bits);
}
int main (int argc, char *argv[])
{
const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;
if (n < 0 || 9 < n) {
std::printf("N out of range (use 0..9): %ld\n", long(n));
return 1;
}
const int32_t size_bct = 1<<(n*2);
int32_t y = size_bct;
do {
y = bct_decrement(y);
int32_t x = size_bct;
do {
x = bct_decrement(x);
std::putchar((x & y & bct_low_bits) ? ' ' : '#');
} while (0 < x);
std::putchar('\n');
} while (0 < y);
return 0;
}
| |
c1031 | #include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
Predicate p) {
std::random_device rd;
std::mt19937 generator(rd());
while (!std::is_sorted(begin, end, p)) {
std::shuffle(begin, end, generator);
}
}
template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bogo_sort(
begin, end,
std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bogo_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| |
c1032 | #include <iostream>
#include <optional>
#include <ranges>
#include <string>
#include <vector>
using namespace std;
struct Patient
{
string ID;
string LastName;
};
struct Visit
{
string PatientID;
string Date;
optional<float> Score;
};
int main(void)
{
auto patients = vector<Patient> {
{"1001", "Hopper"},
{"4004", "Wirth"},
{"3003", "Kemeny"},
{"2002", "Gosling"},
{"5005", "Kurtz"}};
auto visits = vector<Visit> {
{"2002", "2020-09-10", 6.8},
{"1001", "2020-09-17", 5.5},
{"4004", "2020-09-24", 8.4},
{"2002", "2020-10-08", },
{"1001", "" , 6.6},
{"3003", "2020-11-12", },
{"4004", "2020-11-05", 7.0},
{"1001", "2020-11-19", 5.3}};
sort(patients.begin(), patients.end(),
[](const auto& a, const auto&b){ return a.ID < b.ID;});
cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n";
for(const auto& patient : patients)
{
string lastVisit;
float sum = 0;
int numScores = 0;
auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};
for(const auto& visit : visits | views::filter( patientFilter ))
{
if(visit.Score)
{
sum += *visit.Score;
numScores++;
}
lastVisit = max(lastVisit, visit.Date);
}
cout << "| " << patient.ID << " | ";
cout.width(8); cout << patient.LastName << " | ";
cout.width(10); cout << lastVisit << " | ";
if(numScores > 0)
{
cout.width(9); cout << sum << " | ";
cout.width(9); cout << (sum / float(numScores));
}
else cout << " | ";
cout << " |\n";
}
}
| |
c1033 | #include <iomanip>
#include <iostream>
typedef double F(double,double);
void euler(F f, double y0, double a, double b, double h)
{
double y = y0;
for (double t = a; t < b; t += h)
{
std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n";
y += h * f(t, y);
}
std::cout << "done\n";
}
double newtonCoolingLaw(double, double t)
{
return -0.07 * (t - 20);
}
int main()
{
euler(newtonCoolingLaw, 100, 0, 100, 2);
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
}
| |
c1034 | #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>
double nextNumber( double number ) {
return number + floor( 0.5 + sqrt( number ) ) ;
}
int main( ) {
std::vector<double> non_squares ;
typedef std::vector<double>::iterator SVI ;
non_squares.reserve( 1000000 ) ;
for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
non_squares.push_back( nextNumber( i ) ) ;
std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
std::ostream_iterator<double>(std::cout, " " ) ) ;
std::cout << '\n' ;
SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
if ( found != non_squares.end( ) ) {
std::cout << "Found a square number in the sequence!\n" ;
std::cout << "It is " << *found << " !\n" ;
}
else {
std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
}
return 0 ;
}
| |
c1035 | #include <iostream>
#include <string>
int main()
{
std::string s = "0123456789";
int const n = 3;
int const m = 4;
char const c = '2';
std::string const sub = "456";
std::cout << s.substr(n, m)<< "\n";
std::cout << s.substr(n) << "\n";
std::cout << s.substr(0, s.size()-1) << "\n";
std::cout << s.substr(s.find(c), m) << "\n";
std::cout << s.substr(s.find(sub), m) << "\n";
}
| |
c1036 | #include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
class jortSort {
public:
template<class T>
bool jort_sort( T* o, size_t s ) {
T* n = copy_array( o, s );
sort_array( n, s );
bool r = false;
if( n ) {
r = check( o, n, s );
delete [] n;
}
return r;
}
private:
template<class T>
T* copy_array( T* o, size_t s ) {
T* z = new T[s];
memcpy( z, o, s * sizeof( T ) );
return z;
}
template<class T>
void sort_array( T* n, size_t s ) {
std::sort( n, n + s );
}
template<class T>
bool check( T* n, T* o, size_t s ) {
for( size_t x = 0; x < s; x++ )
if( n[x] != o[x] ) return false;
return true;
}
};
jortSort js;
template<class T>
void displayTest( T* o, size_t s ) {
std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) );
std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n";
}
int main( int argc, char* argv[] ) {
const size_t s = 5;
std::string oStr[] = { "5", "A", "D", "R", "S" };
displayTest( oStr, s );
std::swap( oStr[0], oStr[1] );
displayTest( oStr, s );
int oInt[] = { 1, 2, 3, 4, 5 };
displayTest( oInt, s );
std::swap( oInt[0], oInt[1] );
displayTest( oInt, s );
return 0;
}
| |
c1037 | #include <iostream>
bool is_leap_year(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
int main() {
for (auto year : {1900, 1994, 1996, 1997, 2000}) {
std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n";
}
}
| |
c1038 | #include <boost/multiprecision/gmp.hpp>
#include <iostream>
using namespace boost::multiprecision;
mpz_int p(uint n, uint p) {
mpz_int r = 1;
mpz_int k = n - p;
while (n > k)
r *= n--;
return r;
}
mpz_int c(uint n, uint k) {
mpz_int r = p(n, k);
while (k)
r /= k--;
return r;
}
int main() {
for (uint i = 1u; i < 12u; i++)
std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl;
for (uint i = 10u; i < 60u; i += 10u)
std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl;
return 0;
}
| |
c1039 | #include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
void lexicographical_sort(std::vector<int>& numbers) {
std::vector<std::string> strings(numbers.size());
std::transform(numbers.begin(), numbers.end(), strings.begin(),
[](int i) { return std::to_string(i); });
std::sort(strings.begin(), strings.end());
std::transform(strings.begin(), strings.end(), numbers.begin(),
[](const std::string& s) { return std::stoi(s); });
}
std::vector<int> lexicographically_sorted_vector(int n) {
std::vector<int> numbers(n >= 1 ? n : 2 - n);
std::iota(numbers.begin(), numbers.end(), std::min(1, n));
lexicographical_sort(numbers);
return numbers;
}
template <typename T>
void print_vector(std::ostream& out, const std::vector<T>& v) {
out << '[';
if (!v.empty()) {
auto i = v.begin();
out << *i++;
for (; i != v.end(); ++i)
out << ',' << *i;
}
out << "]\n";
}
int main(int argc, char** argv) {
for (int i : { 0, 5, 13, 21, -22 }) {
std::cout << i << ": ";
print_vector(std::cout, lexicographically_sorted_vector(i));
}
return 0;
}
| |
c1040 | #include <string>
#include <iostream>
using std::string;
const char* smallNumbers[] = {
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
string spellHundreds(unsigned n) {
string res;
if (n > 99) {
res = smallNumbers[n/100];
res += " hundred";
n %= 100;
if (n) res += " and ";
}
if (n >= 20) {
static const char* Decades[] = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};
res += Decades[n/10];
n %= 10;
if (n) res += "-";
}
if (n < 20 && n > 0)
res += smallNumbers[n];
return res;
}
const char* thousandPowers[] = {
" billion", " million", " thousand", "" };
typedef unsigned long Spellable;
string spell(Spellable n) {
if (n < 20) return smallNumbers[n];
string res;
const char** pScaleName = thousandPowers;
Spellable scaleFactor = 1000000000;
while (scaleFactor > 0) {
if (n >= scaleFactor) {
Spellable h = n / scaleFactor;
res += spellHundreds(h) + *pScaleName;
n %= scaleFactor;
if (n) res += ", ";
}
scaleFactor /= 1000;
++pScaleName;
}
return res;
}
int main() {
#define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl;
SPELL_IT( 99);
SPELL_IT( 300);
SPELL_IT( 310);
SPELL_IT( 1501);
SPELL_IT( 12609);
SPELL_IT( 512609);
SPELL_IT(43112609);
SPELL_IT(1234567890);
return 0;
}
| |
c1041 | #include <iostream>
#include <algorithm>
#include <string>
#include <list>
using namespace std;
bool cmp(const string& a, const string& b)
{
return b.length() < a.length();
}
void compareAndReportStringsLength(list<string> listOfStrings)
{
if (!listOfStrings.empty())
{
char Q = '"';
string has_length(" has length ");
string predicate_max(" and is the longest string");
string predicate_min(" and is the shortest string");
string predicate_ave(" and is neither the longest nor the shortest string");
list<string> ls(listOfStrings);
ls.sort(cmp);
int max = ls.front().length();
int min = ls.back().length();
for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
{
int length = s->length();
string* predicate;
if (length == max)
predicate = &predicate_max;
else if (length == min)
predicate = &predicate_min;
else
predicate = &predicate_ave;
cout << Q << *s << Q << has_length << length << *predicate << endl;
}
}
}
int main(int argc, char* argv[])
{
list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(listOfStrings);
return EXIT_SUCCESS;
}
| |
c1042 | #include <time.h>
#include <iostream>
using namespace std;
const int MAX = 126;
class shell
{
public:
shell()
{ _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }
void sort( int* a, int count )
{
_cnt = count;
for( int x = 0; x < 9; x++ )
if( count > _gap[x] )
{ _idx = x; break; }
sortIt( a );
}
private:
void sortIt( int* arr )
{
bool sorted = false;
while( true )
{
sorted = true;
int st = 0;
for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
{
if( arr[st] > arr[x] )
{ swap( arr[st], arr[x] ); sorted = false; }
st = x;
}
if( ++_idx >= 8 ) _idx = 8;
if( sorted && _idx == 8 ) break;
}
}
void swap( int& a, int& b ) { int t = a; a = b; b = t; }
int _gap[9], _idx, _cnt;
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];
for( int x = 0; x < MAX; x++ )
arr[x] = rand() % MAX - rand() % MAX;
cout << " Before: \n=========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl; shell s; s.sort( arr, MAX );
cout << " After: \n========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl << endl; return system( "pause" );
}
| |
c1043 | #include <iostream>
#include <list>
int main ()
{
std::list<int> numbers {1, 5, 7, 0, 3, 2};
numbers.insert(numbers.begin(), 9);
numbers.insert(numbers.end(), 4);
auto it = std::next(numbers.begin(), numbers.size() / 2);
numbers.insert(it, 6);
for(const auto& i: numbers)
std::cout << i << ' ';
std::cout << '\n';
}
| |
c1044 | #include <fstream>
#include <iostream>
int main()
{
std::ifstream input("filename.txt", std::ios_base::binary);
if (!input)
{
std::cerr << "error: can't open file\n";
return -1;
}
size_t count[256];
std::fill_n(count, 256, 0);
for (char c; input.get(c); ++count[uint8_t(c)])
;
for (size_t i = 0; i < 256; ++i)
{
if (count[i] && isgraph(i))
{
std::cout << char(i) << " = " << count[i] << '\n';
}
}
}
| |
c1045 | #include<iostream>
#include<vector>
#include<numeric>
#include<functional>
class
{
public:
int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}
private:
int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }
int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}
}combinations;
int main()
{
static constexpr int treatment = 9;
const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);
std::function<int (int, int, int)> pick;
pick = [&](int n, int from, int accumulated)
{
if(n == 0)
return accumulated > treated ? 1 : 0;
else
return pick(n - 1, from - 1, accumulated + data[from - 1]) +
(from > n ? pick(n, from - 1, accumulated) : 0);
};
int total = combinations(data.size(), treatment);
int greater = pick(treatment, data.size(), 0);
int lesser = total - greater;
std::cout << "<= : " << 100.0 * lesser / total << "% " << lesser << std::endl
<< " > : " << 100.0 * greater / total << "% " << greater << std::endl;
}
| |
c1046 | #include <iomanip>
#include <iostream>
#include <vector>
constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;
int mobiusFunction(int n) {
if (!MU.empty()) {
return MU[n];
}
MU.resize(MU_MAX + 1, 1);
int root = sqrt(MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1) {
for (int j = i; j <= MU_MAX; j += i) {
MU[j] *= -i;
}
for (int j = i * i; j <= MU_MAX; j += i * i) {
MU[j] = 0;
}
}
}
for (int i = 2; i <= MU_MAX; i++) {
if (MU[i] == i) {
MU[i] = 1;
} else if (MU[i] == -i) {
MU[i] = -1;
} else if (MU[i] < 0) {
MU[i] = 1;
} else if (MU[i] > 0) {
MU[i] = -1;
}
}
return MU[n];
}
int main() {
std::cout << "First 199 terms of the möbius function are as follows:\n ";
for (int n = 1; n < 200; n++) {
std::cout << std::setw(2) << mobiusFunction(n) << " ";
if ((n + 1) % 20 == 0) {
std::cout << '\n';
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.