_id
stringlengths
2
5
text
stringlengths
7
10.9k
title
stringclasses
1 value
c553
for (int i = 1; i < 10; i += 2) std::cout << i << std::endl;
c554
#include <iostream> #include <cmath> #include <chrono> using namespace std; using namespace chrono; int main() { auto st = high_resolution_clock::now(); const uint i5 = 100000, i4 = 10000, i3 = 1000, i2 = 100, i1 = 10; uint p4[] = { 0, 1, 32, 243 }, nums[10], p5[10], t = 0, m5, m4, m3, m2, m1, m0; m5 = m4 = m3 = m2 = m1 = m0 = 0; for (uint i = 0; i < 10; i++) p5[i] = pow(nums[i] = i, 5); for (auto i : p4) { auto im = m5, ip = i; m4 = 0; for (auto j : p5) { auto jm = im + m4, jp = ip + j; m3 = 0; for (auto k : p5) { auto km = jm + m3, kp = jp + k; m2 = 0; for (auto l : p5) { auto lm = km + m2, lp = kp + l; m1 = 0; for (auto m : p5) { auto mm = lm + m1, mp = lp + m; m0 = 0; for (auto n : p5) { auto nm = mm + m0++; if (nm == mp + n && nm > 1) t += nm; } m1 += i1; } m2 += i2; } m3 += i3; } m4 += i4; } m5 += i5; } auto et = high_resolution_clock::now(); std::cout << t << " " << duration_cast<nanoseconds>(et - st).count() / 1000.0 << " μs"; }
c555
#ifndef CLICKCOUNTER_H #define CLICKCOUNTER_H #include <QWidget> class QLabel ; class QPushButton ; class QVBoxLayout ; class Counter : public QWidget { Q_OBJECT public : Counter( QWidget * parent = 0 ) ; private : int number ; QLabel *countLabel ; QPushButton *clicker ; QVBoxLayout *myLayout ; private slots : void countClicks( ) ; } ; #endif
c556
#include <iostream> #include <fstream> std::ios::off_type getFileSize(const char *filename) { std::ifstream f(filename); std::ios::pos_type begin = f.tellg(); f.seekg(0, std::ios::end); std::ios::pos_type end = f.tellg(); return end - begin; } int main() { std::cout << getFileSize("input.txt") << std::endl; std::cout << getFileSize("/input.txt") << std::endl; return 0; }
c557
#include <iostream> #include "prime_sieve.hpp" bool is_left_truncatable(const prime_sieve& sieve, int p) { for (int n = 10, q = p; p > n; n *= 10) { if (!sieve.is_prime(p % n) || q == p % n) return false; q = p % n; } return true; } bool is_right_truncatable(const prime_sieve& sieve, int p) { for (int q = p/10; q > 0; q /= 10) { if (!sieve.is_prime(q)) return false; } return true; } int main() { const int limit = 1000000; prime_sieve sieve(limit + 1); int largest_left = 0; int largest_right = 0; for (int p = limit; p >= 2; --p) { if (sieve.is_prime(p) && is_left_truncatable(sieve, p)) { largest_left = p; break; } } for (int p = limit; p >= 2; --p) { if (sieve.is_prime(p) && is_right_truncatable(sieve, p)) { largest_right = p; break; } } std::cout << "Largest left truncatable prime is " << largest_left << '\n'; std::cout << "Largest right truncatable prime is " << largest_right << '\n'; return 0; }
c558
#include <iostream> #include <thread> #include <chrono> int main() { unsigned long microseconds; std::cin >> microseconds; std::cout << "Sleeping..." << std::endl; std::this_thread::sleep_for(std::chrono::microseconds(microseconds)); std::cout << "Awake!\n"; }
c559
#include <iostream> int main() { bool is_open[100] = { false }; for (int pass = 0; pass < 100; ++pass) for (int door = pass; door < 100; door += pass+1) is_open[door] = !is_open[door]; for (int door = 0; door < 100; ++door) std::cout << "door #" << door+1 << (is_open[door]? " is open." : " is closed.") << std::endl; return 0; }
c560
#include <iomanip> #include <iostream> #include <vector> #define _USE_MATH_DEFINES #include <math.h> struct Time { int hour, minute, second; friend std::ostream &operator<<(std::ostream &, const Time &); }; std::ostream &operator<<(std::ostream &os, const Time &t) { return os << std::setfill('0') << std::setw(2) << t.hour << ':' << std::setw(2) << t.minute << ':' << std::setw(2) << t.second; } double timeToDegrees(Time &&t) { return 360.0 * t.hour / 24.0 + 360.0 * t.minute / (24 * 60.0) + 360.0 * t.second / (24 * 3600.0); } Time degreesToTime(double angle) { while (angle < 0.0) { angle += 360.0; } while (angle > 360.0) { angle -= 360.0; } double totalSeconds = 24.0 * 60 * 60 * angle / 360; Time t; t.second = (int)totalSeconds % 60; t.minute = ((int)totalSeconds % 3600 - t.second) / 60; t.hour = (int)totalSeconds / 3600; return t; } double meanAngle(const std::vector<double> &angles) { double yPart = 0.0, xPart = 0.0; for (auto a : angles) { xPart += cos(a * M_PI / 180); yPart += sin(a * M_PI / 180); } return atan2(yPart / angles.size(), xPart / angles.size()) * 180 / M_PI; } int main() { std::vector<double> tv; tv.push_back(timeToDegrees({ 23, 0, 17 })); tv.push_back(timeToDegrees({ 23, 40, 20 })); tv.push_back(timeToDegrees({ 0, 12, 45 })); tv.push_back(timeToDegrees({ 0, 17, 19 })); double ma = meanAngle(tv); auto mt = degreesToTime(ma); std::cout << mt << '\n'; return 0; }
c561
#include <future> #include <iostream> #include <fstream> #include <mutex> #include <queue> #include <string> #include <thread> struct lock_queue { std::queue<std::string> q; std::mutex mutex; }; void reader(std::string filename, std::future<size_t> lines, lock_queue& out) { std::string line; std::ifstream in(filename); while(std::getline(in, line)) { line += '\n'; std::lock_guard<std::mutex> lock(out.mutex); out.q.push(line); } { std::lock_guard<std::mutex> lock(out.mutex); out.q.push(""); } lines.wait(); std::cout << "\nPrinted " << lines.get() << " lines\n"; } void printer(std::promise<size_t> lines, lock_queue& in) { std::string s; size_t line_n = 0; bool print = false; while(true) { { std::lock_guard<std::mutex> lock(in.mutex); if(( print = not in.q.empty() )) { s = in.q.front(); in.q.pop(); } } if(print) { if(s == "") break; std::cout << s; ++line_n; print = false; } } lines.set_value(line_n); } int main() { lock_queue queue; std::promise<size_t> promise; std::thread t1(reader, "input.txt", promise.get_future(), std::ref(queue)); std::thread t2(printer, std::move(promise), std::ref(queue)); t1.join(); t2.join(); }
c562
#include <iostream> #include <vector> typedef std::vector<std::vector<int>> vv; vv pascal_upper(int n) { vv matrix(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i > j) matrix[i].push_back(0); else if (i == j || i == 0) matrix[i].push_back(1); else matrix[i].push_back(matrix[i - 1][j - 1] + matrix[i][j - 1]); } } return matrix; } vv pascal_lower(int n) { vv matrix(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i < j) matrix[i].push_back(0); else if (i == j || j == 0) matrix[i].push_back(1); else matrix[i].push_back(matrix[i - 1][j - 1] + matrix[i - 1][j]); } } return matrix; } vv pascal_symmetric(int n) { vv matrix(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == 0 || j == 0) matrix[i].push_back(1); else matrix[i].push_back(matrix[i][j - 1] + matrix[i - 1][j]); } } return matrix; } void print_matrix(vv matrix) { for (std::vector<int> v: matrix) { for (int i: v) { std::cout << " " << i; } std::cout << std::endl; } } int main() { std::cout << "PASCAL UPPER MATRIX" << std::endl; print_matrix(pascal_upper(5)); std::cout << "PASCAL LOWER MATRIX" << std::endl; print_matrix(pascal_lower(5)); std::cout << "PASCAL SYMMETRIC MATRIX" << std::endl; print_matrix(pascal_symmetric(5)); }
c563
#include <iostream> int main() { std::cerr << "Goodbye, World!\n"; }
c564
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostream& os, const char* name) const; private: int max_print; int count1 = 0; int count2 = 0; std::vector<int> primes; }; void prime_info::add_prime(int prime) { ++count2; if (prime < limit1) ++count1; if (count2 <= max_print) primes.push_back(prime); } void prime_info::print(std::ostream& os, const char* name) const { os << "First " << max_print << " " << name << " primes: "; std::copy(primes.begin(), primes.end(), std::ostream_iterator<int>(os, " ")); os << '\n'; os << "Number of " << name << " primes below " << limit1 << ": " << count1 << '\n'; os << "Number of " << name << " primes below " << limit2 << ": " << count2 << '\n'; } int main() { prime_sieve sieve(limit2 + 100); std::cout.imbue(std::locale("")); prime_info strong_primes(36); prime_info weak_primes(37); int p1 = 2, p2 = 3; for (int p3 = 5; p2 < limit2; ++p3) { if (!sieve.is_prime(p3)) continue; int diff = p1 + p3 - 2 * p2; if (diff < 0) strong_primes.add_prime(p2); else if (diff > 0) weak_primes.add_prime(p2); p1 = p2; p2 = p3; } strong_primes.print(std::cout, "strong"); weak_primes.print(std::cout, "weak"); return 0; }
c565
#include <iomanip> #include <iostream> #include <fstream> #include <map> #include <sstream> #include <string> #include <vector> std::vector<std::string> split(const std::string& str, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(str); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } int main() { using namespace std; string line; int i = 0; ifstream in("days_of_week.txt"); if (in.is_open()) { while (getline(in, line)) { i++; if (line.empty()) { continue; } auto days = split(line, ' '); if (days.size() != 7) { throw std::runtime_error("There aren't 7 days in line " + i); } map<string, int> temp; for (auto& day : days) { if (temp.find(day) != temp.end()) { cerr << " ∞ " << line << '\n'; continue; } temp[day] = 1; } int len = 1; while (true) { temp.clear(); for (auto& day : days) { string key = day.substr(0, len); if (temp.find(key) != temp.end()) { break; } temp[key] = 1; } if (temp.size() == 7) { cout << setw(2) << len << " " << line << '\n'; break; } len++; } } } return 0; }
c566
#include<iostream> #include<csignal> #include<cstdlib> using namespace std; void fpe_handler(int signal) { cerr << "Floating Point Exception: division by zero" << endl; exit(signal); } int main() { signal(SIGFPE, fpe_handler); int a = 1; int b = 0; cout << a/b << endl; return 0; }
c567
#include <algorithm> #include <string> std::all_of( ++(strings.begin()), strings.end(), [&](std::string a){ return a == strings.front(); } ) std::is_sorted( strings.begin(), strings.end(), [](std::string a, std::string b){ return !(b < a); }) )
c568
#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> bool ordered(const std::string &word) { return std::is_sorted(word.begin(), word.end()); } int main() { std::ifstream infile("unixdict.txt"); if (!infile) { std::cerr << "Can't open word file\n"; return -1; } std::vector<std::string> words; std::string word; int longest = 0; while (std::getline(infile, word)) { int length = word.length(); if (length < longest) continue; if (ordered(word)) { if (longest < length) { longest = length; words.clear(); } words.push_back(word); } } std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n")); }
c569
#include <iostream> #include <chrono> int main() { int fizz = 0, buzz = 0, fizzbuzz = 0; bool isFizz = false; auto startTime = std::chrono::high_resolution_clock::now(); for (unsigned int i = 1; i <= 4000000000; i++) { isFizz = false; if (i % 3 == 0) { isFizz = true; fizz++; } if (i % 5 == 0) { if (isFizz) { fizz--; fizzbuzz++; } else { buzz++; } } } auto endTime = std::chrono::high_resolution_clock::now(); auto totalTime = endTime - startTime; printf("\t fizz : %d, buzz: %d, fizzbuzz: %d, duration %lld milliseconds\n", fizz, buzz, fizzbuzz, (totalTime / std::chrono::milliseconds(1))); return 0; }
c570
#include <list> #include <boost/any.hpp> typedef std::list<boost::any> anylist; void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator; iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
c571
struct MyException { };
c572
#include <QtSql> #include <iostream> int main(int argc, char *argv[]) { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " data-source user password\n"; return 1; } QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); db.setDatabaseName(argv[1]); if (!db.open(argv[2], argv[3])) { auto error = db.lastError(); std::cerr << "Cannot connect to data source: " << error.text().toStdString() << '\n'; } else { std::cout << "Connected to data source.\n"; QSqlQuery query(db); query.prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?"); query.bindValue(0, "Smith, Steve"); query.bindValue(1, 42); query.bindValue(2, true); query.bindValue(3, 99); if (!query.exec()) { auto error = db.lastError(); std::cerr << "Cannot update database: " << error.text().toStdString() << '\n'; } else { std::cout << "Update succeeded.\n"; } } return 0; }
c573
#include <iostream> #include <vector> constexpr unsigned int LIMIT = 6000; std::vector<bool> primes(unsigned int limit) { std::vector<bool> p(limit + 1, true); unsigned int root = std::sqrt(limit); p[0] = false; p[1] = false; for (size_t i = 2; i <= root; i++) { if (p[i]) { for (size_t j = 2 * i; j <= limit; j += i) { p[j] = false; } } } return p; } bool triplet(const std::vector<bool> &p, unsigned int n) { return n >= 2 && p[n - 1] && p[n + 3] && p[n + 5]; } int main() { std::vector<bool> p = primes(LIMIT); for (size_t i = 2; i < LIMIT; i++) { if (triplet(p, i)) { printf("%4d: %4d, %4d, %4d\n", i, i - 1, i + 3, i + 5); } } return 0; }
c574
class foo_params{ friend void foo(foo_params p); public: foo_params(int r): required_param_(r), optional_x_(0), optional_y_(1), optional_z_(3.1415) {} foo_params& x(int i){ optional_x_=i; return *this; } foo_params& y(int i){ optional_y_=i; return *this; } foo_params& z(float f){ optional_z_=f; return *this; } private: int required_param_; int optional_x_; int optional_y_; float optional_z_; };
c575
#include <iostream> #include <cstdlib> #include <ctime> int main() { std::srand(std::time(0)); int lower, upper, guess; std::cout << "Enter lower limit: "; std::cin >> lower; std::cout << "Enter upper limit: "; std::cin >> upper; int random_number = lower + std::rand() % ((upper + 1) - lower); do { std::cout << "Guess what number I have: "; std::cin >> guess; if (guess > random_number) std::cout << "Your guess is too high\n"; else if (guess < random_number) std::cout << "Your guess is too low\n"; else std::cout << "You got it!\n"; } while (guess != random_number); return 0; }
c576
#include <iostream> #include <sstream> #include <algorithm> using namespace std; template <class S> class BestShuffle { public: BestShuffle() : rd(), g(rd()) {} S operator()(const S& s1) { S s2 = s1; shuffle(s2.begin(), s2.end(), g); for (unsigned i = 0; i < s2.length(); i++) if (s2[i] == s1[i]) for (unsigned j = 0; j < s2.length(); j++) if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) { swap(s2[i], s2[j]); break; } ostringstream os; os << s1 << endl << s2 << " [" << count(s2, s1) << ']'; return os.str(); } private: static int count(const S& s1, const S& s2) { auto count = 0; for (unsigned i = 0; i < s1.length(); i++) if (s1[i] == s2[i]) count++; return count; } random_device rd; mt19937 g; }; int main(int argc, char* arguments[]) { BestShuffle<basic_string<char>> bs; for (auto i = 1; i < argc; i++) cout << bs(basic_string<char>(arguments[i])) << endl; return 0; }
c577
#include <iostream> #include <cstdint> #include <limits> int main (int argc, char *argv[]) { std::cout << std::boolalpha << std::numeric_limits<std::int32_t>::is_modulo << '\n' << std::numeric_limits<std::uint32_t>::is_modulo << '\n' << std::numeric_limits<std::int64_t>::is_modulo << '\n' << std::numeric_limits<std::uint64_t>::is_modulo << '\n' << "Signed 32-bit:\n" << -(-2147483647-1) << '\n' << 2000000000 + 2000000000 << '\n' << -2147483647 - 2147483647 << '\n' << 46341 * 46341 << '\n' << (-2147483647-1) / -1 << '\n' << "Signed 64-bit:\n" << -(-9223372036854775807-1) << '\n' << 5000000000000000000+5000000000000000000 << '\n' << -9223372036854775807 - 9223372036854775807 << '\n' << 3037000500 * 3037000500 << '\n' << (-9223372036854775807-1) / -1 << '\n' << "Unsigned 32-bit:\n" << -4294967295U << '\n' << 3000000000U + 3000000000U << '\n' << 2147483647U - 4294967295U << '\n' << 65537U * 65537U << '\n' << "Unsigned 64-bit:\n" << -18446744073709551615LU << '\n' << 10000000000000000000LU + 10000000000000000000LU << '\n' << 9223372036854775807LU - 18446744073709551615LU << '\n' << 4294967296LU * 4294967296LU << '\n'; return 0; }
c578
#include <algorithm> #include <string> #include <vector> #include <iostream> template<class T> void print(const std::vector<T> &vec) { for (typename std::vector<T>::const_iterator i = vec.begin(); i != vec.end(); ++i) { std::cout << *i; if ((i + 1) != vec.end()) std::cout << ","; } std::cout << std::endl; } int main() { std::string example("Hello"); std::sort(example.begin(), example.end()); do { std::cout << example << '\n'; } while (std::next_permutation(example.begin(), example.end())); std::vector<int> another; another.push_back(1234); another.push_back(4321); another.push_back(1234); another.push_back(9999); std::sort(another.begin(), another.end()); do { print(another); } while (std::next_permutation(another.begin(), another.end())); return 0; }
c579
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), h.begin(), toupper ); istringstream i( h ); copy( istream_iterator<string>( i ), istream_iterator<string>(), back_inserter<vector<string> >( hand ) ); if( hand.size() != 5 ) return "invalid hand."; vector<string>::iterator it = hand.begin(); sort( it, hand.end() ); if( hand.end() != adjacent_find( it, hand.end() ) ) return "invalid hand."; while( it != hand.end() ) { if( ( *it ).length() != 2 ) return "invalid hand."; int n = face.find( ( *it ).at( 0 ) ), l = suit.find( ( *it ).at( 1 ) ); if( n < 0 || l < 0 ) return "invalid hand."; faceCnt[n]++; suitCnt[l]++; it++; } cout << h << ": "; return analyzeHand(); } private: string analyzeHand() { bool p1 = false, p2 = false, t = false, f = false, fl = false, st = false; for( int x = 0; x < 13; x++ ) switch( faceCnt[x] ) { case 2: if( p1 ) p2 = true; else p1 = true; break; case 3: t = true; break; case 4: f = true; } for( int x = 0; x < 4; x++ )if( suitCnt[x] == 5 ){ fl = true; break; } if( !p1 && !p2 && !t && !f ) { int s = 0; for( int x = 0; x < 13; x++ ) { if( faceCnt[x] ) s++; else s = 0; if( s == 5 ) break; } st = ( s == 5 ) || ( s == 4 && faceCnt[0] && !faceCnt[1] ); } if( st && fl ) return "straight-flush"; else if( f ) return "four-of-a-kind"; else if( p1 && t ) return "full-house"; else if( fl ) return "flush"; else if( st ) return "straight"; else if( t ) return "three-of-a-kind"; else if( p1 && p2 ) return "two-pair"; else if( p1 ) return "one-pair"; return "high-card"; } string face, suit; unsigned char faceCnt[13], suitCnt[4]; }; int main( int argc, char* argv[] ) { poker p; cout << p.analyze( "2h 2d 2s ks qd" ) << endl; cout << p.analyze( "2h 5h 7d 8s 9d" ) << endl; cout << p.analyze( "ah 2d 3s 4s 5s" ) << endl; cout << p.analyze( "2h 3h 2d 3s 3d" ) << endl; cout << p.analyze( "2h 7h 2d 3s 3d" ) << endl; cout << p.analyze( "2h 7h 7d 7s 7c" ) << endl; cout << p.analyze( "th jh qh kh ah" ) << endl; cout << p.analyze( "4h 4c kc 5d tc" ) << endl; cout << p.analyze( "qc tc 7c 6c 4c" ) << endl << endl; return system( "pause" ); }
c580
#include <algorithm> #include <iostream> #include <ostream> #include <vector> template<std::size_t> struct int_ {}; template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); } template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); } template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; } template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); } return (beg[m - 1] + beg[m]) / 2.0; } template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end()); auto cbeg = c.cbegin(); auto cend = c.cend(); auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend); return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); } int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (auto & c : cs) { cout << fivenum(c) << endl; } return 0; }
c581
#ifndef PROCESSING_FLOODFILLALGORITHM_H_ #define PROCESSING_FLOODFILLALGORITHM_H_ #include <opencv2/opencv.hpp> #include <string.h> #include <queue> using namespace cv; using namespace std; class FloodFillAlgorithm { public: FloodFillAlgorithm(Mat* image) : image(image) { } virtual ~FloodFillAlgorithm(); void flood(Point startPoint, Scalar tgtColor, Scalar loDiff); void flood(Point startPoint, Mat* tgtMat); protected: Mat* image; private: bool insideImage(Point p); }; #endif
c582
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { } Wheel(std::initializer_list<char> data) : values(data), index(0) { if (values.size() < 1) { throw new std::runtime_error("Not enough elements"); } } char front() { return values[index]; } void popFront() { index = (index + 1) % values.size(); } }; struct NamedWheel { private: std::map<char, Wheel> wheels; public: void put(char c, Wheel w) { wheels[c] = w; } char front(char c) { char v = wheels[c].front(); while ('A' <= v && v <= 'Z') { v = wheels[v].front(); } return v; } void popFront(char c) { auto v = wheels[c].front(); wheels[c].popFront(); while ('A' <= v && v <= 'Z') { auto d = wheels[v].front(); wheels[v].popFront(); v = d; } } }; void group1() { Wheel w({ '1', '2', '3' }); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << w.front(); w.popFront(); } std::cout << '\n'; } void group2() { Wheel a({ '1', 'B', '2' }); Wheel b({ '3', '4' }); NamedWheel n; n.put('A', a); n.put('B', b); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << n.front('A'); n.popFront('A'); } std::cout << '\n'; } void group3() { Wheel a({ '1', 'D', 'D' }); Wheel d({ '6', '7', '8' }); NamedWheel n; n.put('A', a); n.put('D', d); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << n.front('A'); n.popFront('A'); } std::cout << '\n'; } void group4() { Wheel a({ '1', 'B', 'C' }); Wheel b({ '3', '4' }); Wheel c({ '5', 'B' }); NamedWheel n; n.put('A', a); n.put('B', b); n.put('C', c); for (size_t i = 0; i < 20; i++) { std::cout << ' ' << n.front('A'); n.popFront('A'); } std::cout << '\n'; } int main() { group1(); group2(); group3(); group4(); return 0; }
c583
#include <ctime> #include <iostream> using namespace std; int identity(int x) { return x; } int sum(int num) { for (int i = 0; i < 1000000; i++) num += i; return num; } double time_it(int (*action)(int), int arg) { clock_t start_time = clock(); action(arg); clock_t finis_time = clock(); return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC; } int main() { cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl; cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl; return 0; }
c584
#include <complex> #include <cmath> #include <iostream> using namespace std; template<int MSize = 3, class T = complex<double> > class SqMx { typedef T Ax[MSize][MSize]; typedef SqMx<MSize, T> Mx; private: Ax a; SqMx() { } public: SqMx(const Ax &_a) { for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) a[r][c] = _a[r][c]; } static Mx identity() { Mx m; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) m.a[r][c] = (r == c ? 1 : 0); return m; } friend ostream &operator<<(ostream& os, const Mx &p) { for (int i = 0; i < MSize; i++) { for (int j = 0; j < MSize; j++) os << p.a[i][j] << ','; os << endl; } return os; } Mx operator*(const Mx &b) { Mx d; for (int r = 0; r < MSize; r++) for (int c = 0; c < MSize; c++) { d.a[r][c] = 0; for (int k = 0; k < MSize; k++) d.a[r][c] += a[r][k] * b.a[k][c]; } return d; }
c585
#include <algorithm> #include <iostream> #include <cmath> #include <set> #include <vector> using namespace std; bool find() { const auto MAX = 250; vector<double> pow5(MAX); for (auto i = 1; i < MAX; i++) pow5[i] = (double)i * i * i * i * i; for (auto x0 = 1; x0 < MAX; x0++) { for (auto x1 = 1; x1 < x0; x1++) { for (auto x2 = 1; x2 < x1; x2++) { for (auto x3 = 1; x3 < x2; x3++) { auto sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3]; if (binary_search(pow5.begin(), pow5.end(), sum)) { cout << x0 << " " << x1 << " " << x2 << " " << x3 << " " << pow(sum, 1.0 / 5.0) << endl; return true; } } } } } return false; } int main(void) { int tm = clock(); if (!find()) cout << "Nothing found!\n"; cout << "time=" << (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC) << " milliseconds\r\n"; return 0; }
c586
#include <boost/regex.hpp> #include <fstream> #include <iostream> #include <vector> #include <string> #include <set> #include <cstdlib> #include <algorithm> using namespace std ; boost::regex e ( "\\s+" ) ; int main( int argc , char *argv[ ] ) { ifstream infile( argv[ 1 ] ) ; vector<string> duplicates ; set<string> datestamps ; if ( ! infile.is_open( ) ) { cerr << "Can't open file " << argv[ 1 ] << '\n' ; return 1 ; } int all_ok = 0 ; int pattern_ok = 0 ; while ( infile ) { string eingabe ; getline( infile , eingabe ) ; boost::sregex_token_iterator i ( eingabe.begin( ), eingabe.end( ) , e , -1 ), j ; vector<string> fields( i, j ) ; if ( fields.size( ) == 49 ) pattern_ok++ ; else cout << "Format not ok!\n" ; if ( datestamps.insert( fields[ 0 ] ).second ) { int howoften = ( fields.size( ) - 1 ) / 2 ; for ( int n = 1 ; atoi( fields[ 2 * n ].c_str( ) ) >= 1 ; n++ ) { if ( n == howoften ) { all_ok++ ; break ; } } } else { duplicates.push_back( fields[ 0 ] ) ; } } infile.close( ) ; cout << "The following " << duplicates.size() << " datestamps were duplicated:\n" ; copy( duplicates.begin( ) , duplicates.end( ) , ostream_iterator<string>( cout , "\n" ) ) ; cout << all_ok << " records were complete and ok!\n" ; return 0 ; }
c587
#include <iostream> #include <array> #include <string> using namespace std; int main() { const array<string, 12> days { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" }; const array<string, 12> gifts { "And a partridge in a pear tree", "Two turtle doves", "Three french hens", "Four calling birds", "FIVE GOLDEN RINGS", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming" }; for(int i = 0; i < days.size(); ++i) { cout << "On the " << days[i] << " day of christmas, my true love gave to me\n"; if(i == 0) { cout << "A partridge in a pear tree\n"; } else { int j = i + 1; while(j-- > 0) cout << gifts[j] << '\n'; } cout << '\n'; } return 0; }
c588
#include <algorithm> #include <bitset> #include <iostream> #include <vector> typedef unsigned long ulong; std::vector<ulong> primes; typedef struct { ulong p, e; } prime_factor; void sieve() { constexpr int SIZE = 1 << 16; std::bitset<SIZE> bits; bits.flip(); bits.reset(0); bits.reset(1); for (int i = 0; i < 256; i++) { if (bits.test(i)) { for (int j = i * i; j < SIZE; j += i) { bits.reset(j); } } } for (int i = 0; i < SIZE; i++) { if (bits.test(i)) { primes.push_back(i); } } } auto get_prime_factors(ulong n) { std::vector<prime_factor> lst; ulong e, p; for (ulong i = 0; i < primes.size(); i++) { p = primes[i]; if (p * p > n) break; for (e = 0; !(n % p); n /= p, e++); if (e) { lst.push_back({ p, e }); } } if (n != 1) { lst.push_back({ n, 1 }); } return lst; } auto get_factors(ulong n) { auto f = get_prime_factors(n); std::vector<ulong> lst{ 1 }; size_t len2 = 1; for (size_t i = 0; i < f.size(); i++, len2 = lst.size()) { for (ulong j = 0, p = f[i].p; j < f[i].e; j++, p *= f[i].p) { for (size_t k = 0; k < len2; k++) { lst.push_back(lst[k] * p); } } } std::sort(lst.begin(), lst.end()); return lst; } ulong mpow(ulong a, ulong p, ulong m) { ulong r = 1; while (p) { if (p & 1) { r = r * a % m; } a = a * a % m; p >>= 1; } return r; } ulong ipow(ulong a, ulong p) { ulong r = 1; while (p) { if (p & 1) r *= a; a *= a; p >>= 1; } return r; } ulong gcd(ulong m, ulong n) { ulong t; while (m) { t = m; m = n % m; n = t; } return n; } ulong lcm(ulong m, ulong n) { ulong g = gcd(m, n); return m / g * n; } ulong multi_order_p(ulong a, ulong p, ulong e) { ulong m = ipow(p, e); ulong t = m / p * (p - 1); auto fac = get_factors(t); for (size_t i = 0; i < fac.size(); i++) { if (mpow(a, fac[i], m) == 1) { return fac[i]; } } return 0; } ulong multi_order(ulong a, ulong m) { auto pf = get_prime_factors(m); ulong res = 1; for (size_t i = 0; i < pf.size(); i++) { res = lcm(res, multi_order_p(a, pf[i].p, pf[i].e)); } return res; } int main() { sieve(); printf("%lu\n", multi_order(37, 1000)); printf("%lu\n", multi_order(54, 100001)); return 0; }
c589
class Camera { }; class MobilePhone { }; class CameraPhone: public Camera, public MobilePhone { };
c590
#include <iostream> using namespace std; int main() { int cnt = 0, cnt2, cnt3, tmp, binary[8]; for (int i = 3; cnt < 25; i++) { tmp = i; cnt2 = 0; cnt3 = 0; for (int j = 7; j > 0; j--) { binary[j] = tmp % 2; tmp /= 2; } binary[0] = tmp; for (int j = 0; j < 8; j++) { if (binary[j] == 1) { cnt2++; } } for (int j = 2; j <= (cnt2 / 2); j++) { if (cnt2 % j == 0) { cnt3++; break; } } if (cnt3 == 0 && cnt2 != 1) { cout << i << endl; cnt++; } } cout << endl; int binary2[31]; for (int i = 888888877; i <= 888888888; i++) { tmp = i; cnt2 = 0; cnt3 = 0; for (int j = 30; j > 0; j--) { binary2[j] = tmp % 2; tmp /= 2; } binary2[0] = tmp; for (int j = 0; j < 31; j++) { if (binary2[j] == 1) { cnt2++; } } for (int j = 2; j <= (cnt2 / 2); j++) { if (cnt2 % j == 0) { cnt3++; break; } } if (cnt3 == 0 && cnt2 != 1) { cout << i << endl; } } }
c591
#include <cstdio> int main() { std::rename("input.txt", "output.txt"); std::rename("docs", "mydocs"); std::rename("/input.txt", "/output.txt"); std::rename("/docs", "/mydocs"); return 0; }
c592
#include <string> #include <algorithm> #include <iterator> #include <cstddef> #include <exception> #include <iostream> class not_found: public std::exception { public: not_found(std::string const& s): text(s + " not found") {} char const* what() const throw() { return text.c_str(); } ~not_found() throw() {} private: std::string text; }; std::size_t get_index(std::string* haystack, int haystack_size, std::string needle) { std::size_t index = std::find(haystack, haystack+haystack_size, needle) - haystack; if (index == haystack_size) throw not_found(needle); else return index; } template<typename FwdIter> typename std::iterator_traits<FwdIter>::difference_type fwd_get_index(FwdIter first, FwdIter last, std::string needle) { FwdIter elem = std::find(first, last, needle); if (elem == last) throw not_found(needle); else return std::distance(first, elem); } template<typename InIter> typename std::iterator_traits<InIter>::difference_type generic_get_index(InIter first, InIter last, std::string needle) { typename std::iterator_traits<InIter>::difference_type index = 0; while (first != last && *first != needle) { ++index; ++first; } if (first == last) throw not_found(needle); else return index; } std::string haystack[] = { "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo" }; template<typename T, std::size_t sz> T* begin(T (&array)[sz]) { return array; } template<typename T, std::size_t sz> T* end(T (&array)[sz]) { return array + sz; } template<typename T, std::size_t sz> std::size_t size(T (&array)[sz]) { return sz; } void test(std::string const& needle) { std::cout << "-- C style interface --\n"; try { std::size_t index = get_index(haystack, size(haystack), needle); std::cout << needle << " found at index " << index << "\n"; } catch(std::exception& exc) { std::cout << exc.what() << "\n"; } std::cout << "-- generic interface, first version --\n"; try { std::size_t index = fwd_get_index(begin(haystack), end(haystack), needle); std::cout << needle << " found at index " << index << "\n"; } catch(std::exception& exc) { std::cout << exc.what() << "\n"; } std::cout << "-- generic interface, second version --\n"; try { std::size_t index = generic_get_index(begin(haystack), end(haystack), needle); std::cout << needle << " found at index " << index << "\n"; } catch(std::exception& exc) { std::cout << exc.what() << "\n"; } } int main() { std::cout << "\n=== Word which only occurs once ===\n"; test("Wally"); std::cout << "\n=== Word occuring multiple times ===\n"; test("Bush"); std::cout << "\n=== Word not occuring at all ===\n"; test("Goofy"); }
c593
class Abs { public: virtual int method1(double value) = 0; virtual int add(int a, int b){ return a+b; } };
c594
#include <iostream> #include <limits> using namespace std; void showTokens(int tokens) { cout << "Tokens remaining " << tokens << endl << endl; } int main() { int tokens = 12; while (true) { showTokens(tokens); cout << " How many tokens 1, 2 or 3? "; int t; cin >> t; if (cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl << "Invalid input, try again." << endl << endl; } else if (t < 1 || t > 3) { cout << endl << "Must be a number between 1 and 3, try again." << endl << endl; } else { int ct = 4 - t; string s = (ct > 1) ? "s" : ""; cout << " Computer takes " << ct << " token" << s << endl << endl; tokens -= 4; } if (tokens == 0) { showTokens(0); cout << " Computer wins!" << endl; return 0; } } }
c595
#include <windows.h> #include <iostream> #include <string> using namespace std; class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: "; m[8] = "SEPTEMBER: "; m[9] = "OCTOBER: "; m[10] = "NOVEMBER: "; m[11] = "DECEMBER: "; } void findLastSunday( int y ) { year = y; isleapyear(); int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, d; for( int i = 0; i < 12; i++ ) { d = days[i]; while( true ) { if( !getWeekDay( i, d ) ) break; d--; } lastDay[i] = d; } display(); } private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } } void display() { system( "cls" ); cout << " YEAR " << year << endl << "=============" << endl; for( int x = 0; x < 12; x++ ) cout << m[x] << lastDay[x] << endl; cout << endl << endl; } int getWeekDay( int m, int d ) { int y = year; int f = y + d + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 ); f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7; return f; } int lastDay[12], year; string m[12]; bool isleap; }; int main( int argc, char* argv[] ) { int y; lastSunday ls; while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0; ls.findLastSunday( y ); system( "pause" ); } return 0; }
c596
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> bool is_vowel(char ch) { switch (ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': return true; } return false; } bool alternating_vowels_and_consonants(const std::string& str) { for (size_t i = 1, len = str.size(); i < len; ++i) { if (is_vowel(str[i]) == is_vowel(str[i - 1])) return false; } return true; } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; for (int n = 1; getline(in, line); ) { if (line.size() > 9 && alternating_vowels_and_consonants(line)) std::cout << std::setw(2) << n++ << ": " << line << '\n'; } return EXIT_SUCCESS; }
c597
#include <iostream> #include <vector> template <typename C, typename A> void merge2(const C& c1, const C& c2, const A& action) { auto i1 = std::cbegin(c1); auto i2 = std::cbegin(c2); while (i1 != std::cend(c1) && i2 != std::cend(c2)) { if (*i1 <= *i2) { action(*i1); i1 = std::next(i1); } else { action(*i2); i2 = std::next(i2); } } while (i1 != std::cend(c1)) { action(*i1); i1 = std::next(i1); } while (i2 != std::cend(c2)) { action(*i2); i2 = std::next(i2); } } template <typename A, typename C> void mergeN(const A& action, std::initializer_list<C> all) { using I = typename C::const_iterator; using R = std::pair<I, I>; std::vector<R> vit; for (auto& c : all) { auto p = std::make_pair(std::cbegin(c), std::cend(c)); vit.push_back(p); } bool done; R* least; do { done = true; auto it = vit.begin(); auto end = vit.end(); least = nullptr; while (it != end && it->first == it->second) { it++; } if (it != end) { least = &(*it); } while (it != end) { while (it != end && it->first == it->second) { it++; } if (least != nullptr && it != end && it->first != it->second && *(it->first) < *(least->first)) { least = &(*it); } if (it != end) { it++; } } if (least != nullptr && least->first != least->second) { done = false; action(*(least->first)); least->first = std::next(least->first); } } while (!done); } void display(int num) { std::cout << num << ' '; } int main() { std::vector<int> v1{ 0, 3, 6 }; std::vector<int> v2{ 1, 4, 7 }; std::vector<int> v3{ 2, 5, 8 }; merge2(v2, v1, display); std::cout << '\n'; mergeN(display, { v1 }); std::cout << '\n'; mergeN(display, { v3, v2, v1 }); std::cout << '\n'; }
c598
#include <iostream> #include <vector> #include <iomanip> void primeFactors( unsigned n, std::vector<unsigned>& r ) { int f = 2; if( n == 1 ) r.push_back( 1 ); else { while( true ) { if( !( n % f ) ) { r.push_back( f ); n /= f; if( n == 1 ) return; } else f++; } } } unsigned sumDigits( unsigned n ) { unsigned sum = 0, m; while( n ) { m = n % 10; sum += m; n -= m; n /= 10; } return sum; } unsigned sumDigits( std::vector<unsigned>& v ) { unsigned sum = 0; for( std::vector<unsigned>::iterator i = v.begin(); i != v.end(); i++ ) { sum += sumDigits( *i ); } return sum; } void listAllSmithNumbers( unsigned n ) { std::vector<unsigned> pf; for( unsigned i = 4; i < n; i++ ) { primeFactors( i, pf ); if( pf.size() < 2 ) continue; if( sumDigits( i ) == sumDigits( pf ) ) std::cout << std::setw( 4 ) << i << " "; pf.clear(); } std::cout << "\n\n"; } int main( int argc, char* argv[] ) { listAllSmithNumbers( 10000 ); return 0; }
c599
#include <vector> #include <unordered_map> #include <iostream> int main() { std::vector<int> alreadyDiscovered; std::unordered_map<int, int> divsumMap; int count = 0; for (int N = 1; N <= 20000; ++N) { int divSumN = 0; for (int i = 1; i <= N / 2; ++i) { if (fmod(N, i) == 0) { divSumN += i; } } if (divSumN != 1) divsumMap[N] = divSumN; for (std::unordered_map<int, int>::iterator it = divsumMap.begin(); it != divsumMap.end(); ++it) { int M = it->first; int divSumM = it->second; int divSumN = divsumMap[N]; if (N != M && divSumM == N && divSumN == M) { if (std::find(alreadyDiscovered.begin(), alreadyDiscovered.end(), N) != alreadyDiscovered.end()) break; std::cout << "[" << M << ", " << N << "]" << std::endl; alreadyDiscovered.push_back(M); alreadyDiscovered.push_back(N); count++; } } } std::cout << count << " amicable pairs discovered" << std::endl; }
c600
#include <string> std::string str; std::string str(); std::string str{}; std::string str(""); std::string str{""}; if (str.empty()) { ... } if (str.length() == 0) { ... } if (str == "") { ... } str.clear(); str = ""; str = {}; std::string tmp{}; str.swap(tmp); std::swap(str, tmp); std::string s_array[100]; std::array<std::string, 100> arr; std::vector<std::string>(100,""); void func( std::string& s = {} );
c601
#include<string> #include<iostream> auto split(const std::string& input, const std::string& delim){ std::string res; for(auto ch : input){ if(!res.empty() && ch != res.back()) res += delim; res += ch; } return res; } int main(){ std::cout << split("gHHH5 ))YY++,,, }
c602
#include <cstdlib> #include <complex> template<typename ElementType, std::size_t dim1, std::size_t dim2> std::size_t get_first_dimension(ElementType (&a)[dim1][dim2]) { return dim1; } template<typename ElementType, std::size_t dim1, std::size_t dim2> std::size_t get_second_dimension(ElementType (&a)[dim1][dim2]) { return dim2; } template<typename ColorType, typename ImageType> void draw_Mandelbrot(ImageType& image, ColorType set_color, ColorType non_set_color, double cxmin, double cxmax, double cymin, double cymax, unsigned int max_iterations) { std::size_t const ixsize = get_first_dimension(image); std::size_t const iysize = get_first_dimension(image); for (std::size_t ix = 0; ix < ixsize; ++ix) for (std::size_t iy = 0; iy < iysize; ++iy) { std::complex<double> c(cxmin + ix/(ixsize-1.0)*(cxmax-cxmin), cymin + iy/(iysize-1.0)*(cymax-cymin)); std::complex<double> z = 0; unsigned int iterations; for (iterations = 0; iterations < max_iterations && std::abs(z) < 2.0; ++iterations) z = z*z + c; image[ix][iy] = (iterations == max_iterations) ? set_color : non_set_color; } }
c603
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
c604
#include <iostream> #include <complex> using std::complex; void complex_operations() { complex<double> a(1.0, 1.0); complex<double> b(3.14159, 1.25); std::cout << a + b << std::endl; std::cout << a * b << std::endl; std::cout << 1.0 / a << std::endl; std::cout << -a << std::endl; std::cout << std::conj(a) << std::endl; }
c605
#include <algorithm> #include <ctime> #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { srand(time(0)); unsigned int attributes_total = 0; unsigned int count = 0; int attributes[6] = {}; int rolls[4] = {}; while(attributes_total < 75 || count < 2) { attributes_total = 0; count = 0; for(int attrib = 0; attrib < 6; attrib++) { for(int roll = 0; roll < 4; roll++) { rolls[roll] = 1 + (rand() % 6); } sort(rolls, rolls + 4); int roll_total = rolls[1] + rolls[2] + rolls[3]; attributes[attrib] = roll_total; attributes_total += roll_total; if(roll_total >= 15) count++; } } cout << "Attributes generated : ["; cout << attributes[0] << ", "; cout << attributes[1] << ", "; cout << attributes[2] << ", "; cout << attributes[3] << ", "; cout << attributes[4] << ", "; cout << attributes[5]; cout << "]\nTotal: " << attributes_total; cout << ", Values above 15 : " << count; return 0; }
c606
#include <iostream> #include <iomanip> #include <array> #include <string> #include <tuple> #include <algorithm> using namespace std; template<int N = 8> class Board { public: array<pair<int, int>, 8> moves; array<array<int, N>, N> data; Board() { moves[0] = make_pair(2, 1); moves[1] = make_pair(1, 2); moves[2] = make_pair(-1, 2); moves[3] = make_pair(-2, 1); moves[4] = make_pair(-2, -1); moves[5] = make_pair(-1, -2); moves[6] = make_pair(1, -2); moves[7] = make_pair(2, -1); } array<int, 8> sortMoves(int x, int y) const { array<tuple<int, int>, 8> counts; for(int i = 0; i < 8; ++i) { int dx = get<0>(moves[i]); int dy = get<1>(moves[i]); int c = 0; for(int j = 0; j < 8; ++j) { int x2 = x + dx + get<0>(moves[j]); int y2 = y + dy + get<1>(moves[j]); if (x2 < 0 || x2 >= N || y2 < 0 || y2 >= N) continue; if(data[y2][x2] != 0) continue; c++; } counts[i] = make_tuple(c, i); } random_shuffle(counts.begin(), counts.end()); sort(counts.begin(), counts.end()); array<int, 8> out; for(int i = 0; i < 8; ++i) out[i] = get<1>(counts[i]); return out; } void solve(string start) { for(int v = 0; v < N; ++v) for(int u = 0; u < N; ++u) data[v][u] = 0; int x0 = start[0] - 'a'; int y0 = N - (start[1] - '0'); data[y0][x0] = 1; array<tuple<int, int, int, array<int, 8>>, N*N> order; order[0] = make_tuple(x0, y0, 0, sortMoves(x0, y0)); int n = 0; while(n < N*N-1) { int x = get<0>(order[n]); int y = get<1>(order[n]); bool ok = false; for(int i = get<2>(order[n]); i < 8; ++i) { int dx = moves[get<3>(order[n])[i]].first; int dy = moves[get<3>(order[n])[i]].second; if(x+dx < 0 || x+dx >= N || y+dy < 0 || y+dy >= N) continue; if(data[y + dy][x + dx] != 0) continue; get<2>(order[n]) = i + 1; ++n; data[y+dy][x+dx] = n + 1; order[n] = make_tuple(x+dx, y+dy, 0, sortMoves(x+dx, y+dy)); ok = true; break; } if(!ok) { data[y][x] = 0; --n; } } } template<int N> friend ostream& operator<<(ostream &out, const Board<N> &b); }; template<int N> ostream& operator<<(ostream &out, const Board<N> &b) { for (int v = 0; v < N; ++v) { for (int u = 0; u < N; ++u) { if (u != 0) out << ","; out << setw(3) << b.data[v][u]; } out << endl; } return out; } int main() { Board<5> b1; b1.solve("c3"); cout << b1 << endl; Board<8> b2; b2.solve("b5"); cout << b2 << endl; Board<31> b3; b3.solve("a1"); cout << b3 << endl; return 0; }
c607
#include <iostream> int main() { std::cout << (int)'a' << std::endl; std::cout << (char)97 << std::endl; return 0; }
c608
#include <iostream> #include <map> int main() { const char* strings[] = {"133252abcdeeffd", "a6789798st", "yxcdfgxcyz"}; std::map<char, int> count; for (const char* str : strings) { for (; *str; ++str) ++count[*str]; } for (const auto& p : count) { if (p.second == 1) std::cout << p.first; } std::cout << '\n'; }
c610
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
c611
#include <time.h> #include <iostream> #include <string> using namespace std; class penney { public: penney() { pW = cW = 0; } void gameLoop() { string a; while( true ) { playerChoice = computerChoice = ""; if( rand() % 2 ) { computer(); player(); } else { player(); computer(); } play(); cout << "[Y] to play again "; cin >> a; if( a[0] != 'Y' && a[0] != 'y' ) { cout << "Computer won " << cW << " times." << endl << "Player won " << pW << " times."; break; } cout << endl << endl; } } private: void computer() { if( playerChoice.length() == 0 ) { for( int x = 0; x < 3; x++ ) computerChoice.append( ( rand() % 2 ) ? "H" : "T", 1 ); } else { computerChoice.append( playerChoice[1] == 'T' ? "H" : "T", 1 ); computerChoice += playerChoice.substr( 0, 2 ); } cout << "Computer's sequence of three is: " << computerChoice << endl; } void player() { cout << "Enter your sequence of three (H/T) "; cin >> playerChoice; } void play() { sequence = ""; while( true ) { sequence.append( ( rand() % 2 ) ? "H" : "T", 1 ); if( sequence.find( playerChoice ) != sequence.npos ) { showWinner( 1 ); break; } else if( sequence.find( computerChoice ) != sequence.npos ) { showWinner( 0 ); break; } } } void showWinner( int i ) { string s; if( i ) { s = "Player wins!"; pW++; } else { s = "Computer wins!"; cW++; } cout << "Tossed sequence: " << sequence << endl << s << endl << endl; } string playerChoice, computerChoice, sequence; int pW, cW; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned>( time( NULL ) ) ); penney game; game.gameLoop(); return 0; }
c613
#include <iostream> int main( ) { int current = 0 ; while ( ( current * current ) % 1000000 != 269696 ) current++ ; std::cout << "The square of " << current << " is " << (current * current) << " !\n" ; return 0 ; }
c614
#include <cstdlib> #include <iostream> #include <sstream> #include <iomanip> #include <list> bool k_prime(unsigned n, unsigned k) { unsigned f = 0; for (unsigned p = 2; f < k && p * p <= n; p++) while (0 == n % p) { n /= p; f++; } return f + (n > 1 ? 1 : 0) == k; } std::list<unsigned> primes(unsigned k, unsigned n) { std::list<unsigned> list; for (unsigned i = 2;list.size() < n;i++) if (k_prime(i, k)) list.push_back(i); return list; } int main(const int argc, const char* argv[]) { using namespace std; for (unsigned k = 1; k <= 5; k++) { ostringstream os(""); const list<unsigned> l = primes(k, 10); for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++) os << setw(4) << *i; cout << "k = " << k << ':' << os.str() << endl; } return EXIT_SUCCESS; }
c615
#include <iostream> #include <cmath> #include <cassert> using namespace std; #define PI 3.14159265359 class Vector { public: Vector(double ix, double iy, char mode) { if(mode=='a') { x=ix*cos(iy); y=ix*sin(iy); } else { x=ix; y=iy; } } Vector(double ix,double iy) { x=ix; y=iy; } Vector operator+(const Vector& first) { return Vector(x+first.x,y+first.y); } Vector operator-(Vector first) { return Vector(x-first.x,y-first.y); } Vector operator*(double scalar) { return Vector(x*scalar,y*scalar); } Vector operator/(double scalar) { return Vector(x/scalar,y/scalar); } bool operator==(Vector first) { return (x==first.x&&y==first.y); } void v_print() { cout << "X: " << x << " Y: " << y; } double x,y; }; int main() { Vector vec1(0,1); Vector vec2(2,2); Vector vec3(sqrt(2),45*PI/180,'a'); vec3.v_print(); assert(vec1+vec2==Vector(2,3)); assert(vec1-vec2==Vector(-2,-1)); assert(vec1*5==Vector(0,5)); assert(vec2/2==Vector(1,1)); return 0; }
c616
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <string> int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::set<std::string> dictionary; while (getline(in, line)) dictionary.insert(line); std::cout << std::left; for (const std::string& word : dictionary) { size_t len = word.size(); if (len < 6) continue; std::string word1, word2; for (size_t i = 0; i < len; i += 2) { word1 += word[i]; if (i + 1 < len) word2 += word[i + 1]; } if (dictionary.find(word1) != dictionary.end() && dictionary.find(word2) != dictionary.end()) { std::cout << std::setw(10) << word << std::setw(6) << word1 << word2 << '\n'; } } return EXIT_SUCCESS; }
c617
#include <iostream> #include <string> #include <vector> std::vector<std::string> hist; std::ostream& operator<<(std::ostream& os, const std::string& str) { return os << str.c_str(); } void appendHistory(const std::string& name) { hist.push_back(name); } void hello() { std::cout << "Hello World!\n"; appendHistory(__func__); } void history() { if (hist.size() == 0) { std::cout << "No history\n"; } else { for (auto& str : hist) { std::cout << " - " << str << '\n'; } } appendHistory(__func__); } void help() { std::cout << "Available commands:\n"; std::cout << " hello\n"; std::cout << " hist\n"; std::cout << " exit\n"; std::cout << " help\n"; appendHistory(__func__); } int main() { bool done = false; std::string cmd; do { std::cout << "Enter a command, type help for a listing.\n"; std::cin >> cmd; for (size_t i = 0; i < cmd.size(); ++i) { cmd[i] = toupper(cmd[i]); } if (strcmp(cmd.c_str(), "HELLO") == 0) { hello(); } else if (strcmp(cmd.c_str(), "HIST") == 0) { history(); } else if (strcmp(cmd.c_str(), "EXIT") == 0) { done = true; } else { help(); } } while (!done); return 0; }
c618
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class chaos { public: void start() { POINT org; fillPts(); initialPoint( org ); initColors(); int cnt = 0, i; bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear( 255 ); while( cnt++ < 1000000 ) { switch( rand() % 6 ) { case 0: case 3: i = 0; break; case 1: case 5: i = 1; break; case 2: case 4: i = 2; } setPoint( org, myPoints[i], i ); } bmp.saveBitmap( "F:/st.bmp" ); } private: void setPoint( POINT &o, POINT v, int i ) { POINT z; o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1; SetPixel( bmp.getDC(), o.x, o.y, colors[i] ); } void fillPts() { int a = BMP_SIZE - 1; myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0; myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a; } void initialPoint( POINT& p ) { p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 ); p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 ); } void initColors() { colors[0] = RGB( 255, 0, 0 ); colors[1] = RGB( 0, 255, 0 ); colors[2] = RGB( 0, 0, 255 ); } myBitmap bmp; POINT myPoints[3]; COLORREF colors[3]; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); chaos c; c.start(); return 0; }
c619
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& print(std::ostream& os, const T& src) { auto it = src.cbegin(); auto end = src.cend(); os << "["; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << "]"; } typedef std::map<std::string, int> Map; typedef Map::value_type MapEntry; void standardRank(const Map& scores) { std::cout << "Standard Rank" << std::endl; std::vector<int> list; for (auto& elem : scores) { list.push_back(elem.second); } std::sort(list.begin(), list.end(), std::greater<int>{}); list.erase(std::unique(list.begin(), list.end()), list.end()); int rank = 1; for (auto value : list) { int temp = rank; for (auto& e : scores) { if (e.second == value) { std::cout << temp << " " << value << " " << e.first.c_str() << std::endl; rank++; } } } std::cout << std::endl; } void modifiedRank(const Map& scores) { std::cout << "Modified Rank" << std::endl; std::vector<int> list; for (auto& elem : scores) { list.push_back(elem.second); } std::sort(list.begin(), list.end(), std::greater<int>{}); list.erase(std::unique(list.begin(), list.end()), list.end()); int rank = 0; for (auto value : list) { rank += std::count_if(scores.begin(), scores.end(), [value](const MapEntry& e) { return e.second == value; }); for (auto& e : scores) { if (e.second == value) { std::cout << rank << " " << value << " " << e.first.c_str() << std::endl; } } } std::cout << std::endl; } void denseRank(const Map& scores) { std::cout << "Dense Rank" << std::endl; std::vector<int> list; for (auto& elem : scores) { list.push_back(elem.second); } std::sort(list.begin(), list.end(), std::greater<int>{}); list.erase(std::unique(list.begin(), list.end()), list.end()); int rank = 1; for (auto value : list) { for (auto& e : scores) { if (e.second == value) { std::cout << rank << " " << value << " " << e.first.c_str() << std::endl; } } rank++; } std::cout << std::endl; } void ordinalRank(const Map& scores) { std::cout << "Ordinal Rank" << std::endl; std::vector<int> list; for (auto& elem : scores) { list.push_back(elem.second); } std::sort(list.begin(), list.end(), std::greater<int>{}); list.erase(std::unique(list.begin(), list.end()), list.end()); int rank = 1; for (auto value : list) { for (auto& e : scores) { if (e.second == value) { std::cout << rank++ << " " << value << " " << e.first.c_str() << std::endl; } } } std::cout << std::endl; } void fractionalRank(const Map& scores) { std::cout << "Ordinal Rank" << std::endl; std::vector<int> list; for (auto& elem : scores) { list.push_back(elem.second); } std::sort(list.begin(), list.end(), std::greater<int>{}); list.erase(std::unique(list.begin(), list.end()), list.end()); int rank = 0; for (auto value : list) { double avg = 0.0; int cnt = 0; for (auto& e : scores) { if (e.second == value) { rank++; cnt++; avg += rank; } } avg /= cnt; for (auto& e : scores) { if (e.second == value) { std::cout << std::setprecision(1) << std::fixed << avg << " " << value << " " << e.first.c_str() << std::endl; } } } std::cout << std::endl; } int main() { using namespace std; map<string, int> scores{ {"Solomon", 44}, {"Jason", 42}, {"Errol", 42}, {"Gary", 41}, {"Bernard", 41}, {"Barry", 41}, {"Stephen", 39} }; standardRank(scores); modifiedRank(scores); denseRank(scores); ordinalRank(scores); fractionalRank(scores); return 0; }
c620
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|' || c == '!' || c == '^'; } bool eval_expr(const std::string &expr) { std::stack<bool> sob; for (auto e : expr) { if (e == 'T') { sob.push(true); } else if (e == 'F') { sob.push(false); } else { auto it = std::find_if(vars.cbegin(), vars.cend(), [e](const var &v) { return v.name == e; }); if (it != vars.cend()) { sob.push(it->value); } else { int before = sob.size(); switch (e) { case '&': sob.push(pop(sob) & pop(sob)); break; case '|': sob.push(pop(sob) | pop(sob)); break; case '!': sob.push(!pop(sob)); break; case '^': sob.push(pop(sob) ^ pop(sob)); break; default: throw std::exception("Non-conformant character in expression."); } } } } if (sob.size() != 1) { throw std::exception("Stack should contain exactly one element."); } return sob.top(); } void set_vars(int pos, const std::string &expr) { if (pos > vars.size()) { throw std::exception("Argument to set_vars can't be greater than the number of variables."); } if (pos == vars.size()) { for (auto &v : vars) { std::cout << (v.value ? "T " : "F "); } std::cout << (eval_expr(expr) ? 'T' : 'F') << '\n'; } else { vars[pos].value = false; set_vars(pos + 1, expr); vars[pos].value = true; set_vars(pos + 1, expr); } } std::string process_expr(const std::string &src) { std::stringstream expr; for (auto c : src) { if (!isspace(c)) { expr << (char)toupper(c); } } return expr.str(); } int main() { std::cout << "Accepts single-character variables (except for 'T' and 'F',\n"; std::cout << "which specify explicit true or false values), postfix, with\n"; std::cout << "&|!^ for and, or, not, xor, respectively; optionally\n"; std::cout << "seperated by whitespace. Just enter nothing to quit.\n"; while (true) { std::cout << "\nBoolean expression: "; std::string input; std::getline(std::cin, input); auto expr = process_expr(input); if (expr.length() == 0) { break; } vars.clear(); for (auto e : expr) { if (!is_operator(e) && e != 'T' && e != 'F') { vars.push_back({ e, false }); } } std::cout << '\n'; if (vars.size() == 0) { std::cout << "No variables were entered.\n"; } else { for (auto &v : vars) { std::cout << v.name << " "; } std::cout << expr << '\n'; auto h = vars.size() * 3 + expr.length(); for (size_t i = 0; i < h; i++) { std::cout << '='; } std::cout << '\n'; set_vars(0, expr); } } return 0; }
c621
#include <iostream> int main() { const int N = 15; int t[N+2] = {0,1}; for(int i = 1; i<=N; i++){ for(int j = i; j>1; j--) t[j] = t[j] + t[j-1]; t[i+1] = t[i]; for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1]; std::cout << t[i+1] - t[i] << " "; } return 0; }
c622
#include <iostream> #include <string> std::string strip_white(const std::string& input) { size_t b = input.find_first_not_of(' '); if (b == std::string::npos) b = 0; return input.substr(b, input.find_last_not_of(' ') + 1 - b); } std::string strip_comments(const std::string& input, const std::string& delimiters) { return strip_white(input.substr(0, input.find_first_of(delimiters))); } int main( ) { std::string input; std::string delimiters("#;"); while ( getline(std::cin, input) && !input.empty() ) { std::cout << strip_comments(input, delimiters) << std::endl ; } return 0; }
c623
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <string> int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } const int min_length = 6; std::string word; std::set<std::string> dictionary; while (getline(in, word)) { if (word.size() >= min_length) dictionary.insert(word); } int count = 0; for (const std::string& word1 : dictionary) { if (word1.find('e') == std::string::npos) continue; std::string word2(word1); std::replace(word2.begin(), word2.end(), 'e', 'i'); if (dictionary.find(word2) != dictionary.end()) { std::cout << std::right << std::setw(2) << ++count << ". " << std::left << std::setw(10) << word1 << " -> " << word2 << '\n'; } } return EXIT_SUCCESS; }
c624
#include <utility> #include <algorithm> #include <array> #include <iterator> #include <iostream> template< class F, class Arg > struct PApply { F f; Arg arg; template< class F_, class Arg_ > PApply( F_&& f, Arg_&& arg ) : f(std::forward<F_>(f)), arg(std::forward<Arg_>(arg)) { } template< class ... Args > auto operator() ( Args&& ...args ) -> decltype( f(arg,std::declval<Args>()...) ) { return f( arg, std::forward<Args>(args)... ); } }; template< class F, class Arg > PApply<F,Arg> papply( F&& f, Arg&& arg ) { return PApply<F,Arg>( std::forward<F>(f), std::forward<Arg>(arg) ); } template< class F > std::array<int,4> fs( F&& f, std::array<int,4> cont ) { std::transform( std::begin(cont), std::end(cont), std::begin(cont), std::forward<F>(f) ); return cont; } std::ostream& operator << ( std::ostream& out, const std::array<int,4>& c ) { std::copy( std::begin(c), std::end(c), std::ostream_iterator<int>(out, ", ") ); return out; } int f1( int x ) { return x * 2; } int f2( int x ) { return x * x; } int main() { std::array<int,4> xs = {{ 0, 1, 2, 3 }}; std::array<int,4> ys = {{ 2, 4, 6, 8 }}; auto fsf1 = papply( fs<decltype(f1)>, f1 ); auto fsf2 = papply( fs<decltype(f2)>, f2 ); std::cout << "xs:\n" << "\tfsf1: " << fsf1(xs) << '\n' << "\tfsf2: " << fsf2(xs) << "\n\n" << "ys:\n" << "\tfsf1: " << fsf1(ys) << '\n' << "\tfsf2: " << fsf2(ys) << '\n'; }
c625
#include <string> #include <iostream> int main() { std::string s = "hello"; std::cout << s << " literal" << std::endl; std::string s2 = s + " literal"; std::cout << s2 << std::endl; return 0; }
c626
#include <boost/asio.hpp> int main() { boost::asio::io_context io_context; boost::asio::ip::tcp::socket sock(io_context); boost::asio::ip::tcp::resolver resolver(io_context); boost::asio::ip::tcp::resolver::query query("localhost", "4321"); boost::asio::connect(sock, resolver.resolve(query)); boost::asio::write(sock, boost::asio::buffer("Hello world socket\r\n")); return 0; }
c627
#include <iostream> enum class zd {N00,N01,N10,N11}; class N { private: int dVal = 0, dLen; void _a(int i) { for (;; i++) { if (dLen < i) dLen = i; switch ((zd)((dVal >> (i*2)) & 3)) { case zd::N00: case zd::N01: return; case zd::N10: if (((dVal >> ((i+1)*2)) & 1) != 1) return; dVal += (1 << (i*2+1)); return; case zd::N11: dVal &= ~(3 << (i*2)); _b((i+1)*2); }}} void _b(int pos) { if (pos == 0) {++*this; return;} if (((dVal >> pos) & 1) == 0) { dVal += 1 << pos; _a(pos/2); if (pos > 1) _a((pos/2)-1); } else { dVal &= ~(1 << pos); _b(pos + 1); _b(pos - ((pos > 1)? 2:1)); }} void _c(int pos) { if (((dVal >> pos) & 1) == 1) {dVal &= ~(1 << pos); return;} _c(pos + 1); if (pos > 0) _b(pos - 1); else ++*this; return; } public: N(char const* x = "0") { int i = 0, q = 1; for (; x[i] > 0; i++); for (dLen = --i/2; i >= 0; i--) {dVal+=(x[i]-48)*q; q*=2; }} const N& operator++() {dVal += 1; _a(0); return *this;} const N& operator+=(const N& other) { for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _b(GN); return *this; } const N& operator-=(const N& other) { for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _c(GN); for (;((dVal >> dLen*2) & 3) == 0 or dLen == 0; dLen--); return *this; } const N& operator*=(const N& other) { N Na = other, Nb = other, Nt, Nr; for (int i = 0; i <= (dLen + 1) * 2; i++) { if (((dVal >> i) & 1) > 0) Nr += Nb; Nt = Nb; Nb += Na; Na = Nt; } return *this = Nr; } const bool operator<=(const N& other) const {return dVal <= other.dVal;} friend std::ostream& operator<<(std::ostream&, const N&); }; N operator "" N(char const* x) {return N(x);} std::ostream &operator<<(std::ostream &os, const N &G) { const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"}; if (G.dVal == 0) return os << "0"; os << dig1[(G.dVal >> (G.dLen*2)) & 3]; for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3]; return os; }
c628
#include <iostream> #include <vector> #include <sstream> void print(std::vector<std::vector<double>> dist, std::vector<std::vector<int>> next) { std::cout << "(pair, dist, path)" << std::endl; const auto size = std::size(next); for (auto i = 0; i < size; ++i) { for (auto j = 0; j < size; ++j) { if (i != j) { auto u = i + 1; auto v = j + 1; std::cout << "(" << u << " -> " << v << ", " << dist[i][j] << ", "; std::stringstream path; path << u; do { u = next[u - 1][v - 1]; path << " -> " << u; } while (u != v); std::cout << path.str() << ")" << std::endl; } } } } void solve(std::vector<std::vector<int>> w_s, const int num_vertices) { std::vector<std::vector<double>> dist(num_vertices); for (auto& dim : dist) { for (auto i = 0; i < num_vertices; ++i) { dim.push_back(INT_MAX); } } for (auto& w : w_s) { dist[w[0] - 1][w[1] - 1] = w[2]; } std::vector<std::vector<int>> next(num_vertices); for (auto i = 0; i < num_vertices; ++i) { for (auto j = 0; j < num_vertices; ++j) { next[i].push_back(0); } for (auto j = 0; j < num_vertices; ++j) { if (i != j) { next[i][j] = j + 1; } } } for (auto k = 0; k < num_vertices; ++k) { for (auto i = 0; i < num_vertices; ++i) { for (auto j = 0; j < num_vertices; ++j) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } } print(dist, next); } int main() { std::vector<std::vector<int>> w = { { 1, 3, -2 }, { 2, 1, 4 }, { 2, 3, 3 }, { 3, 4, 2 }, { 4, 2, -1 }, }; int num_vertices = 4; solve(w, num_vertices); std::cin.ignore(); std::cin.get(); return 0; }
c629
#include <gtkmm.h> int main(int argc, char *argv[]) { Gtk::Main app(argc, argv); Gtk::MessageDialog msg("Goodbye, World!"); msg.run(); }
c630
#include <iostream> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int main() { for (int i=0; i<1000; i++) { auto s_i = std::to_string(i); auto s_ds = std::to_string(digitSum(i)); if (s_i.find(s_ds) != std::string::npos) { std::cout << i << " "; } } std::cout << std::endl; return 0; }
c631
#include <vector> #include <string> #include <iostream> #include <ctime> class Date { struct tm ltime; public: Date() { time_t t = time(0); localtime_r(&t, &ltime); } std::string getDate(const char* fmt) { char out[200]; size_t result = strftime(out, sizeof out, fmt, &ltime); return std::string(out, out + result); } std::string getISODate() {return getDate("%F");} std::string getTextDate() {return getDate("%A, %B %d, %Y");} }; int main() { Date d; std::cout << d.getISODate() << std::endl; std::cout << d.getTextDate() << std::endl; return 0; }
c632
#include <vector> #include <boost/date_time/gregorian/gregorian.hpp> #include <algorithm> #include <iostream> #include <iterator> using namespace boost::gregorian ; void print( const date &d ) { std::cout << d.year( ) << "-" << d.month( ) << "\n" ; } int main( ) { greg_month longmonths[ ] = {Jan, Mar , May , Jul , Aug , Oct , Dec } ; int monthssize = sizeof ( longmonths ) / sizeof (greg_month ) ; typedef std::vector<date> DateVector ; DateVector weekendmonster ; std::vector<unsigned short> years_without_5we_months ; for ( unsigned short i = 1900 ; i < 2101 ; i++ ) { bool months_found = false ; for ( int j = 0 ; j < monthssize ; j++ ) { date d ( i , longmonths[ j ] , 1 ) ; if ( d.day_of_week( ) == Friday ) { weekendmonster.push_back( d ) ; if ( months_found == false ) months_found = true ; } } if ( months_found == false ) { years_without_5we_months.push_back( i ) ; } } std::cout << "Between 1900 and 2100 , there are " << weekendmonster.size( ) << " months with 5 complete weekends!\n" ; std::cout << "Months with 5 complete weekends are:\n" ; std::for_each( weekendmonster.begin( ) , weekendmonster.end( ) , print ) ; std::cout << years_without_5we_months.size( ) << " years had no months with 5 complete weekends!\n" ; std::cout << "These are:\n" ; std::copy( years_without_5we_months.begin( ) , years_without_5we_months.end( ) , std::ostream_iterator<unsigned short>( std::cout , "\n" ) ) ; std::cout << std::endl ; return 0 ; }
c633
#include <cctype> #include <iomanip> #include <iostream> #include <list> #include <memory> #include <sstream> #include <string> #include <variant> namespace s_expr { enum class token_type { none, left_paren, right_paren, symbol, string, number }; enum class char_type { left_paren, right_paren, quote, escape, space, other }; enum class parse_state { init, quote, symbol }; struct token { token_type type = token_type::none; std::variant<std::string, double> data; }; char_type get_char_type(char ch) { switch (ch) { case '(': return char_type::left_paren; case ')': return char_type::right_paren; case '"': return char_type::quote; case '\\': return char_type::escape; } if (isspace(static_cast<unsigned char>(ch))) return char_type::space; return char_type::other; } bool parse_number(const std::string& str, token& tok) { try { size_t pos = 0; double num = std::stod(str, &pos); if (pos == str.size()) { tok.type = token_type::number; tok.data = num; return true; } } catch (const std::exception&) { } return false; } bool get_token(std::istream& in, token& tok) { char ch; parse_state state = parse_state::init; bool escape = false; std::string str; token_type type = token_type::none; while (in.get(ch)) { char_type ctype = get_char_type(ch); if (escape) { ctype = char_type::other; escape = false; } else if (ctype == char_type::escape) { escape = true; continue; } if (state == parse_state::quote) { if (ctype == char_type::quote) { type = token_type::string; break; } else str += ch; } else if (state == parse_state::symbol) { if (ctype == char_type::space) break; if (ctype != char_type::other) { in.putback(ch); break; } str += ch; } else if (ctype == char_type::quote) { state = parse_state::quote; } else if (ctype == char_type::other) { state = parse_state::symbol; type = token_type::symbol; str = ch; } else if (ctype == char_type::left_paren) { type = token_type::left_paren; break; } else if (ctype == char_type::right_paren) { type = token_type::right_paren; break; } } if (type == token_type::none) { if (state == parse_state::quote) throw std::runtime_error("syntax error: missing quote"); return false; } tok.type = type; if (type == token_type::string) tok.data = str; else if (type == token_type::symbol) { if (!parse_number(str, tok)) tok.data = str; } return true; } void indent(std::ostream& out, int level) { for (int i = 0; i < level; ++i) out << " "; } class object { public: virtual ~object() {} virtual void write(std::ostream&) const = 0; virtual void write_indented(std::ostream& out, int level) const { indent(out, level); write(out); } }; class string : public object { public: explicit string(const std::string& str) : string_(str) {} void write(std::ostream& out) const { out << std::quoted(string_); } private: std::string string_; }; class symbol : public object { public: explicit symbol(const std::string& str) : string_(str) {} void write(std::ostream& out) const { for (char ch : string_) { if (get_char_type(ch) != char_type::other) out << '\\'; out << ch; } } private: std::string string_; }; class number : public object { public: explicit number(double num) : number_(num) {} void write(std::ostream& out) const { out << number_; } private: double number_; }; class list : public object { public: void write(std::ostream& out) const; void write_indented(std::ostream&, int) const; void append(const std::shared_ptr<object>& ptr) { list_.push_back(ptr); } private: std::list<std::shared_ptr<object>> list_; }; void list::write(std::ostream& out) const { out << "("; if (!list_.empty()) { auto i = list_.begin(); (*i)->write(out); while (++i != list_.end()) { out << ' '; (*i)->write(out); } } out << ")"; } void list::write_indented(std::ostream& out, int level) const { indent(out, level); out << "(\n"; if (!list_.empty()) { for (auto i = list_.begin(); i != list_.end(); ++i) { (*i)->write_indented(out, level + 1); out << '\n'; } } indent(out, level); out << ")"; } class tokenizer { public: tokenizer(std::istream& in) : in_(in) {} bool next() { if (putback_) { putback_ = false; return true; } return get_token(in_, current_); } const token& current() const { return current_; } void putback() { putback_ = true; } private: std::istream& in_; bool putback_ = false; token current_; }; std::shared_ptr<object> parse(tokenizer&); std::shared_ptr<list> parse_list(tokenizer& tok) { std::shared_ptr<list> lst = std::make_shared<list>(); while (tok.next()) { if (tok.current().type == token_type::right_paren) return lst; else tok.putback(); lst->append(parse(tok)); } throw std::runtime_error("syntax error: unclosed list"); } std::shared_ptr<object> parse(tokenizer& tokenizer) { if (!tokenizer.next()) return nullptr; const token& tok = tokenizer.current(); switch (tok.type) { case token_type::string: return std::make_shared<string>(std::get<std::string>(tok.data)); case token_type::symbol: return std::make_shared<symbol>(std::get<std::string>(tok.data)); case token_type::number: return std::make_shared<number>(std::get<double>(tok.data)); case token_type::left_paren: return parse_list(tokenizer); default: break; } throw std::runtime_error("syntax error: unexpected token"); } } void parse_string(const std::string& str) { std::istringstream in(str); s_expr::tokenizer tokenizer(in); auto exp = s_expr::parse(tokenizer); if (exp != nullptr) { exp->write_indented(std::cout, 0); std::cout << '\n'; } } int main(int argc, char** argv) { std::string test_string = "((data \"quoted data\" 123 4.5)\n" " (data (!@# (4.5) \"(more\" \"data)\")))"; if (argc == 2) test_string = argv[1]; try { parse_string(test_string); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; } return 0; }
c634
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/integer.hpp> int main() { using boost::multiprecision::cpp_int; using boost::multiprecision::pow; using boost::multiprecision::powm; cpp_int a("2988348162058574136915891421498819466320163312926952423791023078876139"); cpp_int b("2351399303373464486466122544523690094744975233415544072992656881240319"); std::cout << powm(a, b, pow(cpp_int(10), 40)) << '\n'; return 0; }
c635
T* p = new T[n]; for(size_t i = 0; i != n; ++i) p[i] = make_a_T(); delete[] p;
c636
#include <iostream> #include <vector> using namespace std; typedef unsigned int uint; class NarcissisticDecs { public: void makeList( int mx ) { uint st = 0, tl; int pwr = 0, len; while( narc.size() < mx ) { len = getDigs( st ); if( pwr != len ) { pwr = len; fillPower( pwr ); } tl = 0; for( int i = 1; i < 10; i++ ) tl += static_cast<uint>( powr[i] * digs[i] ); if( tl == st ) narc.push_back( st ); st++; } } void display() { for( vector<uint>::iterator i = narc.begin(); i != narc.end(); i++ ) cout << *i << " "; cout << "\n\n"; } private: int getDigs( uint st ) { memset( digs, 0, 10 * sizeof( int ) ); int r = 0; while( st ) { digs[st % 10]++; st /= 10; r++; } return r; } void fillPower( int z ) { for( int i = 1; i < 10; i++ ) powr[i] = pow( static_cast<float>( i ), z ); } vector<uint> narc; uint powr[10]; int digs[10]; }; int main( int argc, char* argv[] ) { NarcissisticDecs n; n.makeList( 25 ); n.display(); return system( "pause" ); }
c637
#include <iostream> #include <stack> #include <string> #include <map> #include <set> using namespace std; struct Entry_ { string expr_; string op_; }; bool PrecedenceLess(const string& lhs, const string& rhs, bool assoc) { static const map<string, int> KNOWN({ { "+", 1 }, { "-", 1 }, { "*", 2 }, { "/", 2 }, { "^", 3 } }); static const set<string> ASSOCIATIVE({ "+", "*" }); return (KNOWN.count(lhs) ? KNOWN.find(lhs)->second : 0) < (KNOWN.count(rhs) ? KNOWN.find(rhs)->second : 0) + (assoc && !ASSOCIATIVE.count(rhs) ? 1 : 0); } void Parenthesize(Entry_* old, const string& token, bool assoc) { if (!old->op_.empty() && PrecedenceLess(old->op_, token, assoc)) old->expr_ = '(' + old->expr_ + ')'; } void AddToken(stack<Entry_>* stack, const string& token) { if (token.find_first_of("0123456789") != string::npos) stack->push(Entry_({ token, string() })); else { if (stack->size() < 2) cout<<"Stack underflow"; auto rhs = stack->top(); Parenthesize(&rhs, token, false); stack->pop(); auto lhs = stack->top(); Parenthesize(&lhs, token, true); stack->top().expr_ = lhs.expr_ + ' ' + token + ' ' + rhs.expr_; stack->top().op_ = token; } } string ToInfix(const string& src) { stack<Entry_> stack; for (auto start = src.begin(), p = src.begin(); ; ++p) { if (p == src.end() || *p == ' ') { if (p > start) AddToken(&stack, string(start, p)); if (p == src.end()) break; start = p + 1; } } if (stack.size() != 1) cout<<"Incomplete expression"; return stack.top().expr_; } int main(void) { try { cout << ToInfix("3 4 2 * 1 5 - 2 3 ^ ^ / +") << "\n"; cout << ToInfix("1 2 + 3 4 + ^ 5 6 + ^") << "\n"; return 0; } catch (...) { cout << "Failed\n"; return -1; } }
c638
#include <iostream> using namespace std; int main(int argc, char **argv) { char *program = argv[0]; cout << "Program: " << program << endl; }
c639
#include <iomanip> #include <iostream> #include <vector> class Node { private: double v; int fixed; public: Node() : v(0.0), fixed(0) { } Node(double v, int fixed) : v(v), fixed(fixed) { } double getV() const { return v; } void setV(double nv) { v = nv; } int getFixed() const { return fixed; } void setFixed(int nf) { fixed = nf; } }; void setBoundary(std::vector<std::vector<Node>>& m) { m[1][1].setV(1.0); m[1][1].setFixed(1); m[6][7].setV(-1.0); m[6][7].setFixed(-1); } double calculateDifference(const std::vector<std::vector<Node>>& m, std::vector<std::vector<Node>>& d, const int w, const int h) { double total = 0.0; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { double v = 0.0; int n = 0; if (i > 0) { v += m[i - 1][j].getV(); n++; } if (j > 0) { v += m[i][j - 1].getV(); n++; } if (i + 1 < h) { v += m[i + 1][j].getV(); n++; } if (j + 1 < w) { v += m[i][j + 1].getV(); n++; } v = m[i][j].getV() - v / n; d[i][j].setV(v); if (m[i][j].getFixed() == 0) { total += v * v; } } } return total; } double iter(std::vector<std::vector<Node>>& m, const int w, const int h) { using namespace std; vector<vector<Node>> d; for (int i = 0; i < h; ++i) { vector<Node> t(w); d.push_back(t); } double curr[] = { 0.0, 0.0, 0.0 }; double diff = 1e10; while (diff > 1e-24) { setBoundary(m); diff = calculateDifference(m, d, w, h); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { m[i][j].setV(m[i][j].getV() - d[i][j].getV()); } } } for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { int k = 0; if (i != 0) ++k; if (j != 0) ++k; if (i < h - 1) ++k; if (j < w - 1) ++k; curr[m[i][j].getFixed() + 1] += d[i][j].getV()*k; } } return (curr[2] - curr[0]) / 2.0; } const int S = 10; int main() { using namespace std; vector<vector<Node>> mesh; for (int i = 0; i < S; ++i) { vector<Node> t(S); mesh.push_back(t); } double r = 2.0 / iter(mesh, S, S); cout << "R = " << setprecision(15) << r << '\n'; return 0; }
c640
#include <cassert> #include <algorithm> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; bool is_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25); } template <typename integer> class n_smooth_generator { public: explicit n_smooth_generator(size_t n); integer next(); size_t size() const { return results_.size(); } private: std::vector<size_t> primes_; std::vector<size_t> index_; std::vector<integer> results_; std::vector<integer> queue_; }; template <typename integer> n_smooth_generator<integer>::n_smooth_generator(size_t n) { for (size_t p = 2; p <= n; ++p) { if (is_prime(p)) { primes_.push_back(p); queue_.push_back(p); } } index_.assign(primes_.size(), 0); results_.push_back(1); } template <typename integer> integer n_smooth_generator<integer>::next() { integer last = results_.back(); for (size_t i = 0, n = primes_.size(); i < n; ++i) { if (queue_[i] == last) queue_[i] = results_[++index_[i]] * primes_[i]; } results_.push_back(*min_element(queue_.begin(), queue_.end())); return last; } void print_vector(const std::vector<big_int>& numbers) { for (size_t i = 0, n = numbers.size(); i < n; ++i) { std::cout << std::setw(9) << numbers[i]; if ((i + 1) % 10 == 0) std::cout << '\n'; } std::cout << '\n'; } int main() { const int max = 250; std::vector<big_int> first, second; int count1 = 0; int count2 = 0; n_smooth_generator<big_int> smooth_gen(3); big_int p1, p2; while (count1 < max || count2 < max) { big_int n = smooth_gen.next(); if (count1 < max && is_prime(n + 1)) { p1 = n + 1; if (first.size() < 50) first.push_back(p1); ++count1; } if (count2 < max && is_prime(n - 1)) { p2 = n - 1; if (second.size() < 50) second.push_back(p2); ++count2; } } std::cout << "First 50 Pierpont primes of the first kind:\n"; print_vector(first); std::cout << "First 50 Pierpont primes of the second kind:\n"; print_vector(second); std::cout << "250th Pierpont prime of the first kind: " << p1 << '\n'; std::cout << "250th Pierpont prime of the second kind: " << p2 << '\n'; return 0; }
c641
#include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/ip/tcp.hpp> #include <iostream> #include <string> bool get_mac_vendor(const std::string& mac, std::string& vendor) { namespace beast = boost::beast; namespace http = beast::http; namespace net = boost::asio; using tcp = net::ip::tcp; net::io_context ioc; tcp::resolver resolver(ioc); const char* host = "api.macvendors.com"; beast::tcp_stream stream(ioc); stream.connect(resolver.resolve(host, "http")); http::request<http::string_body> req{http::verb::get, "/" + mac, 10}; req.set(http::field::host, host); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); http::write(stream, req); beast::flat_buffer buffer; http::response<http::string_body> res; http::read(stream, buffer, res); bool success = res.result() == http::status::ok; if (success) vendor = res.body(); beast::error_code ec; stream.socket().shutdown(tcp::socket::shutdown_both, ec); if (ec && ec != beast::errc::not_connected) throw beast::system_error{ec}; return success; } int main(int argc, char** argv) { if (argc != 2 || strlen(argv[1]) == 0) { std::cerr << "usage: " << argv[0] << " MAC-address\n"; return EXIT_FAILURE; } try { std::string vendor; if (get_mac_vendor(argv[1], vendor)) { std::cout << vendor << '\n'; return EXIT_SUCCESS; } else { std::cout << "N/A\n"; } } catch(std::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; } return EXIT_FAILURE; }
c642
#include <vector> #include <iostream> #include <numeric> #include <cmath> #include <algorithm> double toInverse ( int i ) { return 1.0 / i ; } int main( ) { std::vector<int> numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ; double geometric_mean = pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ; std::vector<double> inverses ; inverses.resize( numbers.size( ) ) ; std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ; double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean " << geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ; return 0 ; }
c643
#include <iomanip> #include <iostream> #include <vector> #define _USE_MATH_DEFINES #include <math.h> template<typename C> double meanAngle(const C& c) { auto it = std::cbegin(c); auto end = std::cend(c); double x = 0.0; double y = 0.0; double len = 0.0; while (it != end) { x += cos(*it * M_PI / 180); y += sin(*it * M_PI / 180); len++; it = std::next(it); } return atan2(y, x) * 180 / M_PI; } void printMean(std::initializer_list<double> init) { std::cout << std::fixed << std::setprecision(3) << meanAngle(init) << '\n'; } int main() { printMean({ 350, 10 }); printMean({ 90, 180, 270, 360 }); printMean({ 10, 20, 30 }); return 0; }
c644
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <iterator> #include <sstream> int main() { std::string s = "rosetta code phrase reversal"; std::cout << "Input : " << s << '\n' << "Input reversed : " << std::string(s.rbegin(), s.rend()) << '\n' ; std::istringstream is(s); std::vector<std::string> words(std::istream_iterator<std::string>(is), {}); std::cout << "Each word reversed : " ; for(auto w : words) std::cout << std::string(w.rbegin(), w.rend()) << ' '; std::cout << '\n' << "Original word order reversed : " ; reverse_copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << '\n' ; }
c645
#include <gmpxx.h> #include <algorithm> #include <cassert> #include <functional> #include <iostream> #include <vector> using big_int = mpz_class; const unsigned int small_primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; bool is_probably_prime(const big_int& n, int reps) { return mpz_probab_prime_p(n.get_mpz_t(), reps) != 0; } big_int largest_left_truncatable_prime(unsigned int base) { std::vector<big_int> powers = {1}; std::vector<big_int> value = {0}; big_int result = 0; std::function<void(unsigned int)> add_digit = [&](unsigned int i) { if (i == value.size()) { value.resize(i + 1); powers.push_back(base * powers.back()); } for (unsigned int d = 1; d < base; ++d) { value[i] = value[i - 1] + powers[i] * d; if (!is_probably_prime(value[i], 1)) continue; if (value[i] > result) { if (!is_probably_prime(value[i], 50)) continue; result = value[i]; } add_digit(i + 1); } }; for (unsigned int i = 0; small_primes[i] < base; ++i) { value[0] = small_primes[i]; add_digit(1); } return result; } int main() { for (unsigned int base = 3; base < 18; ++base) { std::cout << base << ": " << largest_left_truncatable_prime(base) << '\n'; } for (unsigned int base = 19; base < 32; base += 2) { std::cout << base << ": " << largest_left_truncatable_prime(base) << '\n'; } }
c646
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { if (sameDigits(n, b)) { return true; } } return false; } bool isPrime(int n) { if (n < 2)return false; if (n % 2 == 0)return n == 2; if (n % 3 == 0)return n == 3; int d = 5; while (d * d <= n) { if (n % d == 0)return false; d += 2; if (n % d == 0)return false; d += 4; } return true; } int main() { for (auto kind : { "", "odd ", "prime " }) { bool quiet = false; int BigLim = 99999; int limit = 20; std::cout << "First " << limit << ' ' << kind << "Brazillian numbers:\n"; int c = 0; int n = 7; while (c < BigLim) { if (isBrazilian(n)) { if (!quiet)std::cout << n << ' '; if (++c == limit) { std::cout << "\n\n"; quiet = true; } } if (quiet && kind != "") continue; if (kind == "") { n++; } else if (kind == "odd ") { n += 2; } else if (kind == "prime ") { while (true) { n += 2; if (isPrime(n)) break; } } else { throw new std::runtime_error("Unexpected"); } } if (kind == "") { std::cout << "The " << BigLim + 1 << "th Brazillian number is: " << n << "\n\n"; } } return 0; }
c647
#include <iostream> int main() { int a, b; if (!(std::cin >> a >> b)) { std::cerr << "could not read the numbers\n"; return 1; } if (a < b) std::cout << a << " is less than " << b << "\n"; if (a == b) std::cout << a << " is equal to " << b << "\n"; if (a > b) std::cout << a << " is greater than " << b << "\n"; }
c648
#include <iostream> #include <iomanip> int main() { for (int i = 0; i <= 33; i++) std::cout << std::setw(6) << std::dec << i << " " << std::setw(6) << std::hex << i << " " << std::setw(6) << std::oct << i << std::endl; return 0; }
c649
#include <iostream> #include <sstream> #include <algorithm> #include <vector> #include <string> std::string findLargestConcat ( std::vector< int > & mynumbers ) { std::vector<std::string> concatnumbers ; std::sort ( mynumbers.begin( ) , mynumbers.end( ) ) ; do { std::ostringstream numberstream ; for ( int i : mynumbers ) numberstream << i ; concatnumbers.push_back( numberstream.str( ) ) ; } while ( std::next_permutation( mynumbers.begin( ) , mynumbers.end( ) )) ; return *( std::max_element( concatnumbers.begin( ) , concatnumbers.end( ) ) ) ; } int main( ) { std::vector<int> mynumbers = { 98, 76 , 45 , 34, 9 , 4 , 3 , 1 } ; std::vector<int> othernumbers = { 54 , 546 , 548 , 60 } ; std::cout << "The largest concatenated int is " << findLargestConcat( mynumbers ) << " !\n" ; std::cout << "And here it is " << findLargestConcat( othernumbers ) << " !\n" ; return 0 ; }
c650
#include <set> #include <algorithm> #include <string> #include <iostream> #include <vector> #include <numeric> std::set<std::string> createPrefixes ( const std::string & s ) { std::set<std::string> result ; for ( int i = 1 ; i < s.size( ) + 1 ; i++ ) result.insert( s.substr( 0 , i )) ; return result ; } std::set<std::string> findIntersection ( const std::set<std::string> & a , const std::set<std::string> & b ) { std::set<std::string> intersection ; std::set_intersection( a.begin( ) , a.end( ) , b.begin( ) , b.end( ) , std::inserter ( intersection , intersection.begin( ) ) ) ; return intersection ; } std::set<std::string> findCommonPrefixes( const std::vector<std::string> & theStrings ) { std::set<std::string> result ; if ( theStrings.size( ) == 1 ) { result.insert( *(theStrings.begin( ) ) ) ; } if ( theStrings.size( ) > 1 ) { std::vector<std::set<std::string>> prefixCollector ; for ( std::string s : theStrings ) prefixCollector.push_back( createPrefixes ( s ) ) ; std::set<std::string> neutralElement (createPrefixes( *(theStrings.begin( ) ) )) ; result = std::accumulate( prefixCollector.begin( ) , prefixCollector.end( ) , neutralElement , findIntersection ) ; } return result ; } std::string lcp( const std::vector<std::string> & allStrings ) { if ( allStrings.size( ) == 0 ) return "" ; if ( allStrings.size( ) == 1 ) { return allStrings[ 0 ] ; } if ( allStrings.size( ) > 1 ) { std::set<std::string> prefixes( findCommonPrefixes ( allStrings ) ) ; if ( prefixes.empty( ) ) return "" ; else { std::vector<std::string> common ( prefixes.begin( ) , prefixes.end( ) ) ; std::sort( common.begin( ) , common.end( ) , [] ( const std::string & a, const std::string & b ) { return a.length( ) > b.length( ) ; } ) ; return *(common.begin( ) ) ; } } } int main( ) { std::vector<std::string> input { "interspecies" , "interstellar" , "interstate" } ; std::cout << "lcp(\"interspecies\",\"interstellar\",\"interstate\") = " << lcp ( input ) << std::endl ; input.clear( ) ; input.push_back( "throne" ) ; input.push_back ( "throne" ) ; std::cout << "lcp( \"throne\" , \"throne\"" << ") = " << lcp ( input ) << std::endl ; input.clear( ) ; input.push_back( "cheese" ) ; std::cout << "lcp( \"cheese\" ) = " << lcp ( input ) << std::endl ; input.clear( ) ; std::cout << "lcp(\"\") = " << lcp ( input ) << std::endl ; input.push_back( "prefix" ) ; input.push_back( "suffix" ) ; std::cout << "lcp( \"prefix\" , \"suffix\" ) = " << lcp ( input ) << std::endl ; input.clear( ) ; input.push_back( "foo" ) ; input.push_back( "foobar" ) ; std::cout << "lcp( \"foo\" , \"foobar\" ) = " << lcp ( input ) << std::endl ; return 0 ; }
c651
#include <iostream> #include <tuple> #include <vector> using namespace std; double shoelace(vector<pair<double, double>> points) { double leftSum = 0.0; double rightSum = 0.0; for (int i = 0; i < points.size(); ++i) { int j = (i + 1) % points.size(); leftSum += points[i].first * points[j].second; rightSum += points[j].first * points[i].second; } return 0.5 * abs(leftSum - rightSum); } void main() { vector<pair<double, double>> points = { make_pair( 3, 4), make_pair( 5, 11), make_pair(12, 8), make_pair( 9, 5), make_pair( 5, 6), }; auto ans = shoelace(points); cout << ans << endl; }
c652
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <iterator> std::vector<int> GenerateFactors(int n) { std::vector<int> factors = { 1, n }; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { factors.push_back(i); if (i * i != n) factors.push_back(n / i); } } std::sort(factors.begin(), factors.end()); return factors; } int main() { const int SampleNumbers[] = { 3135, 45, 60, 81 }; for (size_t i = 0; i < sizeof(SampleNumbers) / sizeof(int); ++i) { std::vector<int> factors = GenerateFactors(SampleNumbers[i]); std::cout << "Factors of "; std::cout.width(4); std::cout << SampleNumbers[i] << " are: "; std::copy(factors.begin(), factors.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } return EXIT_SUCCESS; }
c653
void print_logic(bool a, bool b) { std::cout << std::boolalpha; std::cout << "a and b is " << (a && b) << "\n"; std::cout << "a or b is " << (a || b) << "\n"; std::cout << "not a is " << (!a) << "\n"; }
c654
#include <random> #include <map> #include <string> #include <iostream> #include <cmath> #include <iomanip> int main( ) { std::random_device myseed ; std::mt19937 engine ( myseed( ) ) ; std::normal_distribution<> normDistri ( 2 , 3 ) ; std::map<int , int> normalFreq ; int sum = 0 ; double mean = 0.0 ; double stddev = 0.0 ; for ( int i = 1 ; i < 10001 ; i++ ) ++normalFreq[ normDistri ( engine ) ] ; for ( auto MapIt : normalFreq ) { sum += MapIt.first * MapIt.second ; } mean = sum / 10000 ; stddev = sqrt( sum / 10000 ) ; std::cout << "The mean of the distribution is " << mean << " , the " ; std::cout << "standard deviation " << stddev << " !\n" ; std::cout << "And now the histogram:\n" ; for ( auto MapIt : normalFreq ) { std::cout << std::left << std::setw( 4 ) << MapIt.first << std::string( MapIt.second / 100 , '*' ) << std::endl ; } return 0 ; }