Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into C++ but keep the logic exactly as in Python.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t 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 }; for (auto p : primes) { auto p2 = p * p; if (p2 > n) break; if (n % p2 == 0) return false; } return true; } uint64_t iroot(uint64_t n, uint64_t r) { static constexpr double adj = 1e-6; return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj); } uint64_t ipow(uint64_t n, uint64_t p) { uint64_t prod = 1; for (; p > 0; p >>= 1) { if (p & 1) prod *= n; n *= n; } return prod; } std::vector<uint64_t> powerful(uint64_t n, uint64_t k) { std::vector<uint64_t> result; std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) { if (r < k) { result.push_back(m); return; } uint64_t root = iroot(n/m, r); for (uint64_t v = 1; v <= root; ++v) { if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1)) continue; f(m * ipow(v, r), r - 1); } }; f(1, 2*k - 1); std::sort(result.begin(), result.end()); return result; } uint64_t powerful_count(uint64_t n, uint64_t k) { uint64_t count = 0; std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) { if (r <= k) { count += iroot(n/m, r); return; } uint64_t root = iroot(n/m, r); for (uint64_t v = 1; v <= root; ++v) { if (is_square_free(v) && std::gcd(m, v) == 1) f(m * ipow(v, r), r - 1); } }; f(1, 2*k - 1); return count; } int main() { const size_t max = 5; for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) { auto result = powerful(p, k); std::cout << result.size() << " " << k << "-powerful numbers <= 10^" << k << ":"; for (size_t i = 0; i < result.size(); ++i) { if (i == max) std::cout << " ..."; else if (i < max || i + max >= result.size()) std::cout << ' ' << result[i]; } std::cout << '\n'; } std::cout << '\n'; for (uint64_t k = 2; k <= 10; ++k) { std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < " << k + 10 << ":"; for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10) std::cout << ' ' << powerful_count(p, k); std::cout << '\n'; } }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t 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 }; for (auto p : primes) { auto p2 = p * p; if (p2 > n) break; if (n % p2 == 0) return false; } return true; } uint64_t iroot(uint64_t n, uint64_t r) { static constexpr double adj = 1e-6; return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj); } uint64_t ipow(uint64_t n, uint64_t p) { uint64_t prod = 1; for (; p > 0; p >>= 1) { if (p & 1) prod *= n; n *= n; } return prod; } std::vector<uint64_t> powerful(uint64_t n, uint64_t k) { std::vector<uint64_t> result; std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) { if (r < k) { result.push_back(m); return; } uint64_t root = iroot(n/m, r); for (uint64_t v = 1; v <= root; ++v) { if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1)) continue; f(m * ipow(v, r), r - 1); } }; f(1, 2*k - 1); std::sort(result.begin(), result.end()); return result; } uint64_t powerful_count(uint64_t n, uint64_t k) { uint64_t count = 0; std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) { if (r <= k) { count += iroot(n/m, r); return; } uint64_t root = iroot(n/m, r); for (uint64_t v = 1; v <= root; ++v) { if (is_square_free(v) && std::gcd(m, v) == 1) f(m * ipow(v, r), r - 1); } }; f(1, 2*k - 1); return count; } int main() { const size_t max = 5; for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) { auto result = powerful(p, k); std::cout << result.size() << " " << k << "-powerful numbers <= 10^" << k << ":"; for (size_t i = 0; i < result.size(); ++i) { if (i == max) std::cout << " ..."; else if (i < max || i + max >= result.size()) std::cout << ' ' << result[i]; } std::cout << '\n'; } std::cout << '\n'; for (uint64_t k = 2; k <= 10; ++k) { std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < " << k + 10 << ":"; for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10) std::cout << ' ' << powerful_count(p, k); std::cout << '\n'; } }
Translate the given Python code snippet into C++ without altering its behavior.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) return res def kpowerful(k, upper_bound, count_only=True): ps = primepowers(k, upper_bound) def accu(i, ub): c = 0 if count_only else [] for p in ps[i]: u = ub//p if not u: break c += 1 if count_only else [p] for j in range(i + 1, len(ps)): if u < ps[j][0]: break c += accu(j, u) if count_only else [p*x for x in accu(j, u)] return c res = accu(0, upper_bound) return res if count_only else sorted(res) for k in range(2, 11): res = kpowerful(k, 10**k, count_only=False) print(f'{len(res)} {k}-powerfuls up to 10^{k}:', ' '.join(str(x) for x in res[:5]), '...', ' '.join(str(x) for x in res[-5:]) ) for k in range(2, 11): res = [kpowerful(k, 10**n) for n in range(k+10)] print(f'{k}-powerful up to 10^{k+10}:', ' '.join(str(x) for x in res))
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t 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 }; for (auto p : primes) { auto p2 = p * p; if (p2 > n) break; if (n % p2 == 0) return false; } return true; } uint64_t iroot(uint64_t n, uint64_t r) { static constexpr double adj = 1e-6; return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj); } uint64_t ipow(uint64_t n, uint64_t p) { uint64_t prod = 1; for (; p > 0; p >>= 1) { if (p & 1) prod *= n; n *= n; } return prod; } std::vector<uint64_t> powerful(uint64_t n, uint64_t k) { std::vector<uint64_t> result; std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) { if (r < k) { result.push_back(m); return; } uint64_t root = iroot(n/m, r); for (uint64_t v = 1; v <= root; ++v) { if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1)) continue; f(m * ipow(v, r), r - 1); } }; f(1, 2*k - 1); std::sort(result.begin(), result.end()); return result; } uint64_t powerful_count(uint64_t n, uint64_t k) { uint64_t count = 0; std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) { if (r <= k) { count += iroot(n/m, r); return; } uint64_t root = iroot(n/m, r); for (uint64_t v = 1; v <= root; ++v) { if (is_square_free(v) && std::gcd(m, v) == 1) f(m * ipow(v, r), r - 1); } }; f(1, 2*k - 1); return count; } int main() { const size_t max = 5; for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) { auto result = powerful(p, k); std::cout << result.size() << " " << k << "-powerful numbers <= 10^" << k << ":"; for (size_t i = 0; i < result.size(); ++i) { if (i == max) std::cout << " ..."; else if (i < max || i + max >= result.size()) std::cout << ' ' << result[i]; } std::cout << '\n'; } std::cout << '\n'; for (uint64_t k = 2; k <= 10; ++k) { std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < " << k + 10 << ":"; for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10) std::cout << ' ' << powerful_count(p, k); std::cout << '\n'; } }
Keep all operations the same but rewrite the snippet in C++.
infile = open('infile.dat', 'rb') outfile = open('outfile.dat', 'wb') while True: onerecord = infile.read(80) if len(onerecord) < 80: break onerecordreversed = bytes(reversed(onerecord)) outfile.write(onerecordreversed) infile.close() outfile.close()
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> void reverse(std::istream& in, std::ostream& out) { constexpr size_t record_length = 80; char record[record_length]; while (in.read(record, record_length)) { std::reverse(std::begin(record), std::end(record)); out.write(record, record_length); } out.flush(); } int main(int argc, char** argv) { std::ifstream in("infile.dat", std::ios_base::binary); if (!in) { std::cerr << "Cannot open input file\n"; return EXIT_FAILURE; } std::ofstream out("outfile.dat", std::ios_base::binary); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } try { in.exceptions(std::ios_base::badbit); out.exceptions(std::ios_base::badbit); reverse(in, out); } catch (const std::exception& ex) { std::cerr << "I/O error: " << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() for word in wordList: if len(word)>5 and word[:3].lower()==word[-3:].lower(): print(word)
#include <cstdlib> #include <fstream> #include <iostream> 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 word; int n = 0; while (getline(in, word)) { const size_t len = word.size(); if (len > 5 && word.compare(0, 3, word, len - 3) == 0) std::cout << ++n << ": " << word << '\n'; } return EXIT_SUCCESS; }
Transform the following Python implementation into C++, maintaining the same output and logic.
from math import sqrt def isGiuga(m): n = m f = 2 l = sqrt(n) while True: if n % f == 0: if ((m / f) - 1) % f != 0: return False n /= f if f > n: return True else: f += 1 if f > l: return False if __name__ == '__main__': n = 3 c = 0 print("The first 4 Giuga numbers are: ") while c < 4: if isGiuga(n): c += 1 print(n) n += 1
#include <iostream> bool is_giuga(unsigned int n) { unsigned int m = n / 2; auto test_factor = [&m, n](unsigned int p) -> bool { if (m % p != 0) return true; m /= p; return m % p != 0 && (n / p - 1) % p == 0; }; if (!test_factor(3) || !test_factor(5)) return false; static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6}; for (unsigned int p = 7, i = 0; p * p <= m; ++i) { if (!test_factor(p)) return false; p += wheel[i & 7]; } return m == 1 || (n / m - 1) % m == 0; } int main() { std::cout << "First 5 Giuga numbers:\n"; for (unsigned int i = 0, n = 6; i < 5; n += 4) { if (is_giuga(n)) { std::cout << n << '\n'; ++i; } } }
Convert this Python block to C++, preserving its control flow and logic.
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int degree = polynomial.size() - 1; int d = degree; for (int i : polynomial) { if (d < degree) { if (i >= 0) { formatted += " + "; } else { formatted += " - "; } } formatted += std::to_string(abs(i)); if (d > 1) { formatted += "x^" + std::to_string(d); } else if (d == 1) { formatted += "x"; } d--; } return formatted; } std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor) { std::vector<int> quotient; quotient = dividend; int normalizer = divisor[0]; for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++) { quotient[i] /= normalizer; int coef = quotient[i]; if (coef != 0) { for (int j = 1; j < divisor.size(); j++) { quotient[i + j] += -divisor[j] * coef; } } } return quotient; } int main(int argc, char **argv) { std::vector<int> dividend{ 1, -12, 0, -42}; std::vector<int> divisor{ 1, -3}; std::cout << frmtPolynomial(dividend) << "\n"; std::cout << frmtPolynomial(divisor) << "\n"; std::vector<int> quotient = syntheticDiv(dividend, divisor); std::cout << frmtPolynomial(quotient, true) << "\n"; }
Generate a C++ translation of this Python snippet without changing its computational steps.
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int degree = polynomial.size() - 1; int d = degree; for (int i : polynomial) { if (d < degree) { if (i >= 0) { formatted += " + "; } else { formatted += " - "; } } formatted += std::to_string(abs(i)); if (d > 1) { formatted += "x^" + std::to_string(d); } else if (d == 1) { formatted += "x"; } d--; } return formatted; } std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor) { std::vector<int> quotient; quotient = dividend; int normalizer = divisor[0]; for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++) { quotient[i] /= normalizer; int coef = quotient[i]; if (coef != 0) { for (int j = 1; j < divisor.size(); j++) { quotient[i + j] += -divisor[j] * coef; } } } return quotient; } int main(int argc, char **argv) { std::vector<int> dividend{ 1, -12, 0, -42}; std::vector<int> divisor{ 1, -3}; std::cout << frmtPolynomial(dividend) << "\n"; std::cout << frmtPolynomial(divisor) << "\n"; std::vector<int> quotient = syntheticDiv(dividend, divisor); std::cout << frmtPolynomial(quotient, true) << "\n"; }
Write a version of this Python function in C++ with identical behavior.
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: oddWordSet.add(word[::2]) [print(i) for i in sorted(oddWordSet)]
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <string> #include <utility> #include <vector> using word_list = std::vector<std::pair<std::string, std::string>>; void print_words(std::ostream& out, const word_list& words) { int n = 1; for (const auto& pair : words) { out << std::right << std::setw(2) << n++ << ": " << std::left << std::setw(14) << pair.first << pair.second << '\n'; } } 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 = 5; std::string line; std::set<std::string> dictionary; while (getline(in, line)) { if (line.size() >= min_length) dictionary.insert(line); } word_list odd_words, even_words; for (const std::string& word : dictionary) { if (word.size() < min_length + 2*(min_length/2)) continue; std::string odd_word, even_word; for (auto w = word.begin(); w != word.end(); ++w) { odd_word += *w; if (++w == word.end()) break; even_word += *w; } if (dictionary.find(odd_word) != dictionary.end()) odd_words.emplace_back(word, odd_word); if (dictionary.find(even_word) != dictionary.end()) even_words.emplace_back(word, even_word); } std::cout << "Odd words:\n"; print_words(std::cout, odd_words); std::cout << "\nEven words:\n"; print_words(std::cout, even_words); return EXIT_SUCCESS; }
Translate this program into C++ but keep the logic exactly as in Python.
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: level = [] while lst: d, name = lst[0] if d == depth: children = [] level.append((name, children)) lst.pop(0) elif d > depth: to_nest(lst, d, children) elif d < depth: return return level[0] if level else None if __name__ == '__main__': print('Start Nest format:') nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), ('mocks', [('trolling', [])])]) pp(nest, width=25) print('\n... To Indent format:') as_ind = to_indent(nest) pp(as_ind, width=25) print('\n... To Nest format:') as_nest = to_nest(as_ind) pp(as_nest, width=25) if nest != as_nest: print("Whoops round-trip issues")
#include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> #include <utility> #include <vector> class nest_tree; bool operator==(const nest_tree&, const nest_tree&); class nest_tree { public: explicit nest_tree(const std::string& name) : name_(name) {} nest_tree& add_child(const std::string& name) { children_.emplace_back(name); return children_.back(); } void print(std::ostream& out) const { print(out, 0); } const std::string& name() const { return name_; } const std::list<nest_tree>& children() const { return children_; } bool equals(const nest_tree& n) const { return name_ == n.name_ && children_ == n.children_; } private: void print(std::ostream& out, int level) const { std::string indent(level * 4, ' '); out << indent << name_ << '\n'; for (const nest_tree& child : children_) child.print(out, level + 1); } std::string name_; std::list<nest_tree> children_; }; bool operator==(const nest_tree& a, const nest_tree& b) { return a.equals(b); } class indent_tree { public: explicit indent_tree(const nest_tree& n) { items_.emplace_back(0, n.name()); from_nest(n, 0); } void print(std::ostream& out) const { for (const auto& item : items_) std::cout << item.first << ' ' << item.second << '\n'; } nest_tree to_nest() const { nest_tree n(items_[0].second); to_nest_(n, 1, 0); return n; } private: void from_nest(const nest_tree& n, int level) { for (const nest_tree& child : n.children()) { items_.emplace_back(level + 1, child.name()); from_nest(child, level + 1); } } size_t to_nest_(nest_tree& n, size_t pos, int level) const { while (pos < items_.size() && items_[pos].first == level + 1) { nest_tree& child = n.add_child(items_[pos].second); pos = to_nest_(child, pos + 1, level + 1); } return pos; } std::vector<std::pair<int, std::string>> items_; }; int main() { nest_tree n("RosettaCode"); auto& child1 = n.add_child("rocks"); auto& child2 = n.add_child("mocks"); child1.add_child("code"); child1.add_child("comparison"); child1.add_child("wiki"); child2.add_child("trolling"); std::cout << "Initial nest format:\n"; n.print(std::cout); indent_tree i(n); std::cout << "\nIndent format:\n"; i.print(std::cout); nest_tree n2(i.to_nest()); std::cout << "\nFinal nest format:\n"; n2.print(std::cout); std::cout << "\nAre initial and final nest formats equal? " << std::boolalpha << n.equals(n2) << '\n'; return 0; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c) seen[c] += 1 return ''.join(newchars) print('abracadabra ->', trstring('abracadabra', rep))
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second.empty()) { *it = f->second.back(); f->second.pop_back(); } } std::cout << magic << "\n"; }
Preserve the algorithm and functionality while converting the code from Python to C++.
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c) seen[c] += 1 return ''.join(newchars) print('abracadabra ->', trstring('abracadabra', rep))
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second.empty()) { *it = f->second.back(); f->second.pop_back(); } } std::cout << magic << "\n"; }
Generate a C++ translation of this Python snippet without changing its computational steps.
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { mpz_class repunit(std::string(prime, '1'), base); if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0) result.push_back(prime); } return result; } int main() { std::vector<uint64_t> primes; const uint64_t limit = 2700; primesieve::generate_primes(limit, &primes); std::vector<std::future<std::vector<uint64_t>>> futures; for (uint32_t base = 2; base <= 36; ++base) { futures.push_back(std::async(repunit_primes, base, primes)); } std::cout << "Repunit prime digits (up to " << limit << ") in:\n"; for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) { std::cout << "Base " << std::setw(2) << base << ':'; for (auto digits : futures[i].get()) std::cout << ' ' << digits; std::cout << '\n'; } }
Translate the given Python code snippet into C++ without altering its behavior.
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { mpz_class repunit(std::string(prime, '1'), base); if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0) result.push_back(prime); } return result; } int main() { std::vector<uint64_t> primes; const uint64_t limit = 2700; primesieve::generate_primes(limit, &primes); std::vector<std::future<std::vector<uint64_t>>> futures; for (uint32_t base = 2; base <= 36; ++base) { futures.push_back(std::async(repunit_primes, base, primes)); } std::cout << "Repunit prime digits (up to " << limit << ") in:\n"; for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) { std::cout << "Base " << std::setw(2) << base << ':'; for (auto digits : futures[i].get()) std::cout << ' ' << digits; std::cout << '\n'; } }
Transform the following Python implementation into C++, maintaining the same output and logic.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; } bool is_curzon(uint64_t n, uint64_t k) { const uint64_t r = k * n; return modpow(k, n, r + 1) == r; } int main() { for (uint64_t k = 2; k <= 10; k += 2) { std::cout << "Curzon numbers with base " << k << ":\n"; uint64_t count = 0, n = 1; for (; count < 50; ++n) { if (is_curzon(n, k)) { std::cout << std::setw(4) << n << (++count % 10 == 0 ? '\n' : ' '); } } for (;;) { if (is_curzon(n, k)) ++count; if (count == 1000) break; ++n; } std::cout << "1000th Curzon number with base " << k << ": " << n << "\n\n"; } return 0; }
Write a version of this Python function in C++ with identical behavior.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; } bool is_curzon(uint64_t n, uint64_t k) { const uint64_t r = k * n; return modpow(k, n, r + 1) == r; } int main() { for (uint64_t k = 2; k <= 10; k += 2) { std::cout << "Curzon numbers with base " << k << ":\n"; uint64_t count = 0, n = 1; for (; count < 50; ++n) { if (is_curzon(n, k)) { std::cout << std::setw(4) << n << (++count % 10 == 0 ? '\n' : ' '); } } for (;;) { if (is_curzon(n, k)) ++count; if (count == 1000) break; ++n; } std::cout << "1000th Curzon number with base " << k << ": " << n << "\n\n"; } return 0; }
Convert this Python block to C++, preserving its control flow and logic.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '') print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\n')
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; } bool is_curzon(uint64_t n, uint64_t k) { const uint64_t r = k * n; return modpow(k, n, r + 1) == r; } int main() { for (uint64_t k = 2; k <= 10; k += 2) { std::cout << "Curzon numbers with base " << k << ":\n"; uint64_t count = 0, n = 1; for (; count < 50; ++n) { if (is_curzon(n, k)) { std::cout << std::setw(4) << n << (++count % 10 == 0 ? '\n' : ' '); } } for (;;) { if (is_curzon(n, k)) ++count; if (count == 1000) break; ++n; } std::cout << "1000th Curzon number with base " << k << ": " << n << "\n\n"; } return 0; }
Translate the given Python code snippet into C++ without altering its behavior.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) * pi); } int main() { std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n" << std::setprecision(80) << f(163) << '\n'; std::cout << "\nResult with last four Heegner numbers:\n"; std::cout << std::setprecision(30); for (unsigned int n : {19, 43, 67, 163}) { auto x = f(n); auto c = ceil(x); auto pc = 100.0 * (x/c); std::cout << "f(" << n << ") = " << x << " = " << pc << "% of " << c << '\n'; } return 0; }
Generate a C++ translation of this Python snippet without changing its computational steps.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) * pi); } int main() { std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n" << std::setprecision(80) << f(163) << '\n'; std::cout << "\nResult with last four Heegner numbers:\n"; std::cout << std::setprecision(30); for (unsigned int n : {19, 43, 67, 163}) { auto x = f(n); auto c = ceil(x); auto pc = 100.0 * (x/c); std::cout << "f(" << n << ") = " << x << " = " << pc << "% of " << c << '\n'; } return 0; }
Port the provided Python code into C++ while preserving the original functionality.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) * pi); } int main() { std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n" << std::setprecision(80) << f(163) << '\n'; std::cout << "\nResult with last four Heegner numbers:\n"; std::cout << std::setprecision(30); for (unsigned int n : {19, 43, 67, 163}) { auto x = f(n); auto c = ceil(x); auto pc = 100.0 * (x/c); std::cout << "f(" << n << ") = " << x << " = " << pc << "% of " << c << '\n'; } return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
class Example(object): def foo(self): print("this is foo") def bar(self): print("this is bar") def __getattr__(self, name): def method(*args): print("tried to handle unknown method " + name) if args: print("it had arguments: " + str(args)) return method example = Example() example.foo() example.bar() example.grill() example.ding("dong")
class animal { public: virtual void bark() { throw "implement me: do not know how to bark"; } }; class elephant : public animal { }; int main() { elephant e; e.bark(); }
Convert the following code from Python to C++, ensuring the logic remains intact.
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( w, go(s[len(w):]) ) if s.startswith(w) else [] def parse(w, xs): return [Node(w)(xs)] if xs else xs return lambda s: go(s) def showParse(tree): def showTokens(x): xs = x['nest'] return ' ' + x['root'] + (showTokens(xs[0]) if xs else '') parses = tree['nest'] return tree['root'] + ':\n' + ( '\n'.join( map(showTokens, parses) ) if parses else ' ( Not parseable in terms of these words )' ) def main(): lexicon = 'a bc abc cd b'.split() testSamples = 'abcd abbc abcbcd acdbc abcdd'.split() print(unlines( map( showParse, map( stringParse(lexicon), testSamples ) ) )) def Node(v): return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} def concatMap(f): return lambda xs: list( chain.from_iterable(map(f, xs)) ) def unlines(xs): return '\n'.join(xs) if __name__ == '__main__': main()
#include <algorithm> #include <iostream> #include <optional> #include <set> #include <string> #include <string_view> #include <vector> struct string_comparator { using is_transparent = void; bool operator()(const std::string& lhs, const std::string& rhs) const { return lhs < rhs; } bool operator()(const std::string& lhs, const std::string_view& rhs) const { return lhs < rhs; } bool operator()(const std::string_view& lhs, const std::string& rhs) const { return lhs < rhs; } }; using dictionary = std::set<std::string, string_comparator>; template <typename iterator, typename separator> std::string join(iterator begin, iterator end, separator sep) { std::string result; if (begin != end) { result += *begin++; for (; begin != end; ++begin) { result += sep; result += *begin; } } return result; } auto create_string(const std::string_view& s, const std::vector<std::optional<size_t>>& v) { auto idx = s.size(); std::vector<std::string_view> sv; while (v[idx].has_value()) { size_t prev = v[idx].value(); sv.push_back(s.substr(prev, idx - prev)); idx = prev; } std::reverse(sv.begin(), sv.end()); return join(sv.begin(), sv.end(), ' '); } std::optional<std::string> word_break(const std::string_view& str, const dictionary& dict) { auto size = str.size() + 1; std::vector<std::optional<size_t>> possible(size); auto check_word = [&dict, &str](size_t i, size_t j) -> std::optional<size_t> { if (dict.find(str.substr(i, j - i)) != dict.end()) return i; return std::nullopt; }; for (size_t i = 1; i < size; ++i) { if (!possible[i].has_value()) possible[i] = check_word(0, i); if (possible[i].has_value()) { for (size_t j = i + 1; j < size; ++j) { if (!possible[j].has_value()) possible[j] = check_word(i, j); } if (possible[str.size()].has_value()) return create_string(str, possible); } } return std::nullopt; } int main(int argc, char** argv) { dictionary dict; dict.insert("a"); dict.insert("bc"); dict.insert("abc"); dict.insert("cd"); dict.insert("b"); auto result = word_break("abcd", dict); if (result.has_value()) std::cout << result.value() << '\n'; return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint64_t p = 10; p <= limit;) { uint64_t prime = pi.next_prime(); if (prime > p) { primes_by_digits.push_back(std::move(primes)); p *= 10; } primes.push_back(prime); } return primes_by_digits; } int main() { std::cout.imbue(std::locale("")); auto start = std::chrono::high_resolution_clock::now(); auto primes_by_digits = get_primes_by_digits(1000000000); std::cout << "First 100 brilliant numbers:\n"; std::vector<uint64_t> brilliant_numbers; for (const auto& primes : primes_by_digits) { for (auto i = primes.begin(); i != primes.end(); ++i) for (auto j = i; j != primes.end(); ++j) brilliant_numbers.push_back(*i * *j); if (brilliant_numbers.size() >= 100) break; } std::sort(brilliant_numbers.begin(), brilliant_numbers.end()); for (size_t i = 0; i < 100; ++i) { std::cout << std::setw(5) << brilliant_numbers[i] << ((i + 1) % 10 == 0 ? '\n' : ' '); } std::cout << '\n'; uint64_t power = 10; size_t count = 0; for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) { const auto& primes = primes_by_digits[p / 2]; size_t position = count + 1; uint64_t min_product = 0; for (auto i = primes.begin(); i != primes.end(); ++i) { uint64_t p1 = *i; auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1); if (j != primes.end()) { uint64_t p2 = *j; uint64_t product = p1 * p2; if (min_product == 0 || product < min_product) min_product = product; position += std::distance(i, j); if (p1 >= p2) break; } } std::cout << "First brilliant number >= 10^" << p << " is " << min_product << " at position " << position << '\n'; power *= 10; if (p % 2 == 1) { size_t size = primes.size(); count += size * (size + 1) / 2; } } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Change the following Python code into C++ without altering its purpose.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n + 1)//2 continue i = np.searchsorted(blk, root, 'left') i += blk[i]*blk[i] < lb if not i: return blk[0]*blk[0], pos p = blk[:i + 1] q = (lb - 1)//p idx = np.searchsorted(blk, q, 'right') sel = idx < n p, idx = p[sel], idx[sel] q = blk[idx] sel = q >= p p, q, idx = p[sel], q[sel], idx[sel] pos += np.sum(idx - np.arange(len(idx))) return np.min(p*q), pos res = [] p = 0 for i in range(100): p, _ = smallest_brilliant(p + 1) res.append(p) print(f'first 100 are {res}') for i in range(max_order*2): thresh = 10**i p, pos = smallest_brilliant(thresh) print(f'Above 10^{i:2d}: {p:20d} at
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint64_t p = 10; p <= limit;) { uint64_t prime = pi.next_prime(); if (prime > p) { primes_by_digits.push_back(std::move(primes)); p *= 10; } primes.push_back(prime); } return primes_by_digits; } int main() { std::cout.imbue(std::locale("")); auto start = std::chrono::high_resolution_clock::now(); auto primes_by_digits = get_primes_by_digits(1000000000); std::cout << "First 100 brilliant numbers:\n"; std::vector<uint64_t> brilliant_numbers; for (const auto& primes : primes_by_digits) { for (auto i = primes.begin(); i != primes.end(); ++i) for (auto j = i; j != primes.end(); ++j) brilliant_numbers.push_back(*i * *j); if (brilliant_numbers.size() >= 100) break; } std::sort(brilliant_numbers.begin(), brilliant_numbers.end()); for (size_t i = 0; i < 100; ++i) { std::cout << std::setw(5) << brilliant_numbers[i] << ((i + 1) % 10 == 0 ? '\n' : ' '); } std::cout << '\n'; uint64_t power = 10; size_t count = 0; for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) { const auto& primes = primes_by_digits[p / 2]; size_t position = count + 1; uint64_t min_product = 0; for (auto i = primes.begin(); i != primes.end(); ++i) { uint64_t p1 = *i; auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1); if (j != primes.end()) { uint64_t p2 = *j; uint64_t product = p1 * p2; if (min_product == 0 || product < min_product) min_product = product; position += std::distance(i, j); if (p1 >= p2) break; } } std::cout << "First brilliant number >= 10^" << p << " is " << min_product << " at position " << position << '\n'; power *= 10; if (p % 2 == 1) { size_t size = primes.size(); count += size * (size + 1) / 2; } } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Convert this Python snippet to C++ and keep its semantics consistent.
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' ))) return s dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt' read_url = lambda url : urllib.request.urlopen( url ).read() load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n')) isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1 def build_map ( words ): map = [(w.decode('ascii'),[]) for w in words] for i1,(w1,n1) in enumerate( map ): for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ): if isnext( w1,w2 ): n1.append( i2 ) n2.append( i1 ) return map def find_path ( words,w1,w2 ): i = [w[0] for w in words].index( w1 ) front,done,res = [i],{i:-1},[] while front : i = front.pop(0) word,next = words[i] for n in next : if n in done : continue done[n] = i if words[n][0] == w2 : while n >= 0 : res = [words[n][0]] + res n = done[n] return ' '.join( res ) front.append( n ) return '%s can not be turned into %s'%( w1,w2 ) for w in ('boy man','girl lady','john jane','alien drool','child adult'): print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
#include <algorithm> #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> using word_map = std::map<size_t, std::vector<std::string>>; bool one_away(const std::string& s1, const std::string& s2) { if (s1.size() != s2.size()) return false; bool result = false; for (size_t i = 0, n = s1.size(); i != n; ++i) { if (s1[i] != s2[i]) { if (result) return false; result = true; } } return result; } template <typename iterator_type, typename separator_type> std::string join(iterator_type begin, iterator_type end, separator_type separator) { std::string result; if (begin != end) { result += *begin++; for (; begin != end; ++begin) { result += separator; result += *begin; } } return result; } bool word_ladder(const word_map& words, const std::string& from, const std::string& to) { auto w = words.find(from.size()); if (w != words.end()) { auto poss = w->second; std::vector<std::vector<std::string>> queue{{from}}; while (!queue.empty()) { auto curr = queue.front(); queue.erase(queue.begin()); for (auto i = poss.begin(); i != poss.end();) { if (!one_away(*i, curr.back())) { ++i; continue; } if (to == *i) { curr.push_back(to); std::cout << join(curr.begin(), curr.end(), " -> ") << '\n'; return true; } std::vector<std::string> temp(curr); temp.push_back(*i); queue.push_back(std::move(temp)); i = poss.erase(i); } } } std::cout << from << " into " << to << " cannot be done.\n"; return false; } int main() { word_map words; std::ifstream in("unixdict.txt"); if (!in) { std::cerr << "Cannot open file unixdict.txt.\n"; return EXIT_FAILURE; } std::string word; while (getline(in, word)) words[word.size()].push_back(word); word_ladder(words, "boy", "man"); word_ladder(words, "girl", "lady"); word_ladder(words, "john", "jane"); word_ladder(words, "child", "adult"); word_ladder(words, "cat", "dog"); word_ladder(words, "lead", "gold"); word_ladder(words, "white", "black"); word_ladder(words, "bubble", "tickle"); return EXIT_SUCCESS; }
Port the following code from Python to C++ with equivalent syntax and logic.
import sys import pygame pygame.init() clk = pygame.time.Clock() if pygame.joystick.get_count() == 0: raise IOError("No joystick detected") joy = pygame.joystick.Joystick(0) joy.init() size = width, height = 600, 600 screen = pygame.display.set_mode(size) pygame.display.set_caption("Joystick Tester") frameRect = pygame.Rect((45, 45), (510, 510)) crosshair = pygame.surface.Surface((10, 10)) crosshair.fill(pygame.Color("magenta")) pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0) crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL) crosshair = crosshair.convert() writer = pygame.font.Font(pygame.font.get_default_font(), 15) buttons = {} for b in range(joy.get_numbuttons()): buttons[b] = [ writer.render( hex(b)[2:].upper(), 1, pygame.Color("red"), pygame.Color("black") ).convert(), ((15*b)+45, 560) ] while True: pygame.event.pump() for events in pygame.event.get(): if events.type == pygame.QUIT: pygame.quit() sys.exit() screen.fill(pygame.Color("black")) x = joy.get_axis(0) y = joy.get_axis(1) screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5)) pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1) for b in range(joy.get_numbuttons()): if joy.get_button(b): screen.blit(buttons[b][0], buttons[b][1]) pygame.display.flip() clk.tick(40)
#include <stdio.h> #include <stdlib.h> void clear() { for(int n = 0;n < 10; n++) { printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n"); } } #define UP "00^00\r\n00|00\r\n00000\r\n" #define DOWN "00000\r\n00|00\r\n00v00\r\n" #define LEFT "00000\r\n<--00\r\n00000\r\n" #define RIGHT "00000\r\n00-->\r\n00000\r\n" #define HOME "00000\r\n00+00\r\n00000\r\n" int main() { clear(); system("stty raw"); printf(HOME); printf("space to exit; wasd to move\r\n"); char c = 1; while(c) { c = getc(stdin); clear(); switch (c) { case 'a': printf(LEFT); break; case 'd': printf(RIGHT); break; case 'w': printf(UP); break; case 's': printf(DOWN); break; case ' ': c = 0; break; default: printf(HOME); }; printf("space to exit; wasd key to move\r\n"); } system("stty cooked"); system("clear"); return 1; }
Convert this Python block to C++, preserving its control flow and logic.
from primesieve import primes LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1] PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP1] GAP2 = GAP1 + 2 if GAP2 not in gapstarts: GAP1 = GAP2 + 2 continue start2 = gapstarts[GAP2] diff = abs(start2 - start1) if diff > PM: print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:") print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n") if PM == LIMIT: break PM *= 10 else: GAP1 = GAP2
#include <iostream> #include <locale> #include <unordered_map> #include <primesieve.hpp> class prime_gaps { public: prime_gaps() { last_prime_ = iterator_.next_prime(); } uint64_t find_gap_start(uint64_t gap); private: primesieve::iterator iterator_; uint64_t last_prime_; std::unordered_map<uint64_t, uint64_t> gap_starts_; }; uint64_t prime_gaps::find_gap_start(uint64_t gap) { auto i = gap_starts_.find(gap); if (i != gap_starts_.end()) return i->second; for (;;) { uint64_t prev = last_prime_; last_prime_ = iterator_.next_prime(); uint64_t diff = last_prime_ - prev; gap_starts_.emplace(diff, prev); if (gap == diff) return prev; } } int main() { std::cout.imbue(std::locale("")); const uint64_t limit = 100000000000; prime_gaps pg; for (uint64_t pm = 10, gap1 = 2;;) { uint64_t start1 = pg.find_gap_start(gap1); uint64_t gap2 = gap1 + 2; uint64_t start2 = pg.find_gap_start(gap2); uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2; if (diff > pm) { std::cout << "Earliest difference > " << pm << " between adjacent prime gap starting primes:\n" << "Gap " << gap1 << " starts at " << start1 << ", gap " << gap2 << " starts at " << start2 << ", difference is " << diff << ".\n\n"; if (pm == limit) break; pm *= 10; } else { gap1 = gap2; } } }
Produce a language-to-language conversion: from Python to C++, same semantics.
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: return b = [x + 1 for x in a] r.append(b) return for i in xrange(last, 0, -1): a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] recurse(n - 1) return r def printSquare(latin,n): for row in latin: print row print def reducedLatinSquares(n,echo): if n <= 0: if echo: print [] return 0 elif n == 1: if echo: print [1] return 1 rlatin = [None] * n for i in xrange(n): rlatin[i] = [None] * n for j in xrange(0, n): rlatin[0][j] = j + 1 class OuterScope: count = 0 def recurse(i): rows = dList(n, i) for r in xrange(len(rows)): rlatin[i - 1] = rows[r] justContinue = False k = 0 while not justContinue and k < i - 1: for j in xrange(1, n): if rlatin[k][j] == rlatin[i - 1][j]: if r < len(rows) - 1: justContinue = True break if i > 2: return k += 1 if not justContinue: if i < n: recurse(i + 1) else: OuterScope.count += 1 if echo: printSquare(rlatin, n) recurse(2) return OuterScope.count def factorial(n): if n == 0: return 1 prod = 1 for i in xrange(2, n + 1): prod *= i return prod print "The four reduced latin squares of order 4 are:\n" reducedLatinSquares(4,True) print "The size of the set of reduced latin squares for the following orders" print "and hence the total number of latin squares of these orders are:\n" for n in xrange(1, 7): size = reducedLatinSquares(n, False) f = factorial(n - 1) f *= f * n * size print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector> typedef std::vector<std::vector<int>> matrix; matrix dList(int n, int start) { start--; std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; std::sort(a.begin() + 1, a.end()); auto first = a[1]; matrix r; std::function<void(int)> recurse; recurse = [&](int last) { if (last == first) { for (size_t j = 1; j < a.size(); j++) { auto v = a[j]; if (j == v) { return; } } std::vector<int> b; std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; }); r.push_back(b); return; } for (int i = last; i >= 1; i--) { std::swap(a[i], a[last]); recurse(last - 1); std::swap(a[i], a[last]); } }; recurse(n - 1); return r; } void printSquare(const matrix &latin, int n) { for (auto &row : latin) { auto it = row.cbegin(); auto end = row.cend(); std::cout << '['; if (it != end) { std::cout << *it; it = std::next(it); } while (it != end) { std::cout << ", " << *it; it = std::next(it); } std::cout << "]\n"; } std::cout << '\n'; } unsigned long reducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { std::cout << "[]\n"; } return 0; } else if (n == 1) { if (echo) { std::cout << "[1]\n"; } return 1; } matrix rlatin; for (int i = 0; i < n; i++) { rlatin.push_back({}); for (int j = 0; j < n; j++) { rlatin[i].push_back(j); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } unsigned long count = 0; std::function<void(int)> recurse; recurse = [&](int i) { auto rows = dList(n, i); for (size_t r = 0; r < rows.size(); r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.size() - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { printSquare(rlatin, n); } } outer: {} } }; recurse(2); return count; } unsigned long factorial(unsigned long n) { if (n <= 0) return 1; unsigned long prod = 1; for (unsigned long i = 2; i <= n; i++) { prod *= i; } return prod; } int main() { std::cout << "The four reduced lating squares of order 4 are:\n"; reducedLatinSquares(4, true); std::cout << "The size of the set of reduced latin squares for the following orders\n"; std::cout << "and hence the total number of latin squares of these orders are:\n\n"; for (int n = 1; n < 7; n++) { auto size = reducedLatinSquares(n, false); auto f = factorial(n - 1); f *= f * n * size; std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n'; } return 0; }
Write the same algorithm in C++ as shown in this Python implementation.
from sympy import primerange PRIMES1M = list(primerange(1, 1_000_000)) ASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M] ORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M)) if ASBASE10SORT[i - 1] == ASBASE10SORT[i]] print('First 30 Ormiston pairs:') for (i, o) in enumerate(ORMISTONS): if i < 30: print(f'({o[0] : 6} {o[1] : 6} )', end='\n' if (i + 1) % 5 == 0 else ' ') else: break print(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')
#include <array> #include <iomanip> #include <iostream> #include <utility> #include <primesieve.hpp> class ormiston_pair_generator { public: ormiston_pair_generator() { prime_ = pi_.next_prime(); } std::pair<uint64_t, uint64_t> next_pair() { for (;;) { uint64_t prime = prime_; auto digits = digits_; prime_ = pi_.next_prime(); digits_ = get_digits(prime_); if (digits_ == digits) return std::make_pair(prime, prime_); } } private: static std::array<int, 10> get_digits(uint64_t n) { std::array<int, 10> result = {}; for (; n > 0; n /= 10) ++result[n % 10]; return result; } primesieve::iterator pi_; uint64_t prime_; std::array<int, 10> digits_; }; int main() { ormiston_pair_generator generator; int count = 0; std::cout << "First 30 Ormiston pairs:\n"; for (; count < 30; ++count) { auto [p1, p2] = generator.next_pair(); std::cout << '(' << std::setw(5) << p1 << ", " << std::setw(5) << p2 << ')' << ((count + 1) % 3 == 0 ? '\n' : ' '); } std::cout << '\n'; for (uint64_t limit = 1000000; limit <= 1000000000; ++count) { auto [p1, p2] = generator.next_pair(); if (p1 > limit) { std::cout << "Number of Ormiston pairs < " << limit << ": " << count << '\n'; limit *= 10; } } }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
import itertools import re RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" r"(?P<s_guard> r"(?P<left>[ r"(?P<m_guard> r"(?P<right>[ r"(?P<e_guard> r"(?P<e_quiet> +)$" ) LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1, 1, 1, 1, 0, 1): 3, (0, 1, 0, 0, 0, 1, 1): 4, (0, 1, 1, 0, 0, 0, 1): 5, (0, 1, 0, 1, 1, 1, 1): 6, (0, 1, 1, 1, 0, 1, 1): 7, (0, 1, 1, 0, 1, 1, 1): 8, (0, 0, 0, 1, 0, 1, 1): 9, } RIGHT_DIGITS = { (1, 1, 1, 0, 0, 1, 0): 0, (1, 1, 0, 0, 1, 1, 0): 1, (1, 1, 0, 1, 1, 0, 0): 2, (1, 0, 0, 0, 0, 1, 0): 3, (1, 0, 1, 1, 1, 0, 0): 4, (1, 0, 0, 1, 1, 1, 0): 5, (1, 0, 1, 0, 0, 0, 0): 6, (1, 0, 0, 0, 1, 0, 0): 7, (1, 0, 0, 1, 0, 0, 0): 8, (1, 1, 1, 0, 1, 0, 0): 9, } MODULES = { " ": 0, " } DIGITS_PER_SIDE = 6 MODULES_PER_DIGIT = 7 class ParityError(Exception): class ChecksumError(Exception): def group(iterable, n): args = [iter(iterable)] * n return tuple(itertools.zip_longest(*args)) def parse(barcode): match = RE_BARCODE.match(barcode) left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT) right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT) left, right = check_parity(left, right) return tuple( itertools.chain( (LEFT_DIGITS[d] for d in left), (RIGHT_DIGITS[d] for d in right), ) ) def check_parity(left, right): left_parity = sum(sum(d) % 2 for d in left) right_parity = sum(sum(d) % 2 for d in right) if left_parity == 0 and right_parity == DIGITS_PER_SIDE: _left = tuple(tuple(reversed(d)) for d in reversed(right)) right = tuple(tuple(reversed(d)) for d in reversed(left)) left = _left elif left_parity != DIGITS_PER_SIDE or right_parity != 0: error = tuple( itertools.chain( (LEFT_DIGITS.get(d, "_") for d in left), (RIGHT_DIGITS.get(d, "_") for d in right), ) ) raise ParityError(" ".join(str(d) for d in error)) return left, right def checksum(digits): odds = (digits[i] for i in range(0, 11, 2)) evens = (digits[i] for i in range(1, 10, 2)) check_digit = (sum(odds) * 3 + sum(evens)) % 10 if check_digit != 0: check_digit = 10 - check_digit if digits[-1] != check_digit: raise ChecksumError(str(check_digit)) return check_digit def main(): barcodes = [ " " " " " " " " " " " ] for barcode in barcodes: try: digits = parse(barcode) except ParityError as err: print(f"{err} parity error!") continue try: check_digit = checksum(digits) except ChecksumError as err: print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})") continue print(f"{' '.join(str(d) for d in digits)}") if __name__ == "__main__": main()
#include <iostream> #include <locale> #include <map> #include <vector> std::string trim(const std::string &str) { auto s = str; auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end()); auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(s.begin(), it2); return s; } template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } const std::map<std::string, int> LEFT_DIGITS = { {" ## #", 0}, {" ## #", 1}, {" # ##", 2}, {" #### #", 3}, {" # ##", 4}, {" ## #", 5}, {" # ####", 6}, {" ### ##", 7}, {" ## ###", 8}, {" # ##", 9} }; const std::map<std::string, int> RIGHT_DIGITS = { {"### # ", 0}, {"## ## ", 1}, {"## ## ", 2}, {"# # ", 3}, {"# ### ", 4}, {"# ### ", 5}, {"# # ", 6}, {"# # ", 7}, {"# # ", 8}, {"### # ", 9} }; const std::string END_SENTINEL = "# #"; const std::string MID_SENTINEL = " # # "; void decodeUPC(const std::string &input) { auto decode = [](const std::string &candidate) { using OT = std::vector<int>; OT output; size_t pos = 0; auto part = candidate.substr(pos, END_SENTINEL.length()); if (part == END_SENTINEL) { pos += END_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } for (size_t i = 0; i < 6; i++) { part = candidate.substr(pos, 7); pos += 7; auto e = LEFT_DIGITS.find(part); if (e != LEFT_DIGITS.end()) { output.push_back(e->second); } else { return std::make_pair(false, output); } } part = candidate.substr(pos, MID_SENTINEL.length()); if (part == MID_SENTINEL) { pos += MID_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } for (size_t i = 0; i < 6; i++) { part = candidate.substr(pos, 7); pos += 7; auto e = RIGHT_DIGITS.find(part); if (e != RIGHT_DIGITS.end()) { output.push_back(e->second); } else { return std::make_pair(false, output); } } part = candidate.substr(pos, END_SENTINEL.length()); if (part == END_SENTINEL) { pos += END_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } int sum = 0; for (size_t i = 0; i < output.size(); i++) { if (i % 2 == 0) { sum += 3 * output[i]; } else { sum += output[i]; } } return std::make_pair(sum % 10 == 0, output); }; auto candidate = trim(input); auto out = decode(candidate); if (out.first) { std::cout << out.second << '\n'; } else { std::reverse(candidate.begin(), candidate.end()); out = decode(candidate); if (out.first) { std::cout << out.second << " Upside down\n"; } else if (out.second.size()) { std::cout << "Invalid checksum\n"; } else { std::cout << "Invalid digit(s)\n"; } } } int main() { std::vector<std::string> barcodes = { " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", }; for (auto &barcode : barcodes) { decodeUPC(barcode); } return 0; }
Write the same code in C++ as shown below in Python.
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ ) { if( getCharPos( *ti++, a, b ) ) if( getCharPos( *ti, c, d ) ) { if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); } else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); } else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); } } } _txt = ntxt; } void display() { cout << "\n\n OUTPUT:\n=========" << endl; string::iterator si = _txt.begin(); int cnt = 0; while( si != _txt.end() ) { cout << *si; si++; cout << *si << " "; si++; if( ++cnt >= 26 ) cout << endl, cnt = 0; } cout << endl << endl; } char getChar( int a, int b ) { return _m[ (b + 5) % 5 ][ (a + 5) % 5 ]; } bool getCharPos( char l, int &a, int &b ) { for( int y = 0; y < 5; y++ ) for( int x = 0; x < 5; x++ ) if( _m[y][x] == l ) { a = x; b = y; return true; } return false; } void getTextReady( string t, bool ij, bool e ) { for( string::iterator si = t.begin(); si != t.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( *si == 'J' && ij ) *si = 'I'; else if( *si == 'Q' && !ij ) continue; _txt += *si; } if( e ) { string ntxt = ""; size_t len = _txt.length(); for( size_t x = 0; x < len; x += 2 ) { ntxt += _txt[x]; if( x + 1 < len ) { if( _txt[x] == _txt[x + 1] ) ntxt += 'X'; ntxt += _txt[x + 1]; } } _txt = ntxt; } if( _txt.length() & 1 ) _txt += 'X'; } void createGrid( string k, bool ij ) { if( k.length() < 1 ) k = "KEYWORD"; k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = ""; for( string::iterator si = k.begin(); si != k.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue; if( nk.find( *si ) == -1 ) nk += *si; } copy( nk.begin(), nk.end(), &_m[0][0] ); } string _txt; char _m[5][5]; }; int main( int argc, char* argv[] ) { string key, i, txt; bool ij, e; cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' ); cout << "Enter a en/decryption key: "; getline( cin, key ); cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' ); cout << "Enter the text: "; getline( cin, txt ); playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" ); }
Translate the given Python code snippet into C++ without altering its behavior.
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ ) { if( getCharPos( *ti++, a, b ) ) if( getCharPos( *ti, c, d ) ) { if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); } else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); } else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); } } } _txt = ntxt; } void display() { cout << "\n\n OUTPUT:\n=========" << endl; string::iterator si = _txt.begin(); int cnt = 0; while( si != _txt.end() ) { cout << *si; si++; cout << *si << " "; si++; if( ++cnt >= 26 ) cout << endl, cnt = 0; } cout << endl << endl; } char getChar( int a, int b ) { return _m[ (b + 5) % 5 ][ (a + 5) % 5 ]; } bool getCharPos( char l, int &a, int &b ) { for( int y = 0; y < 5; y++ ) for( int x = 0; x < 5; x++ ) if( _m[y][x] == l ) { a = x; b = y; return true; } return false; } void getTextReady( string t, bool ij, bool e ) { for( string::iterator si = t.begin(); si != t.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( *si == 'J' && ij ) *si = 'I'; else if( *si == 'Q' && !ij ) continue; _txt += *si; } if( e ) { string ntxt = ""; size_t len = _txt.length(); for( size_t x = 0; x < len; x += 2 ) { ntxt += _txt[x]; if( x + 1 < len ) { if( _txt[x] == _txt[x + 1] ) ntxt += 'X'; ntxt += _txt[x + 1]; } } _txt = ntxt; } if( _txt.length() & 1 ) _txt += 'X'; } void createGrid( string k, bool ij ) { if( k.length() < 1 ) k = "KEYWORD"; k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = ""; for( string::iterator si = k.begin(); si != k.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue; if( nk.find( *si ) == -1 ) nk += *si; } copy( nk.begin(), nk.end(), &_m[0][0] ); } string _txt; char _m[5][5]; }; int main( int argc, char* argv[] ) { string key, i, txt; bool ij, e; cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' ); cout << "Enter a en/decryption key: "; getline( cin, key ); cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' ); cout << "Enter the text: "; getline( cin, txt ); playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" ); }
Maintain the same structure and functionality when rewriting this code in C++.
from fractions import Fraction def harmonic_series(): n, h = Fraction(1), Fraction(1) while True: yield h h += 1 / (n + 1) n += 1 if __name__ == '__main__': from itertools import islice for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)): print(n, '/', d)
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/gmp.hpp> using integer = boost::multiprecision::mpz_int; using rational = boost::rational<integer>; class harmonic_generator { public: rational next() { rational result = term_; term_ += rational(1, ++n_); return result; } void reset() { n_ = 1; term_ = 1; } private: integer n_ = 1; rational term_ = 1; }; int main() { std::cout << "First 20 harmonic numbers:\n"; harmonic_generator hgen; for (int i = 1; i <= 20; ++i) std::cout << std::setw(2) << i << ". " << hgen.next() << '\n'; rational h; for (int i = 1; i <= 80; ++i) h = hgen.next(); std::cout << "\n100th harmonic number: " << h << "\n\n"; int n = 1; hgen.reset(); for (int i = 1; n <= 10; ++i) { if (hgen.next() > n) std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n'; } }
Write a version of this Python function in C++ with identical behavior.
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) mergers.append(merge_me) merge_me.seek(0) stack_tops = [f.read(1) for f in mergers] while stack_tops: c = min(stack_tops) sink.write(c) i = stack_tops.index(c) t = mergers[i].read(1) if t: stack_tops[i] = t else: del stack_tops[i] mergers[i].close() del mergers[i] def main(): input_file_too_large_for_memory = io.StringIO('678925341') t = list(input_file_too_large_for_memory.read()) t.sort() expect = ''.join(t) print('expect', expect) for memory_size in range(1,12): input_file_too_large_for_memory.seek(0) output_file_too_large_for_memory = io.StringIO() sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO) output_file_too_large_for_memory.seek(0) assert(output_file_too_large_for_memory.read() == expect) print('memory size {} passed'.format(memory_size)) if __name__ == '__main__': example = main example()
#include <iostream> #include <fstream> #include <queue> #include <string> #include <algorithm> #include <cstdio> int main(int argc, char* argv[]); void write_vals(int* const, const size_t, const size_t); std::string mergeFiles(size_t); struct Compare { bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 ) { return p1.first >= p2.first; } }; using ipair = std::pair<int,int>; using pairvector = std::vector<ipair>; using MinHeap = std::priority_queue< ipair, pairvector, Compare >; const size_t memsize = 32; const size_t chunksize = memsize / sizeof(int); const std::string tmp_prefix{"tmp_out_"}; const std::string tmp_suffix{".txt"}; const std::string merged_file{"merged.txt"}; void write_vals( int* const values, const size_t size, const size_t chunk ) { std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix); std::ofstream ofs(output_file.c_str()); for (int i=0; i<size; i++) ofs << values[i] << '\t'; ofs << '\n'; ofs.close(); } std::string mergeFiles(size_t chunks, const std::string& merge_file ) { std::ofstream ofs( merge_file.c_str() ); MinHeap minHeap; std::ifstream* ifs_tempfiles = new std::ifstream[chunks]; for (size_t i = 1; i<=chunks; i++) { int topval = 0; std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix); ifs_tempfiles[i-1].open( sorted_file.c_str() ); if (ifs_tempfiles[i-1].is_open()) { ifs_tempfiles[i-1] >> topval; ipair top(topval, (i-1)); minHeap.push( top ); } } while (minHeap.size() > 0) { int next_val = 0; ipair min_pair = minHeap.top(); minHeap.pop(); ofs << min_pair.first << ' '; std::flush(ofs); if ( ifs_tempfiles[min_pair.second] >> next_val) { ipair np( next_val, min_pair.second ); minHeap.push( np ); } } for (int i = 1; i <= chunks; i++) { ifs_tempfiles[i-1].close(); } ofs << '\n'; ofs.close(); delete[] ifs_tempfiles; return merged_file; } int main(int argc, char* argv[] ) { if (argc < 2) { std::cerr << "usage: ExternalSort <filename> \n"; return 1; } std::ifstream ifs( argv[1] ); if ( ifs.fail() ) { std::cerr << "error opening " << argv[1] << "\n"; return 2; } int* inputValues = new int[chunksize]; int chunk = 1; int val = 0; int count = 0; bool done = false; std::cout << "internal buffer is " << memsize << " bytes" << "\n"; while (ifs >> val) { done = false; inputValues[count] = val; count++; if (count == chunksize) { std::sort(inputValues, inputValues + count); write_vals(inputValues, count, chunk); chunk ++; count = 0; done = true; } } if (! done) { std::sort(inputValues, inputValues + count); write_vals(inputValues, count, chunk); } else { chunk --; } ifs.close(); delete[] inputValues; if ( chunk == 0 ) std::cout << "no data found\n"; else std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n"; return EXIT_SUCCESS; }
Convert the following code from Python to C++, ensuring the logic remains intact.
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) mergers.append(merge_me) merge_me.seek(0) stack_tops = [f.read(1) for f in mergers] while stack_tops: c = min(stack_tops) sink.write(c) i = stack_tops.index(c) t = mergers[i].read(1) if t: stack_tops[i] = t else: del stack_tops[i] mergers[i].close() del mergers[i] def main(): input_file_too_large_for_memory = io.StringIO('678925341') t = list(input_file_too_large_for_memory.read()) t.sort() expect = ''.join(t) print('expect', expect) for memory_size in range(1,12): input_file_too_large_for_memory.seek(0) output_file_too_large_for_memory = io.StringIO() sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO) output_file_too_large_for_memory.seek(0) assert(output_file_too_large_for_memory.read() == expect) print('memory size {} passed'.format(memory_size)) if __name__ == '__main__': example = main example()
#include <iostream> #include <fstream> #include <queue> #include <string> #include <algorithm> #include <cstdio> int main(int argc, char* argv[]); void write_vals(int* const, const size_t, const size_t); std::string mergeFiles(size_t); struct Compare { bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 ) { return p1.first >= p2.first; } }; using ipair = std::pair<int,int>; using pairvector = std::vector<ipair>; using MinHeap = std::priority_queue< ipair, pairvector, Compare >; const size_t memsize = 32; const size_t chunksize = memsize / sizeof(int); const std::string tmp_prefix{"tmp_out_"}; const std::string tmp_suffix{".txt"}; const std::string merged_file{"merged.txt"}; void write_vals( int* const values, const size_t size, const size_t chunk ) { std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix); std::ofstream ofs(output_file.c_str()); for (int i=0; i<size; i++) ofs << values[i] << '\t'; ofs << '\n'; ofs.close(); } std::string mergeFiles(size_t chunks, const std::string& merge_file ) { std::ofstream ofs( merge_file.c_str() ); MinHeap minHeap; std::ifstream* ifs_tempfiles = new std::ifstream[chunks]; for (size_t i = 1; i<=chunks; i++) { int topval = 0; std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix); ifs_tempfiles[i-1].open( sorted_file.c_str() ); if (ifs_tempfiles[i-1].is_open()) { ifs_tempfiles[i-1] >> topval; ipair top(topval, (i-1)); minHeap.push( top ); } } while (minHeap.size() > 0) { int next_val = 0; ipair min_pair = minHeap.top(); minHeap.pop(); ofs << min_pair.first << ' '; std::flush(ofs); if ( ifs_tempfiles[min_pair.second] >> next_val) { ipair np( next_val, min_pair.second ); minHeap.push( np ); } } for (int i = 1; i <= chunks; i++) { ifs_tempfiles[i-1].close(); } ofs << '\n'; ofs.close(); delete[] ifs_tempfiles; return merged_file; } int main(int argc, char* argv[] ) { if (argc < 2) { std::cerr << "usage: ExternalSort <filename> \n"; return 1; } std::ifstream ifs( argv[1] ); if ( ifs.fail() ) { std::cerr << "error opening " << argv[1] << "\n"; return 2; } int* inputValues = new int[chunksize]; int chunk = 1; int val = 0; int count = 0; bool done = false; std::cout << "internal buffer is " << memsize << " bytes" << "\n"; while (ifs >> val) { done = false; inputValues[count] = val; count++; if (count == chunksize) { std::sort(inputValues, inputValues + count); write_vals(inputValues, count, chunk); chunk ++; count = 0; done = true; } } if (! done) { std::sort(inputValues, inputValues + count); write_vals(inputValues, count, chunk); } else { chunk --; } ifs.close(); delete[] inputValues; if ( chunk == 0 ) std::cout << "no data found\n"; else std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n"; return EXIT_SUCCESS; }
Convert the following code from Python to C++, ensuring the logic remains intact.
class NG: def __init__(self, a1, a, b1, b): self.a1, self.a, self.b1, self.b = a1, a, b1, b def ingress(self, n): self.a, self.a1 = self.a1, self.a + self.a1 * n self.b, self.b1 = self.b1, self.b + self.b1 * n @property def needterm(self): return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1 @property def egress(self): n = self.a // self.b self.a, self.b = self.b, self.a - self.b * n self.a1, self.b1 = self.b1, self.a1 - self.b1 * n return n @property def egress_done(self): if self.needterm: self.a, self.b = self.a1, self.b1 return self.egress @property def done(self): return self.b == 0 and self.b1 == 0
class matrixNG { private: virtual void consumeTerm(){} virtual void consumeTerm(int n){} virtual const bool needTerm(){} protected: int cfn = 0, thisTerm; bool haveTerm = false; friend class NG; }; class NG_4 : public matrixNG { private: int a1, a, b1, b, t; const bool needTerm() { if (b1==0 and b==0) return false; if (b1==0 or b==0) return true; else thisTerm = a/b; if (thisTerm==(int)(a1/b1)){ t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; haveTerm=true; return false; } return true; } void consumeTerm(){a=a1; b=b1;} void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;} public: NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){} }; class NG : public ContinuedFraction { private: matrixNG* ng; ContinuedFraction* n[2]; public: NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;} NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;} const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;} const bool moreTerms(){ while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm(); return ng->haveTerm; } };
Preserve the algorithm and functionality while converting the code from Python to C++.
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, divmod(num, den) yield digit def get_term_num(rational): ans, dig, pwr = 0, 1, 0 for n in r2cf(rational): for _ in range(n): ans |= dig << pwr pwr += 1 dig ^= 1 return ans if __name__ == '__main__': print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20))) x = Fraction(83116, 51639) print(f"\n{x} is the {get_term_num(x):_}'th term.")
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<unsigned long> continued_fraction(const rational& r) { unsigned long a = r.numerator(); unsigned long b = r.denominator(); std::vector<unsigned long> result; do { result.push_back(a/b); unsigned long c = a; a = b; b = c % b; } while (a != 1); if (result.size() > 0 && result.size() % 2 == 0) { --result.back(); result.push_back(1); } return result; } unsigned long term_number(const rational& r) { unsigned long result = 0; unsigned long d = 1; unsigned long p = 0; for (unsigned long n : continued_fraction(r)) { for (unsigned long i = 0; i < n; ++i, ++p) result |= (d << p); d = !d; } return result; } int main() { rational term = 1; std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n"; for (int i = 1; i <= 20; ++i) { std::cout << std::setw(2) << i << ": " << term << '\n'; term = calkin_wilf_next(term); } rational r(83116, 51639); std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n"; }
Convert the following code from Python to C++, ensuring the logic remains intact.
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, divmod(num, den) yield digit def get_term_num(rational): ans, dig, pwr = 0, 1, 0 for n in r2cf(rational): for _ in range(n): ans |= dig << pwr pwr += 1 dig ^= 1 return ans if __name__ == '__main__': print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20))) x = Fraction(83116, 51639) print(f"\n{x} is the {get_term_num(x):_}'th term.")
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<unsigned long> continued_fraction(const rational& r) { unsigned long a = r.numerator(); unsigned long b = r.denominator(); std::vector<unsigned long> result; do { result.push_back(a/b); unsigned long c = a; a = b; b = c % b; } while (a != 1); if (result.size() > 0 && result.size() % 2 == 0) { --result.back(); result.push_back(1); } return result; } unsigned long term_number(const rational& r) { unsigned long result = 0; unsigned long d = 1; unsigned long p = 0; for (unsigned long n : continued_fraction(r)) { for (unsigned long i = 0; i < n; ++i, ++p) result |= (d << p); d = !d; } return result; } int main() { rational term = 1; std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n"; for (int i = 1; i <= 20; ++i) { std::cout << std::setw(2) << i << ": " << term << '\n'; term = calkin_wilf_next(term); } rational r(83116, 51639); std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n"; }
Change the following Python code into C++ without altering its purpose.
def facpropzeros(N, verbose = True): proportions = [0.0] * N fac, psum = 1, 0.0 for i in range(N): fac *= i + 1 d = list(str(fac)) psum += sum(map(lambda x: x == '0', d)) / len(d) proportions[i] = psum / (i + 1) if verbose: print("The mean proportion of 0 in factorials from 1 to {} is {}.".format(N, psum / N)) return proportions for n in [100, 1000, 10000]: facpropzeros(n) props = facpropzeros(47500, False) n = (next(i for i in reversed(range(len(props))) if props[i] > 0.16)) print("The mean proportion dips permanently below 0.16 at {}.".format(n + 2))
#include <array> #include <chrono> #include <iomanip> #include <iostream> #include <vector> auto init_zc() { std::array<int, 1000> zc; zc.fill(0); zc[0] = 3; for (int x = 1; x <= 9; ++x) { zc[x] = 2; zc[10 * x] = 2; zc[100 * x] = 2; for (int y = 10; y <= 90; y += 10) { zc[y + x] = 1; zc[10 * y + x] = 1; zc[10 * (y + x)] = 1; } } return zc; } template <typename clock_type> auto elapsed(const std::chrono::time_point<clock_type>& t0) { auto t1 = clock_type::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0); return duration.count(); } int main() { auto zc = init_zc(); auto t0 = std::chrono::high_resolution_clock::now(); int trail = 1, first = 0; double total = 0; std::vector<int> rfs{1}; std::cout << std::fixed << std::setprecision(10); for (int f = 2; f <= 50000; ++f) { int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size(); for (int j = trail - 1; j < len || carry != 0; ++j) { if (j < len) carry += rfs[j] * f; d999 = carry % 1000; if (j < len) rfs[j] = d999; else rfs.push_back(d999); zeroes += zc[d999]; carry /= 1000; } while (rfs[trail - 1] == 0) ++trail; d999 = rfs.back(); d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0; zeroes -= d999; int digits = rfs.size() * 3 - d999; total += double(zeroes) / digits; double ratio = total / f; if (ratio >= 0.16) first = 0; else if (first == 0) first = f; if (f == 100 || f == 1000 || f == 10000) { std::cout << "Mean proportion of zero digits in factorials to " << f << " is " << ratio << ". (" << elapsed(t0) << "ms)\n"; } } std::cout << "The mean proportion dips permanently below 0.16 at " << first << ". (" << elapsed(t0) << "ms)\n"; }
Convert the following code from Python to C++, ensuring the logic remains intact.
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
#include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator> typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t; double distance_between(const point_t& a, const point_t& b) { return std::sqrt(std::pow(b.first - a.first, 2) + std::pow(b.second - a.second, 2)); } std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) { if (points.size() < 2) { return { -1, { { 0, 0 }, { 0, 0 } } }; } auto minDistance = std::abs(distance_between(points.at(0), points.at(1))); points_t minPoints = { points.at(0), points.at(1) }; for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) { for (auto j = i + 1; j < std::end(points); ++j) { auto newDistance = std::abs(distance_between(*i, *j)); if (newDistance < minDistance) { minDistance = newDistance; minPoints.first = *i; minPoints.second = *j; } } } return { minDistance, minPoints }; } std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP, const std::vector<point_t>& yP) { if (xP.size() <= 3) { return find_closest_brute(xP); } auto N = xP.size(); auto xL = std::vector<point_t>(); auto xR = std::vector<point_t>(); std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL)); std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR)); auto xM = xP.at((N-1) / 2).first; auto yL = std::vector<point_t>(); auto yR = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { return p.first <= xM; }); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) { return p.first > xM; }); auto p1 = find_closest_optimized(xL, yL); auto p2 = find_closest_optimized(xR, yR); auto minPair = (p1.first <= p2.first) ? p1 : p2; auto yS = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) { return std::abs(xM - p.first) < minPair.first; }); auto result = minPair; for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) { for (auto k = i + 1; k != std::end(yS) && ((k->second - i->second) < minPair.first); ++k) { auto newDistance = std::abs(distance_between(*k, *i)); if (newDistance < result.first) { result = { newDistance, { *k, *i } }; } } } return result; } void print_point(const point_t& point) { std::cout << "(" << point.first << ", " << point.second << ")"; } int main(int argc, char * argv[]) { std::default_random_engine re(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now())); std::uniform_real_distribution<double> urd(-500.0, 500.0); std::vector<point_t> points(100); std::generate(std::begin(points), std::end(points), [&urd, &re]() { return point_t { 1000 + urd(re), 1000 + urd(re) }; }); auto answer = find_closest_brute(points); std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.first < b.first; }); auto xP = points; std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.second < b.second; }); auto yP = points; std::cout << "Min distance (brute): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); answer = find_closest_optimized(xP, yP); std::cout << "\nMin distance (optimized): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
#include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator> typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t; double distance_between(const point_t& a, const point_t& b) { return std::sqrt(std::pow(b.first - a.first, 2) + std::pow(b.second - a.second, 2)); } std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) { if (points.size() < 2) { return { -1, { { 0, 0 }, { 0, 0 } } }; } auto minDistance = std::abs(distance_between(points.at(0), points.at(1))); points_t minPoints = { points.at(0), points.at(1) }; for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) { for (auto j = i + 1; j < std::end(points); ++j) { auto newDistance = std::abs(distance_between(*i, *j)); if (newDistance < minDistance) { minDistance = newDistance; minPoints.first = *i; minPoints.second = *j; } } } return { minDistance, minPoints }; } std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP, const std::vector<point_t>& yP) { if (xP.size() <= 3) { return find_closest_brute(xP); } auto N = xP.size(); auto xL = std::vector<point_t>(); auto xR = std::vector<point_t>(); std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL)); std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR)); auto xM = xP.at((N-1) / 2).first; auto yL = std::vector<point_t>(); auto yR = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { return p.first <= xM; }); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) { return p.first > xM; }); auto p1 = find_closest_optimized(xL, yL); auto p2 = find_closest_optimized(xR, yR); auto minPair = (p1.first <= p2.first) ? p1 : p2; auto yS = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) { return std::abs(xM - p.first) < minPair.first; }); auto result = minPair; for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) { for (auto k = i + 1; k != std::end(yS) && ((k->second - i->second) < minPair.first); ++k) { auto newDistance = std::abs(distance_between(*k, *i)); if (newDistance < result.first) { result = { newDistance, { *k, *i } }; } } } return result; } void print_point(const point_t& point) { std::cout << "(" << point.first << ", " << point.second << ")"; } int main(int argc, char * argv[]) { std::default_random_engine re(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now())); std::uniform_real_distribution<double> urd(-500.0, 500.0); std::vector<point_t> points(100); std::generate(std::begin(points), std::end(points), [&urd, &re]() { return point_t { 1000 + urd(re), 1000 + urd(re) }; }); auto answer = find_closest_brute(points); std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.first < b.first; }); auto xP = points; std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.second < b.second; }); auto yP = points; std::cout << "Min distance (brute): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); answer = find_closest_optimized(xP, yP); std::cout << "\nMin distance (optimized): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); return 0; }
Transform the following Python implementation into C++, maintaining the same output and logic.
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
int i; void* address_of_i = &i;
Please provide an equivalent version of this Python code in C++.
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
class Animal { }; class Dog: public Animal { }; class Lab: public Dog { }; class Collie: public Dog { }; class Cat: public Animal { };
Transform the following Python implementation into C++, maintaining the same output and logic.
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
#include <map>
Rewrite the snippet below in C++ so it works the same as the original Python code.
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) / 2.0 colorMode(HSB) c = color(int(h * 255), int(s * 255), 255) set(x, y, c)
#include "colorwheelwidget.h" #include <QPainter> #include <QPaintEvent> #include <cmath> namespace { QColor hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - std::abs(std::fmod(hp, 2) - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return QColor(r * 255, g * 255, b * 255); } } ColorWheelWidget::ColorWheelWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Color Wheel")); resize(400, 400); } void ColorWheelWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); const QColor backgroundColor(0, 0, 0); const QColor white(255, 255, 255); painter.fillRect(event->rect(), backgroundColor); const int margin = 10; const double diameter = std::min(width(), height()) - 2*margin; QPointF center(width()/2.0, height()/2.0); QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0, diameter, diameter); for (int angle = 0; angle < 360; ++angle) { QColor color(hsvToRgb(angle, 1.0, 1.0)); QRadialGradient gradient(center, diameter/2.0); gradient.setColorAt(0, white); gradient.setColorAt(1, color); QBrush brush(gradient); QPen pen(brush, 1.0); painter.setPen(pen); painter.setBrush(brush); painter.drawPie(rect, angle * 16, 16); } }
Rewrite the snippet below in C++ so it works the same as the original Python code.
pal = [0] * 128 r = 42 g = 84 b = 126 rd = gd = bd = False def setup(): global buffer size(600, 600) frameRate(25) buffer = [None] * width * height for x in range(width): for y in range(width): value = int(((128 + (128 * sin(x / 32.0))) + (128 + (128 * cos(y / 32.0))) + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4) buffer[x + y * width] = value def draw(): global r, g, b, rd, gd, bd if r > 128: rd = True if not rd: r += 1 else: r-=1 if r < 0: rd = False if g > 128: gd = True if not gd: g += 1 else: g- = 1 if r < 0: gd = False if b > 128: bd = True if not bd: b += 1 else: b- = 1 if b < 0: bd = False for i in range(128): s_1 = sin(i * PI / 25) s_2 = sin(i * PI / 50 + PI / 4) pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128) loadPixels() for i, b in enumerate(buffer): pixels[i] = pal[(b + frameCount) % 127] updatePixels()
#include <windows.h> #include <math.h> #include <string> const int BMP_SIZE = 240, MY_TIMER = 987654; 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; } DWORD* bits() { return ( DWORD* )pBits; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class plasma { public: plasma() { currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear(); plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; int i, j, dst = 0; double temp; for( j = 0; j < BMP_SIZE * 2; j++ ) { for( i = 0; i < BMP_SIZE * 2; i++ ) { plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) ); plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 ); dst++; } } } void update() { DWORD dst; BYTE a, c1,c2, c3; currentTime += ( double )( rand() % 2 + 1 ); int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ), x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ), x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ), y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ), y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ), y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) ); int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3; DWORD* bits = _bmp.bits(); for( int j = 0; j < BMP_SIZE; j++ ) { dst = j * BMP_SIZE; for( int i= 0; i < BMP_SIZE; i++ ) { a = plasma2[src1] + plasma1[src2] + plasma2[src3]; c1 = a << 1; c2 = a << 2; c3 = a << 3; bits[dst + i] = RGB( c1, c2, c3 ); src1++; src2++; src3++; } src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE; } draw(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: void draw() { HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); } myBitmap _bmp; HWND _hwnd; float _ang; BYTE *plasma1, *plasma2; double currentTime; int _WD, _WV; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); SetTimer( _hwnd, MY_TIMER, 15, NULL ); _plasma.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_MY_PLASMA_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _plasma.update(); } void wnd::doTimer() { _plasma.update(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_PAINT: { PAINTSTRUCT ps; _inst->doPaint( BeginPaint( hWnd, &ps ) ); EndPaint( hWnd, &ps ); return 0; } case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_TIMER: _inst->doTimer(); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_PLASMA_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma; }; wnd* wnd::_inst = 0; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); }
Generate an equivalent C++ version of this Python code.
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumerate(array)}) _border = set((r, c) for r, c in product(range(-1, 4), repeat=2) if not 0 <= r <= 2 or not 0 <= c <= 2 ) _cell_coords = list(product(range(3), repeat=2)) def topple(self): g = self.grid for r, c in self._cell_coords: if g[(r, c)] >= 4: g[(r - 1, c)] += 1 g[(r + 1, c)] += 1 g[(r, c - 1)] += 1 g[(r, c + 1)] += 1 g[(r, c)] -= 4 return True return False def stabilise(self): while self.topple(): pass g = self.grid for row_col in self._border.intersection(g.keys()): del g[row_col] return self __pos__ = stabilise def __eq__(self, other): g = self.grid return all(g[row_col] == other.grid[row_col] for row_col in self._cell_coords) def __add__(self, other): g = self.grid ans = Sandpile("") for row_col in self._cell_coords: ans.grid[row_col] = g[row_col] + other.grid[row_col] return ans.stabilise() def __str__(self): g, txt = self.grid, [] for row in range(3): txt.append(' '.join(str(g[(row, col)]) for col in range(3))) return '\n'.join(txt) def __repr__(self): return f'{self.__class__.__name__}()' unstable = Sandpile() s1 = Sandpile() s2 = Sandpile() s3 = Sandpile("3 3 3 3 3 3 3 3 3") s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&); public: abelian_sandpile(); explicit abelian_sandpile(std::initializer_list<int> init); void stabilize(); bool is_stable() const; void topple(); abelian_sandpile& operator+=(const abelian_sandpile&); bool operator==(const abelian_sandpile&); private: int& cell_value(size_t row, size_t column) { return cells_[cell_index(row, column)]; } static size_t cell_index(size_t row, size_t column) { return row * sp_columns + column; } static size_t row_index(size_t cell_index) { return cell_index/sp_columns; } static size_t column_index(size_t cell_index) { return cell_index % sp_columns; } std::array<int, sp_cells> cells_; }; abelian_sandpile::abelian_sandpile() { cells_.fill(0); } abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) { assert(init.size() == sp_cells); std::copy(init.begin(), init.end(), cells_.begin()); } abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) { for (size_t i = 0; i < sp_cells; ++i) cells_[i] += other.cells_[i]; stabilize(); return *this; } bool abelian_sandpile::operator==(const abelian_sandpile& other) { return cells_ == other.cells_; } bool abelian_sandpile::is_stable() const { return std::none_of(cells_.begin(), cells_.end(), [](int a) { return a >= sp_limit; }); } void abelian_sandpile::topple() { for (size_t i = 0; i < sp_cells; ++i) { if (cells_[i] >= sp_limit) { cells_[i] -= sp_limit; size_t row = row_index(i); size_t column = column_index(i); if (row > 0) ++cell_value(row - 1, column); if (row + 1 < sp_rows) ++cell_value(row + 1, column); if (column > 0) ++cell_value(row, column - 1); if (column + 1 < sp_columns) ++cell_value(row, column + 1); break; } } } void abelian_sandpile::stabilize() { while (!is_stable()) topple(); } abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) { abelian_sandpile c(a); c += b; return c; } std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) { for (size_t i = 0; i < sp_cells; ++i) { if (i > 0) out << (as.column_index(i) == 0 ? '\n' : ' '); out << as.cells_[i]; } return out << '\n'; } int main() { std::cout << std::boolalpha; std::cout << "Avalanche:\n"; abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3}; while (!sp.is_stable()) { std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; sp.topple(); } std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; std::cout << "Commutativity:\n"; abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3}; abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0}; abelian_sandpile sum1(s1 + s2); abelian_sandpile sum2(s2 + s1); std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n"; std::cout << "s1 + s2 = \n" << sum1; std::cout << "\ns2 + s1 = \n" << sum2; std::cout << '\n'; std::cout << "Identity:\n"; abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3}; abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2}; abelian_sandpile sum3(s3 + s3_id); abelian_sandpile sum4(s3_id + s3_id); std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n'; std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n"; std::cout << "s3 + s3_id = \n" << sum3; std::cout << "\ns3_id + s3_id = \n" << sum4; return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumerate(array)}) _border = set((r, c) for r, c in product(range(-1, 4), repeat=2) if not 0 <= r <= 2 or not 0 <= c <= 2 ) _cell_coords = list(product(range(3), repeat=2)) def topple(self): g = self.grid for r, c in self._cell_coords: if g[(r, c)] >= 4: g[(r - 1, c)] += 1 g[(r + 1, c)] += 1 g[(r, c - 1)] += 1 g[(r, c + 1)] += 1 g[(r, c)] -= 4 return True return False def stabilise(self): while self.topple(): pass g = self.grid for row_col in self._border.intersection(g.keys()): del g[row_col] return self __pos__ = stabilise def __eq__(self, other): g = self.grid return all(g[row_col] == other.grid[row_col] for row_col in self._cell_coords) def __add__(self, other): g = self.grid ans = Sandpile("") for row_col in self._cell_coords: ans.grid[row_col] = g[row_col] + other.grid[row_col] return ans.stabilise() def __str__(self): g, txt = self.grid, [] for row in range(3): txt.append(' '.join(str(g[(row, col)]) for col in range(3))) return '\n'.join(txt) def __repr__(self): return f'{self.__class__.__name__}()' unstable = Sandpile() s1 = Sandpile() s2 = Sandpile() s3 = Sandpile("3 3 3 3 3 3 3 3 3") s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&); public: abelian_sandpile(); explicit abelian_sandpile(std::initializer_list<int> init); void stabilize(); bool is_stable() const; void topple(); abelian_sandpile& operator+=(const abelian_sandpile&); bool operator==(const abelian_sandpile&); private: int& cell_value(size_t row, size_t column) { return cells_[cell_index(row, column)]; } static size_t cell_index(size_t row, size_t column) { return row * sp_columns + column; } static size_t row_index(size_t cell_index) { return cell_index/sp_columns; } static size_t column_index(size_t cell_index) { return cell_index % sp_columns; } std::array<int, sp_cells> cells_; }; abelian_sandpile::abelian_sandpile() { cells_.fill(0); } abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) { assert(init.size() == sp_cells); std::copy(init.begin(), init.end(), cells_.begin()); } abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) { for (size_t i = 0; i < sp_cells; ++i) cells_[i] += other.cells_[i]; stabilize(); return *this; } bool abelian_sandpile::operator==(const abelian_sandpile& other) { return cells_ == other.cells_; } bool abelian_sandpile::is_stable() const { return std::none_of(cells_.begin(), cells_.end(), [](int a) { return a >= sp_limit; }); } void abelian_sandpile::topple() { for (size_t i = 0; i < sp_cells; ++i) { if (cells_[i] >= sp_limit) { cells_[i] -= sp_limit; size_t row = row_index(i); size_t column = column_index(i); if (row > 0) ++cell_value(row - 1, column); if (row + 1 < sp_rows) ++cell_value(row + 1, column); if (column > 0) ++cell_value(row, column - 1); if (column + 1 < sp_columns) ++cell_value(row, column + 1); break; } } } void abelian_sandpile::stabilize() { while (!is_stable()) topple(); } abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) { abelian_sandpile c(a); c += b; return c; } std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) { for (size_t i = 0; i < sp_cells; ++i) { if (i > 0) out << (as.column_index(i) == 0 ? '\n' : ' '); out << as.cells_[i]; } return out << '\n'; } int main() { std::cout << std::boolalpha; std::cout << "Avalanche:\n"; abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3}; while (!sp.is_stable()) { std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; sp.topple(); } std::cout << sp << "stable? " << sp.is_stable() << "\n\n"; std::cout << "Commutativity:\n"; abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3}; abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0}; abelian_sandpile sum1(s1 + s2); abelian_sandpile sum2(s2 + s1); std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n"; std::cout << "s1 + s2 = \n" << sum1; std::cout << "\ns2 + s1 = \n" << sum2; std::cout << '\n'; std::cout << "Identity:\n"; abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3}; abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2}; abelian_sandpile sum3(s3 + s3_id); abelian_sandpile sum4(s3_id + s3_id); std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n'; std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n"; std::cout << "s3 + s3_id = \n" << sum3; std::cout << "\ns3_id + s3_id = \n" << sum4; return 0; }
Generate an equivalent C++ version of this Python code.
print "Goodbye, World!"
#include <iostream> int main() { using namespace std; cout << "Hello, World!" << endl; return 0; }
Produce a language-to-language conversion: from Python to C++, same semantics.
print "Goodbye, World!"
#include <iostream> int main() { using namespace std; cout << "Hello, World!" << endl; return 0; }
Translate the given Python code snippet into C++ without altering its behavior.
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
#include <cstdio> #include <cstdlib> class Point { protected: int x, y; public: Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {} Point(const Point &p) : x(p.x), y(p.y) {} virtual ~Point() {} const Point& operator=(const Point &p) { if (this != &p) { x = p.x; y = p.y; } return *this; } int getX() { return x; } int getY() { return y; } void setX(int x0) { x = x0; } void setY(int y0) { y = y0; } virtual void print() { printf("Point\n"); } }; class Circle: public Point { private: int r; public: Circle(Point p, int r0 = 0) : Point(p), r(r0) {} Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {} virtual ~Circle() {} const Circle& operator=(const Circle &c) { if (this != &c) { x = c.x; y = c.y; r = c.r; } return *this; } int getR() { return r; } void setR(int r0) { r = r0; } virtual void print() { printf("Circle\n"); } }; int main() { Point *p = new Point(); Point *c = new Circle(); p->print(); c->print(); delete p; delete c; return EXIT_SUCCESS; }
Port the following code from Python to C++ with equivalent syntax and logic.
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]') wagstaff(24)
#include <gmpxx.h> #include <primesieve.hpp> #include <iostream> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += " ("; str += std::to_string(len); str += " digits)"; } return str; } bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } int main() { const big_int one(1); primesieve::iterator pi; pi.next_prime(); for (int i = 0; i < 24;) { uint64_t p = pi.next_prime(); big_int n = ((one << p) + 1) / 3; if (is_probably_prime(n)) std::cout << ++i << ": " << p << " - " << to_string(n, 30) << '\n'; } }
Produce a functionally identical C++ code for the snippet given in Python.
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]') wagstaff(24)
#include <gmpxx.h> #include <primesieve.hpp> #include <iostream> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += " ("; str += std::to_string(len); str += " digits)"; } return str; } bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } int main() { const big_int one(1); primesieve::iterator pi; pi.next_prime(); for (int i = 0; i < 24;) { uint64_t p = pi.next_prime(); big_int n = ((one << p) + 1) / 3; if (is_probably_prime(n)) std::cout << ++i << ": " << p << " - " << to_string(n, 30) << '\n'; } }
Convert this Python block to C++, preserving its control flow and logic.
from collections import UserDict import copy class Dict(UserDict): def __init__(self, dict=None, **kwargs): self.__init = True super().__init__(dict, **kwargs) self.default = copy.deepcopy(self.data) self.__init = False def __delitem__(self, key): if key in self.default: self.data[key] = self.default[key] else: raise NotImplementedError def __setitem__(self, key, item): if self.__init: super().__setitem__(key, item) elif key in self.data: self.data[key] = item else: raise KeyError def __repr__(self): return "%s(%s)" % (type(self).__name__, super().__repr__()) def fromkeys(cls, iterable, value=None): if self.__init: super().fromkeys(cls, iterable, value) else: for key in iterable: if key in self.data: self.data[key] = value else: raise KeyError def clear(self): self.data.update(copy.deepcopy(self.default)) def pop(self, key, default=None): raise NotImplementedError def popitem(self): raise NotImplementedError def update(self, E, **F): if self.__init: super().update(E, **F) else: haskeys = False try: keys = E.keys() haskeys = Ture except AttributeError: pass if haskeys: for key in keys: self[key] = E[key] else: for key, val in E: self[key] = val for key in F: self[key] = F[key] def setdefault(self, key, default=None): if key not in self.data: raise KeyError else: return super().setdefault(key, default)
#include <iostream> #include <map> #include <utility> using namespace std; template<typename T> class FixedMap : private T { T m_defaultValues; public: FixedMap(T map) : T(map), m_defaultValues(move(map)){} using T::cbegin; using T::cend; using T::empty; using T::find; using T::size; using T::at; using T::begin; using T::end; auto& operator[](typename T::key_type&& key) { return this->at(forward<typename T::key_type>(key)); } void erase(typename T::key_type&& key) { T::operator[](key) = m_defaultValues.at(key); } void clear() { T::operator=(m_defaultValues); } }; auto PrintMap = [](const auto &map) { for(auto &[key, value] : map) { cout << "{" << key << " : " << value << "} "; } cout << "\n\n"; }; int main(void) { cout << "Map intialized with values\n"; FixedMap<map<string, int>> fixedMap ({ {"a", 1}, {"b", 2}}); PrintMap(fixedMap); cout << "Change the values of the keys\n"; fixedMap["a"] = 55; fixedMap["b"] = 56; PrintMap(fixedMap); cout << "Reset the 'a' key\n"; fixedMap.erase("a"); PrintMap(fixedMap); cout << "Change the values the again\n"; fixedMap["a"] = 88; fixedMap["b"] = 99; PrintMap(fixedMap); cout << "Reset all keys\n"; fixedMap.clear(); PrintMap(fixedMap); try { cout << "Try to add a new key\n"; fixedMap["newKey"] = 99; } catch (exception &ex) { cout << "error: " << ex.what(); } }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from itertools import groupby def magic_numbers(base): hist = [] n = l = i = 0 while True: l += 1 hist.extend((n + digit, l) for digit in range(-n % l, base, l)) i += 1 if i == len(hist): return hist n, l = hist[i] n *= base mn = magic_numbers(10) print("found", len(mn), "magic numbers") print("the largest one is", mn[-1][0]) print("count by number of digits:") print(*(f"{l}:{sum(1 for _ in g)}" for l, g in groupby(l for _, l in mn))) print(end="minimally pandigital in 1..9: ") print(*(m for m, l in mn if l == 9 == len(set(str(m)) - {"0"}))) print(end="minimally pandigital in 0..9: ") print(*(m for m, l in mn if l == 10 == len(set(str(m)))))
#include <array> #include <iostream> #include <numeric> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::uint128_t; class magic_number_generator { public: magic_number_generator() : magic_(10) { std::iota(magic_.begin(), magic_.end(), 0); } bool next(uint128_t& n); public: std::vector<uint128_t> magic_; size_t index_ = 0; int digits_ = 2; }; bool magic_number_generator::next(uint128_t& n) { if (index_ == magic_.size()) { std::vector<uint128_t> magic; for (uint128_t m : magic_) { if (m == 0) continue; uint128_t n = 10 * m; for (int d = 0; d < 10; ++d, ++n) { if (n % digits_ == 0) magic.push_back(n); } } index_ = 0; ++digits_; magic_ = std::move(magic); } if (magic_.empty()) return false; n = magic_[index_++]; return true; } std::array<int, 10> get_digits(uint128_t n) { std::array<int, 10> result = {}; for (; n > 0; n /= 10) ++result[static_cast<int>(n % 10)]; return result; } int main() { int count = 0, dcount = 0; uint128_t magic = 0, p = 10; std::vector<int> digit_count; std::array<int, 10> digits0 = {1,1,1,1,1,1,1,1,1,1}; std::array<int, 10> digits1 = {0,1,1,1,1,1,1,1,1,1}; std::vector<uint128_t> pandigital0, pandigital1; for (magic_number_generator gen; gen.next(magic);) { if (magic >= p) { p *= 10; digit_count.push_back(dcount); dcount = 0; } auto digits = get_digits(magic); if (digits == digits0) pandigital0.push_back(magic); else if (digits == digits1) pandigital1.push_back(magic); ++count; ++dcount; } digit_count.push_back(dcount); std::cout << "There are " << count << " magic numbers.\n\n"; std::cout << "The largest magic number is " << magic << ".\n\n"; std::cout << "Magic number count by digits:\n"; for (int i = 0; i < digit_count.size(); ++i) std::cout << i + 1 << '\t' << digit_count[i] << '\n'; std::cout << "\nMagic numbers that are minimally pandigital in 1-9:\n"; for (auto m : pandigital1) std::cout << m << '\n'; std::cout << "\nMagic numbers that are minimally pandigital in 0-9:\n"; for (auto m : pandigital0) std::cout << m << '\n'; }
Generate a C++ translation of this Python snippet without changing its computational steps.
from collections import deque from typing import Iterable from typing import Iterator from typing import Reversible days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] colors = deque( [ "red", "yellow", "pink", "green", "purple", "orange", "blue", ] ) class MyIterable: class MyIterator: def __init__(self) -> None: self._day = -1 def __iter__(self): return self def __next__(self): if self._day >= 6: raise StopIteration self._day += 1 return days[self._day] class MyReversedIterator: def __init__(self) -> None: self._day = 7 def __iter__(self): return self def __next__(self): if self._day <= 0: raise StopIteration self._day -= 1 return days[self._day] def __iter__(self): return self.MyIterator() def __reversed__(self): return self.MyReversedIterator() def print_elements(container: Iterable[object]) -> None: for element in container: print(element, end=" ") print("") def _drop(it: Iterator[object], n: int) -> None: try: for _ in range(n): next(it) except StopIteration: pass def print_first_fourth_fifth(container: Iterable[object]) -> None: it = iter(container) print(next(it), end=" ") _drop(it, 2) print(next(it), end=" ") print(next(it)) def print_reversed_first_fourth_fifth(container: Reversible[object]) -> None: it = reversed(container) print(next(it), end=" ") _drop(it, 2) print(next(it), end=" ") print(next(it)) def main() -> None: my_iterable = MyIterable() print("All elements:") print_elements(days) print_elements(colors) print_elements(my_iterable) print("\nFirst, fourth, fifth:") print_first_fourth_fifth(days) print_first_fourth_fifth(colors) print_first_fourth_fifth(my_iterable) print("\nLast, fourth to last, fifth to last:") print_reversed_first_fourth_fifth(days) print_reversed_first_fourth_fifth(colors) print_reversed_first_fourth_fifth(my_iterable) if __name__ == "__main__": main()
#include <iostream> #include <list> #include <string> #include <vector> using namespace std; void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) { for(auto it = start; it != sentinel; ++it) { cout << *it << " "; } cout << "\n"; } void FirstFourthFifth(input_iterator auto it) { cout << *it; advance(it, 3); cout << ", " << *it; advance(it, 1); cout << ", " << *it; cout << "\n"; } int main() { vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; list<string> colors{"Red", "Orange", "Yellow", "Green", "Blue", "Purple"}; cout << "All elements:\n"; PrintContainer(days.begin(), days.end()); PrintContainer(colors.begin(), colors.end()); cout << "\nFirst, fourth, and fifth elements:\n"; FirstFourthFifth(days.begin()); FirstFourthFifth(colors.begin()); cout << "\nReverse first, fourth, and fifth elements:\n"; FirstFourthFifth(days.rbegin()); FirstFourthFifth(colors.rbegin()); }
Translate the given Python code snippet into C++ without altering its behavior.
from collections import deque from typing import Iterable from typing import Iterator from typing import Reversible days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] colors = deque( [ "red", "yellow", "pink", "green", "purple", "orange", "blue", ] ) class MyIterable: class MyIterator: def __init__(self) -> None: self._day = -1 def __iter__(self): return self def __next__(self): if self._day >= 6: raise StopIteration self._day += 1 return days[self._day] class MyReversedIterator: def __init__(self) -> None: self._day = 7 def __iter__(self): return self def __next__(self): if self._day <= 0: raise StopIteration self._day -= 1 return days[self._day] def __iter__(self): return self.MyIterator() def __reversed__(self): return self.MyReversedIterator() def print_elements(container: Iterable[object]) -> None: for element in container: print(element, end=" ") print("") def _drop(it: Iterator[object], n: int) -> None: try: for _ in range(n): next(it) except StopIteration: pass def print_first_fourth_fifth(container: Iterable[object]) -> None: it = iter(container) print(next(it), end=" ") _drop(it, 2) print(next(it), end=" ") print(next(it)) def print_reversed_first_fourth_fifth(container: Reversible[object]) -> None: it = reversed(container) print(next(it), end=" ") _drop(it, 2) print(next(it), end=" ") print(next(it)) def main() -> None: my_iterable = MyIterable() print("All elements:") print_elements(days) print_elements(colors) print_elements(my_iterable) print("\nFirst, fourth, fifth:") print_first_fourth_fifth(days) print_first_fourth_fifth(colors) print_first_fourth_fifth(my_iterable) print("\nLast, fourth to last, fifth to last:") print_reversed_first_fourth_fifth(days) print_reversed_first_fourth_fifth(colors) print_reversed_first_fourth_fifth(my_iterable) if __name__ == "__main__": main()
#include <iostream> #include <list> #include <string> #include <vector> using namespace std; void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) { for(auto it = start; it != sentinel; ++it) { cout << *it << " "; } cout << "\n"; } void FirstFourthFifth(input_iterator auto it) { cout << *it; advance(it, 3); cout << ", " << *it; advance(it, 1); cout << ", " << *it; cout << "\n"; } int main() { vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; list<string> colors{"Red", "Orange", "Yellow", "Green", "Blue", "Purple"}; cout << "All elements:\n"; PrintContainer(days.begin(), days.end()); PrintContainer(colors.begin(), colors.end()); cout << "\nFirst, fourth, and fifth elements:\n"; FirstFourthFifth(days.begin()); FirstFourthFifth(colors.begin()); cout << "\nReverse first, fourth, and fifth elements:\n"; FirstFourthFifth(days.rbegin()); FirstFourthFifth(colors.rbegin()); }
Convert this Python block to C++, preserving its control flow and logic.
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return int(str(n)[::-1]) def is_palindrome(n): return n == reverse(n) def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) ) if __name__ == '__main__': main()
#include <functional> #include <bitset> #include <cmath> using namespace std; using Z2 = optional<long long>; using Z1 = function<Z2()>; constexpr auto pow10 = [] { array <long long, 19> n {1}; for (int j{0}, i{1}; i < 19; j = i++) n[i] = n[j] * 10; return n; } (); long long acc, l; bool izRev(int n, unsigned long long i, unsigned long long g) { return (i / pow10[n - 1] != g % 10) ? false : n < 2 ? true : izRev(n - 1, i % pow10[n - 1], g / 10); } const Z1 fG(Z1 n, int start, int end, int reset, const long long step, long long &l) { return [n, i{step * start}, g{step * end}, e{step * reset}, &l, step] () mutable { while (i<g){i+=step; return Z2(l+=step);} l-=g-(i=e); return n();}; } struct nLH { vector<unsigned long long>even{}, odd{}; nLH(const Z1 a, const vector<long long> b, long long llim){while (auto i = a()) for (auto ng : b) if(ng>0 | *i>llim){unsigned long long sq{ng+ *i}, r{sqrt(sq)}; if (r*r == sq) ng&1 ? odd.push_back(sq) : even.push_back(sq);}} }; const double fac = 3.94; const int mbs = (int)sqrt(fac * pow10[9]), mbt = (int)sqrt(fac * fac * pow10[9]) >> 3; const bitset<100000>bs {[]{bitset<100000>n{false}; for(int g{3};g<mbs;++g) n[(g*g)%100000]=true; return n;}()}; constexpr array<const int, 7>li{1,3,0,0,1,1,1},lin{0,-7,0,0,-8,-3,-9},lig{0,9,0,0,8,7,9},lil{0,2,0,0,2,10,2}; const nLH makeL(const int n){ constexpr int r{9}; acc=0; Z1 g{[]{return Z2{};}}; int s{-r}, q{(n>11)*5}; vector<long long> w{}; for (int i{1};i<n/2-q+1;++i){l=pow10[n-i-q]-pow10[i+q-1]; s-=i==n/2-q; g=fG(g,s,r,-r,l,acc+=l*s);} if(q){long long g0{0}, g1{0}, g2{0}, g3{0}, g4{0}, l3{pow10[n-5]}; while (g0<7){const long long g{-10000*g4-1000*g3-100*g2-10*g1-g0}; if (bs[(g+1000000000000LL)%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g); if(g4<r) ++g4; else{g4= -r; if(g3<r) ++g3; else{g3= -r; if(g2<r) ++g2; else{g2= -r; if(g1<lig[g0]) g1+=lil[g0]; else {g0+=li[g0];g1=lin[g0];}}}}}} return q ? nLH(g,w,0) : nLH(g,{0},0); } const bitset<100000>bt {[]{bitset<100000>n{false}; for(int g{11};g<mbt;++g) n[(g*g)%100000]=true; return n;}()}; constexpr array<const int, 17>lu{0,0,0,0,2,0,4,0,0,0,1,4,0,0,0,1,1},lun{0,0,0,0,0,0,1,0,0,0,9,1,0,0,0,1,0},lug{0,0,0,0,18,0,17,0,0,0,9,17,0,0,0,11,18},lul{0,0,0,0,2,0,2,0,0,0,0,2,0,0,0,10,2}; const nLH makeH(const int n){ acc= -pow10[n>>1]-pow10[(n-1)>>1]; Z1 g{[]{ return Z2{};}}; int q{(n>11)*5}; vector<long long> w {}; for (int i{1}; i<(n>>1)-q+1; ++i) g = fG(g,0,18,0,pow10[n-i-q]+pow10[i+q-1], acc); if (n & 1){l=pow10[n>>1]<<1; g=fG(g,0,9,0,l,acc+=l);} if(q){long long g0{4}, g1{0}, g2{0}, g3{0}, g4{0},l3{pow10[n-5]}; while (g0<17){const long long g{g4*10000+g3*1000+g2*100+g1*10+g0}; if (bt[g%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g); if (g4<18) ++g4; else{g4=0; if(g3<18) ++g3; else{g3=0; if(g2<18) ++g2; else{g2=0; if(g1<lug[g0]) g1+=lul[g0]; else{g0+=lu[g0];g1=lun[g0];}}}}}} return q ? nLH(g,w,0) : nLH(g,{0},pow10[n-1]<<2); } #include <chrono> using namespace chrono; using VU = vector<unsigned long long>; using VS = vector<string>; template <typename T> vector<T>& operator +=(vector<T>& v, const vector<T>& w) { v.insert(v.end(), w.begin(), w.end()); return v; } int c{0}; auto st{steady_clock::now()}, st0{st}, tmp{st}; string dFmt(duration<double> et, int digs) { string res{""}; double dt{et.count()}; if (dt > 60.0) { int m = (int)(dt / 60.0); dt -= m * 60.0; res = to_string(m) + "m"; } res += to_string(dt); return res.substr(0, digs - 1) + 's'; } VS dump(int nd, VU lo, VU hi) { VS res {}; for (auto l : lo) for (auto h : hi) { auto r { (h - l) >> 1 }, z { h - r }; if (izRev(nd, r, z)) { char buf[99]; sprintf(buf, "%20llu %11lu %10lu", z, (long long)sqrt(h), (long long)sqrt(l)); res.push_back(buf); } } return res; } void doOne(int n, nLH L, nLH H) { VS lines = dump(n, L.even, H.even); lines += dump(n, L.odd , H.odd); sort(lines.begin(), lines.end()); duration<double> tet = (tmp = steady_clock::now()) - st; int ls = lines.size(); if (ls-- > 0) for (int i{0}; i <= ls; ++i) printf("%3d %s%s", ++c, lines[i].c_str(), i == ls ? "" : "\n"); else printf("%s", string(47, ' ').c_str()); printf(" %2d: %s %s\n", n, dFmt(tmp - st0, 8).c_str(), dFmt(tet, 8).c_str()); st0 = tmp; } void Rare(int n) { doOne(n, makeL(n), makeH(n)); } int main(int argc, char *argv[]) { int max{argc > 1 ? stoi(argv[1]) : 19}; if (max < 2) max = 2; if (max > 19 ) max = 19; printf("%4s %19s %11s %10s %5s %11s %9s\n", "nth", "forward", "rt.sum", "rt.diff", "digs", "block.et", "total.et"); for (int nd{2}; nd <= max; ++nd) Rare(nd); }
Change the programming language of this snippet from Python to C++ without modifying what it does.
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)] if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
#include <bitset> #include <cctype> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> size_t consonants(const std::string& word) { std::bitset<26> bits; size_t bit = 0; for (char ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); if (ch < 'a' || ch > 'z') continue; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: bit = ch - 'a'; if (bits.test(bit)) return 0; bits.set(bit); break; } } return bits.count(); } 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 word; std::map<size_t, std::vector<std::string>, std::greater<int>> map; while (getline(in, word)) { if (word.size() <= 10) continue; size_t count = consonants(word); if (count != 0) map[count].push_back(word); } const int columns = 4; for (const auto& p : map) { std::cout << p.first << " consonants (" << p.second.size() << "):\n"; int n = 0; for (const auto& word : p.second) { std::cout << std::left << std::setw(18) << word; ++n; if (n % columns == 0) std::cout << '\n'; } if (n % columns != 0) std::cout << '\n'; std::cout << '\n'; } return EXIT_SUCCESS; }
Write the same algorithm in C++ as shown in this Python implementation.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" 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; prime_sieve sieve(UCHAR_MAX); auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); }; int n = 0; while (getline(in, line)) { if (std::all_of(line.begin(), line.end(), is_prime)) { ++n; std::cout << std::right << std::setw(2) << n << ": " << std::left << std::setw(10) << line; if (n % 4 == 0) std::cout << '\n'; } } return EXIT_SUCCESS; }
Translate the given Python code snippet into C++ without altering its behavior.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" 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; prime_sieve sieve(UCHAR_MAX); auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); }; int n = 0; while (getline(in, line)) { if (std::all_of(line.begin(), line.end(), is_prime)) { ++n; std::cout << std::right << std::setw(2) << n << ": " << std::left << std::setw(10) << line; if (n % 4 == 0) std::cout << '\n'; } } return EXIT_SUCCESS; }
Translate the given Python code snippet into C++ without altering its behavior.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" 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; prime_sieve sieve(UCHAR_MAX); auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); }; int n = 0; while (getline(in, line)) { if (std::all_of(line.begin(), line.end(), is_prime)) { ++n; std::cout << std::right << std::setw(2) << n << ": " << std::left << std::setw(10) << line; if (n % 4 == 0) std::cout << '\n'; } } return EXIT_SUCCESS; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
def Riordan(N): a = [1, 0, 1] for n in range(3, N): a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1)) return a rios = Riordan(10_000) for i in range(32): print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '') print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.') print(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; if (n == 1) return a1_; big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1); a0_ = a1_; a1_ = a; return a; } std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); return str; } int main() { riordan_number_generator rng; std::cout << "First 32 Riordan numbers:\n"; int i = 1; for (; i <= 32; ++i) { std::cout << std::setw(14) << rng.next() << (i % 4 == 0 ? '\n' : ' '); } for (; i < 1000; ++i) rng.next(); auto num = rng.next(); ++i; std::cout << "\nThe 1000th is " << to_string(num, 40) << " (" << num.get_str().size() << " digits).\n"; for (; i < 10000; ++i) rng.next(); num = rng.next(); std::cout << "The 10000th is " << to_string(num, 40) << " (" << num.get_str().size() << " digits).\n"; }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
def Riordan(N): a = [1, 0, 1] for n in range(3, N): a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1)) return a rios = Riordan(10_000) for i in range(32): print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '') print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.') print(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; if (n == 1) return a1_; big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1); a0_ = a1_; a1_ = a; return a; } std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); return str; } int main() { riordan_number_generator rng; std::cout << "First 32 Riordan numbers:\n"; int i = 1; for (; i <= 32; ++i) { std::cout << std::setw(14) << rng.next() << (i % 4 == 0 ? '\n' : ' '); } for (; i < 1000; ++i) rng.next(); auto num = rng.next(); ++i; std::cout << "\nThe 1000th is " << to_string(num, 40) << " (" << num.get_str().size() << " digits).\n"; for (; i < 10000; ++i) rng.next(); num = rng.next(); std::cout << "The 10000th is " << to_string(num, 40) << " (" << num.get_str().size() << " digits).\n"; }
Convert the following code from Python to C++, ensuring the logic remains intact.
from functools import reduce from sympy import divisors FOUND = 0 for num in range(1, 1_000_000): divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1 if num * num * num == divprod: FOUND += 1 if FOUND <= 50: print(f'{num:5}', end='\n' if FOUND % 10 == 0 else '') if FOUND == 500: print(f'\nFive hundreth: {num:,}') if FOUND == 5000: print(f'\nFive thousandth: {num:,}') if FOUND == 50000: print(f'\nFifty thousandth: {num:,}') break
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } int main() { std::cout.imbue(std::locale("")); std::cout << "First 50 numbers which are the cube roots of the products of " "their proper divisors:\n"; for (unsigned int n = 1, count = 0; count < 50000; ++n) { if (n == 1 || divisor_count(n) == 8) { ++count; if (count <= 50) std::cout << std::setw(3) << n << (count % 10 == 0 ? '\n' : ' '); else if (count == 500 || count == 5000 || count == 50000) std::cout << std::setw(6) << count << "th: " << n << '\n'; } } }
Ensure the translated C++ code behaves exactly like the original Python snippet.
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(self): return self.v class Yaccer(object): def __init__(self): self.operstak = [] self.nodestak =[] self.__dict__.update(self.state1) def v1( self, valStrg ): self.nodestak.append( LeafNode(valStrg)) self.__dict__.update(self.state2) def o2( self, operchar ): def openParen(a,b): return 0 opDict= { '+': ( operator.add, 2, 2 ), '-': (operator.sub, 2, 2 ), '*': (operator.mul, 3, 3 ), '/': (operator.div, 3, 3 ), '^': ( pow, 4, 5 ), '(': ( openParen, 0, 8 ) } operPrecidence = opDict[operchar][2] self.redeuce(operPrecidence) self.operstak.append(opDict[operchar]) self.__dict__.update(self.state1) def syntaxErr(self, char ): print 'parse error - near operator "%s"' %char def pc2( self,operchar ): self.redeuce( 1 ) if len(self.operstak)>0: self.operstak.pop() else: print 'Error - no open parenthesis matches close parens.' self.__dict__.update(self.state2) def end(self): self.redeuce(0) return self.nodestak.pop() def redeuce(self, precidence): while len(self.operstak)>0: tailOper = self.operstak[-1] if tailOper[1] < precidence: break tailOper = self.operstak.pop() vrgt = self.nodestak.pop() vlft= self.nodestak.pop() self.nodestak.append( AstNode(tailOper[0], vlft, vrgt)) state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr } state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 } def Lex( exprssn, p ): bgn = None cp = -1 for c in exprssn: cp += 1 if c in '+-/*^()': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if c=='(': p.po(p, c) elif c==')':p.pc(p, c) else: p.o(p, c) elif c in ' \t': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None elif c in '0123456789': if bgn is None: bgn = cp else: print 'Invalid character in expression' if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if bgn is not None: p.v(p, exprssn[bgn:cp+1]) bgn = None return p.end() expr = raw_input("Expression:") astTree = Lex( expr, Yaccer()) print expr, '=',astTree.eval()
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_node; using boost::spirit::node_val_data; struct parser: public boost::spirit::grammar<parser> { enum rule_ids { addsub_id, multdiv_id, value_id, real_id }; struct set_value { set_value(parser const& p): self(p) {} void operator()(tree_node<node_val_data<std::string::iterator, double> >& node, std::string::iterator begin, std::string::iterator end) const { node.value.value(self.tmp); } parser const& self; }; mutable double tmp; template<typename Scanner> struct definition { rule<Scanner, parser_tag<addsub_id> > addsub; rule<Scanner, parser_tag<multdiv_id> > multdiv; rule<Scanner, parser_tag<value_id> > value; rule<Scanner, parser_tag<real_id> > real; definition(parser const& self) { using namespace boost::spirit; addsub = multdiv >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv); multdiv = value >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value); value = real | inner_node_d[('(' >> addsub >> ')')]; real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]]; } rule<Scanner, parser_tag<addsub_id> > const& start() const { return addsub; } }; }; template<typename TreeIter> double evaluate(TreeIter const& i) { double op1, op2; switch (i->value.id().to_long()) { case parser::real_id: return i->value.value(); case parser::value_id: case parser::addsub_id: case parser::multdiv_id: op1 = evaluate(i->children.begin()); op2 = evaluate(i->children.begin()+1); switch(*i->value.begin()) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: assert(!"Should not happen"); } default: assert(!"Should not happen"); } return 0; } int main() { parser eval; std::string line; while (std::cout << "Expression: " && std::getline(std::cin, line) && !line.empty()) { typedef boost::spirit::node_val_data_factory<double> factory_t; boost::spirit::tree_parse_info<std::string::iterator, factory_t> info = boost::spirit::ast_parse<factory_t>(line.begin(), line.end(), eval, boost::spirit::space_p); if (info.full) { std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl; } else { std::cout << "Error in expression." << std::endl; } } };
Convert the following code from Python to C++, ensuring the logic remains intact.
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(self): return self.v class Yaccer(object): def __init__(self): self.operstak = [] self.nodestak =[] self.__dict__.update(self.state1) def v1( self, valStrg ): self.nodestak.append( LeafNode(valStrg)) self.__dict__.update(self.state2) def o2( self, operchar ): def openParen(a,b): return 0 opDict= { '+': ( operator.add, 2, 2 ), '-': (operator.sub, 2, 2 ), '*': (operator.mul, 3, 3 ), '/': (operator.div, 3, 3 ), '^': ( pow, 4, 5 ), '(': ( openParen, 0, 8 ) } operPrecidence = opDict[operchar][2] self.redeuce(operPrecidence) self.operstak.append(opDict[operchar]) self.__dict__.update(self.state1) def syntaxErr(self, char ): print 'parse error - near operator "%s"' %char def pc2( self,operchar ): self.redeuce( 1 ) if len(self.operstak)>0: self.operstak.pop() else: print 'Error - no open parenthesis matches close parens.' self.__dict__.update(self.state2) def end(self): self.redeuce(0) return self.nodestak.pop() def redeuce(self, precidence): while len(self.operstak)>0: tailOper = self.operstak[-1] if tailOper[1] < precidence: break tailOper = self.operstak.pop() vrgt = self.nodestak.pop() vlft= self.nodestak.pop() self.nodestak.append( AstNode(tailOper[0], vlft, vrgt)) state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr } state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 } def Lex( exprssn, p ): bgn = None cp = -1 for c in exprssn: cp += 1 if c in '+-/*^()': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if c=='(': p.po(p, c) elif c==')':p.pc(p, c) else: p.o(p, c) elif c in ' \t': if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None elif c in '0123456789': if bgn is None: bgn = cp else: print 'Invalid character in expression' if bgn is not None: p.v(p, exprssn[bgn:cp]) bgn = None if bgn is not None: p.v(p, exprssn[bgn:cp+1]) bgn = None return p.end() expr = raw_input("Expression:") astTree = Lex( expr, Yaccer()) print expr, '=',astTree.eval()
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_node; using boost::spirit::node_val_data; struct parser: public boost::spirit::grammar<parser> { enum rule_ids { addsub_id, multdiv_id, value_id, real_id }; struct set_value { set_value(parser const& p): self(p) {} void operator()(tree_node<node_val_data<std::string::iterator, double> >& node, std::string::iterator begin, std::string::iterator end) const { node.value.value(self.tmp); } parser const& self; }; mutable double tmp; template<typename Scanner> struct definition { rule<Scanner, parser_tag<addsub_id> > addsub; rule<Scanner, parser_tag<multdiv_id> > multdiv; rule<Scanner, parser_tag<value_id> > value; rule<Scanner, parser_tag<real_id> > real; definition(parser const& self) { using namespace boost::spirit; addsub = multdiv >> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv); multdiv = value >> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value); value = real | inner_node_d[('(' >> addsub >> ')')]; real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]]; } rule<Scanner, parser_tag<addsub_id> > const& start() const { return addsub; } }; }; template<typename TreeIter> double evaluate(TreeIter const& i) { double op1, op2; switch (i->value.id().to_long()) { case parser::real_id: return i->value.value(); case parser::value_id: case parser::addsub_id: case parser::multdiv_id: op1 = evaluate(i->children.begin()); op2 = evaluate(i->children.begin()+1); switch(*i->value.begin()) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: assert(!"Should not happen"); } default: assert(!"Should not happen"); } return 0; } int main() { parser eval; std::string line; while (std::cout << "Expression: " && std::getline(std::cin, line) && !line.empty()) { typedef boost::spirit::node_val_data_factory<double> factory_t; boost::spirit::tree_parse_info<std::string::iterator, factory_t> info = boost::spirit::ast_parse<factory_t>(line.begin(), line.end(), eval, boost::spirit::space_p); if (info.full) { std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl; } else { std::cout << "Error in expression." << std::endl; } } };
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
import textwrap from itertools import pairwise from typing import Iterator from typing import List import primesieve def primes() -> Iterator[int]: it = primesieve.Iterator() while True: yield it.next_prime() def triplewise(iterable): for (a, _), (b, c) in pairwise(pairwise(iterable)): yield a, b, c def is_anagram(a: int, b: int, c: int) -> bool: return sorted(str(a)) == sorted(str(b)) == sorted(str(c)) def up_to_one_billion() -> int: count = 0 for triple in triplewise(primes()): if is_anagram(*triple): count += 1 if triple[2] >= 1_000_000_000: break return count def up_to_ten_billion() -> int: count = 0 for triple in triplewise(primes()): if is_anagram(*triple): count += 1 if triple[2] >= 10_000_000_000: break return count def first_25() -> List[int]: rv: List[int] = [] for triple in triplewise(primes()): if is_anagram(*triple): rv.append(triple[0]) if len(rv) >= 25: break return rv if __name__ == "__main__": print("Smallest members of first 25 Ormiston triples:") print(textwrap.fill(" ".join(str(i) for i in first_25())), "\n") print(up_to_one_billion(), "Ormiston triples before 1,000,000,000") print(up_to_ten_billion(), "Ormiston triples before 10,000,000,000")
#include <array> #include <iostream> #include <primesieve.hpp> class ormiston_triple_generator { public: ormiston_triple_generator() { for (int i = 0; i < 2; ++i) { primes_[i] = pi_.next_prime(); digits_[i] = get_digits(primes_[i]); } } std::array<uint64_t, 3> next_triple() { for (;;) { uint64_t prime = pi_.next_prime(); auto digits = get_digits(prime); bool is_triple = digits == digits_[0] && digits == digits_[1]; uint64_t prime0 = primes_[0]; primes_[0] = primes_[1]; primes_[1] = prime; digits_[0] = digits_[1]; digits_[1] = digits; if (is_triple) return {prime0, primes_[0], primes_[1]}; } } private: static std::array<int, 10> get_digits(uint64_t n) { std::array<int, 10> result = {}; for (; n > 0; n /= 10) ++result[n % 10]; return result; } primesieve::iterator pi_; std::array<uint64_t, 2> primes_; std::array<std::array<int, 10>, 2> digits_; }; int main() { ormiston_triple_generator generator; int count = 0; std::cout << "Smallest members of first 25 Ormiston triples:\n"; for (; count < 25; ++count) { auto primes = generator.next_triple(); std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\n' : ' '); } std::cout << '\n'; for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) { auto primes = generator.next_triple(); if (primes[2] > limit) { std::cout << "Number of Ormiston triples < " << limit << ": " << count << '\n'; limit *= 10; } } }
Produce a language-to-language conversion: from Python to C++, same semantics.
from sympy import isprime, divisors def is_super_Poulet(n): return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n)) spoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)] print('The first 20 super-Poulet numbers are:', spoulets[:20]) idx1m, val1m = next((i, v) for i, v in enumerate(spoulets) if v > 1_000_000) print(f'The first super-Poulet number over 1 million is the {idx1m}th one, which is {val1m}')
#include <algorithm> #include <iostream> #include <vector> std::vector<unsigned int> divisors(unsigned int n) { std::vector<unsigned int> result{1}; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) result.push_back(power); for (unsigned int p = 3; p * p <= n; p += 2) { size_t size = result.size(); for (power = p; n % p == 0; power *= p, n /= p) for (size_t i = 0; i != size; ++i) result.push_back(power * result[i]); } if (n > 1) { size_t size = result.size(); for (size_t i = 0; i != size; ++i) result.push_back(n * result[i]); } return result; } unsigned long long modpow(unsigned long long base, unsigned int exp, unsigned int mod) { if (mod == 1) return 0; unsigned long long result = 1; base %= mod; for (; exp != 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod; base = (base * base) % mod; } return result; } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6}; for (unsigned int p = 7;;) { for (unsigned int w : wheel) { if (p * p > n) return true; if (n % p == 0) return false; p += w; } } } bool is_poulet_number(unsigned int n) { return modpow(2, n - 1, n) == 1 && !is_prime(n); } bool is_sp_num(unsigned int n) { if (!is_poulet_number(n)) return false; auto div = divisors(n); return all_of(div.begin() + 1, div.end(), [](unsigned int d) { return modpow(2, d, d) == 2; }); } int main() { std::cout.imbue(std::locale("")); unsigned int n = 1, count = 0; std::cout << "First 20 super-Poulet numbers:\n"; for (; count < 20; n += 2) { if (is_sp_num(n)) { ++count; std::cout << n << ' '; } } std::cout << '\n'; for (unsigned int limit = 1000000; limit <= 10000000; limit *= 10) { for (;;) { n += 2; if (is_sp_num(n)) { ++count; if (n > limit) break; } } std::cout << "\nIndex and value of first super-Poulet greater than " << limit << ":\n#" << count << " is " << n << '\n'; } }
Convert the following code from Python to C++, ensuring the logic remains intact.
names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
#include <iostream> struct SpecialVariables { int i = 0; SpecialVariables& operator++() { this->i++; return *this; } }; int main() { SpecialVariables sv; auto sv2 = ++sv; std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n"; }
Write the same code in C++ as shown below in Python.
gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgrid * ygrid minecount = random.randint(int(minecount*minmines), int(minecount*maxmines)) grid = set(product(range(xgrid), range(ygrid))) mines = set(random.sample(grid, minecount)) show = {xy:'.' for xy in grid} return grid, mines, show def printgrid(show, gridsize=gridsize): xgrid, ygrid = gridsize grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid)) for y in range(ygrid)) print( grid ) def resign(showgrid, mines, markedmines): for m in mines: showgrid[m] = 'Y' if m in markedmines else 'N' def clear(x,y, showgrid, grid, mines, markedmines): if showgrid[(x, y)] == '.': xychar = str(sum(1 for xx in (x-1, x, x+1) for yy in (y-1, y, y+1) if (xx, yy) in mines )) if xychar == '0': xychar = '.' showgrid[(x,y)] = xychar for xx in (x-1, x, x+1): for yy in (y-1, y, y+1): xxyy = (xx, yy) if ( xxyy != (x, y) and xxyy in grid and xxyy not in mines | markedmines ): clear(xx, yy, showgrid, grid, mines, markedmines) if __name__ == '__main__': grid, mines, showgrid = gridandmines() markedmines = set([]) print( __doc__ ) print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) ) printgrid(showgrid) while markedmines != mines: inp = raw_input('m x y/c x y/p/r: ').strip().split() if inp: if inp[0] == 'm': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in markedmines: markedmines.remove((x,y)) showgrid[(x,y)] = '.' else: markedmines.add((x,y)) showgrid[(x,y)] = '?' elif inp[0] == 'p': printgrid(showgrid) elif inp[0] == 'c': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in mines | markedmines: print( '\nKLABOOM!! You hit a mine.\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break clear(x,y, showgrid, grid, mines, markedmines) printgrid(showgrid) elif inp[0] == 'r': print( '\nResigning!\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break print( '\nYou got %i and missed %i of the %i mines' % (len(mines.intersection(markedmines)), len(markedmines.difference(mines)), len(mines)) )
#include <iostream> #include <string> #include <windows.h> using namespace std; typedef unsigned char byte; enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR }; class fieldData { public: fieldData() : value( CLOSED ), open( false ) {} byte value; bool open, mine; }; class game { public: ~game() { if( field ) delete [] field; } game( int x, int y ) { go = false; wid = x; hei = y; field = new fieldData[x * y]; memset( field, 0, x * y * sizeof( fieldData ) ); oMines = ( ( 22 - rand() % 11 ) * x * y ) / 100; mMines = 0; int mx, my, m = 0; for( ; m < oMines; m++ ) { do { mx = rand() % wid; my = rand() % hei; } while( field[mx + wid * my].mine ); field[mx + wid * my].mine = true; } graphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; graphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; } void gameLoop() { string c, r, a; int col, row; while( !go ) { drawBoard(); cout << "Enter column, row and an action( c r a ):\nActions: o => open, f => flag, ? => unknown\n"; cin >> c >> r >> a; if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32; col = c[0] - 65; row = r[0] - 49; makeMove( col, row, a ); } } private: void makeMove( int x, int y, string a ) { fieldData* fd = &field[wid * y + x]; if( fd->open && fd->value < CLOSED ) { cout << "This cell is already open!"; Sleep( 3000 ); return; } if( a[0] == 'O' ) openCell( x, y ); else if( a[0] == 'F' ) { fd->open = true; fd->value = FLAG; mMines++; checkWin(); } else { fd->open = true; fd->value = UNKNOWN; } } bool openCell( int x, int y ) { if( !isInside( x, y ) ) return false; if( field[x + y * wid].mine ) boom(); else { if( field[x + y * wid].value == FLAG ) { field[x + y * wid].value = CLOSED; field[x + y * wid].open = false; mMines--; } recOpen( x, y ); checkWin(); } return true; } void drawBoard() { system( "cls" ); cout << "Marked mines: " << mMines << " from " << oMines << "\n\n"; for( int x = 0; x < wid; x++ ) cout << " " << ( char )( 65 + x ) << " "; cout << "\n"; int yy; for( int y = 0; y < hei; y++ ) { yy = y * wid; for( int x = 0; x < wid; x++ ) cout << "+---"; cout << "+\n"; fieldData* fd; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; cout<< "| "; if( !fd->open ) cout << ( char )graphs[1] << " "; else { if( fd->value > 9 ) cout << ( char )graphs[fd->value - 9] << " "; else { if( fd->value < 1 ) cout << " "; else cout << ( char )(fd->value + 48 ) << " "; } } } cout << "| " << y + 1 << "\n"; } for( int x = 0; x < wid; x++ ) cout << "+---"; cout << "+\n\n"; } void checkWin() { int z = wid * hei - oMines, yy; fieldData* fd; for( int y = 0; y < hei; y++ ) { yy = wid * y; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; if( fd->open && fd->value != FLAG ) z--; } } if( !z ) lastMsg( "Congratulations, you won the game!"); } void boom() { int yy; fieldData* fd; for( int y = 0; y < hei; y++ ) { yy = wid * y; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; if( fd->value == FLAG ) { fd->open = true; fd->value = fd->mine ? MINE : ERR; } else if( fd->mine ) { fd->open = true; fd->value = MINE; } } } lastMsg( "B O O O M M M M M !" ); } void lastMsg( string s ) { go = true; drawBoard(); cout << s << "\n\n"; } bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); } void recOpen( int x, int y ) { if( !isInside( x, y ) || field[x + y * wid].open ) return; int bc = getMineCount( x, y ); field[x + y * wid].open = true; field[x + y * wid].value = bc; if( bc ) return; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( xx == 0 && yy == 0 ) continue; recOpen( x + xx, y + yy ); } } int getMineCount( int x, int y ) { int m = 0; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( xx == 0 && yy == 0 ) continue; if( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++; } return m; } int wid, hei, mMines, oMines; fieldData* field; bool go; int graphs[6]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); game g( 4, 6 ); g.gameLoop(); return system( "pause" ); }
Write the same algorithm in C++ as shown in this Python implementation.
def _notcell(c): return '0' if c == '1' else '1' def eca_infinite(cells, rule): lencells = len(cells) rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} c = cells while True: yield c c = _notcell(c[0])*2 + c + _notcell(c[-1])*2 c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1)) if __name__ == '__main__': lines = 25 for rule in (90, 30): print('\nRule: %i' % rule) for i, c in zip(range(lines), eca_infinite('1', rule)): print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '
#include <iostream> #include <iomanip> #include <string> class oo { public: void evolve( int l, int rule ) { std::string cells = "O"; std::cout << " Rule #" << rule << ":\n"; for( int x = 0; x < l; x++ ) { addNoCells( cells ); std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n"; step( cells, rule ); } } private: void step( std::string& cells, int rule ) { int bin; std::string newCells; for( size_t i = 0; i < cells.length() - 2; i++ ) { bin = 0; for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) { bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b ); } newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' ); } cells = newCells; } void addNoCells( std::string& s ) { char l = s.at( 0 ) == 'O' ? '.' : 'O', r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O'; s = l + s + r; s = l + s + r; } }; int main( int argc, char* argv[] ) { oo o; o.evolve( 35, 90 ); std::cout << "\n"; return 0; }
Change the following Python code into C++ without altering its purpose.
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard = "" loc = 0 while(loc < len(lines)): command = lines[loc].strip() try: if(command == "Copy"): clipboard += lines[loc + 1] elif(command == "CopyFile"): if(lines[loc + 1] == "TheF*ckingCode"): clipboard += source else: filetext = open(lines[loc+1]).read() clipboard += filetext elif(command == "Duplicate"): clipboard += clipboard * ((int(lines[loc + 1])) - 1) elif(command == "Pasta!"): print(clipboard) sys.exit(0) else: fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1)) except Exception as e: fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e) loc += 2
#include <fstream> #include <iostream> #include <sstream> #include <streambuf> #include <string> #include <stdlib.h> using namespace std; void fatal_error(string errtext, char *argv[]) { cout << "%" << errtext << endl; cout << "usage: " << argv[0] << " [filename.cp]" << endl; exit(1); } string& ltrim(string& str, const string& chars = "\t\n\v\f\r ") { str.erase(0, str.find_first_not_of(chars)); return str; } string& rtrim(string& str, const string& chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); return str; } string& trim(string& str, const string& chars = "\t\n\v\f\r ") { return ltrim(rtrim(str, chars), chars); } int main(int argc, char *argv[]) { string fname = ""; string source = ""; try { fname = argv[1]; ifstream t(fname); t.seekg(0, ios::end); source.reserve(t.tellg()); t.seekg(0, ios::beg); source.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>()); } catch(const exception& e) { fatal_error("error while trying to read from specified file", argv); } string clipboard = ""; int loc = 0; string remaining = source; string line = ""; string command = ""; stringstream ss; while(remaining.find("\n") != string::npos) { line = remaining.substr(0, remaining.find("\n")); command = trim(line); remaining = remaining.substr(remaining.find("\n") + 1); try { if(line == "Copy") { line = remaining.substr(0, remaining.find("\n")); remaining = remaining.substr(remaining.find("\n") + 1); clipboard += line; } else if(line == "CopyFile") { line = remaining.substr(0, remaining.find("\n")); remaining = remaining.substr(remaining.find("\n") + 1); if(line == "TheF*ckingCode") clipboard += source; else { string filetext = ""; ifstream t(line); t.seekg(0, ios::end); filetext.reserve(t.tellg()); t.seekg(0, ios::beg); filetext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>()); clipboard += filetext; } } else if(line == "Duplicate") { line = remaining.substr(0, remaining.find("\n")); remaining = remaining.substr(remaining.find("\n") + 1); int amount = stoi(line); string origClipboard = clipboard; for(int i = 0; i < amount - 1; i++) { clipboard += origClipboard; } } else if(line == "Pasta!") { cout << clipboard << endl; return 0; } else { ss << (loc + 1); fatal_error("unknown command '" + command + "' encounter on line " + ss.str(), argv); } } catch(const exception& e) { ss << (loc + 1); fatal_error("error while executing command '" + command + "' on line " + ss.str(), argv); } loc += 2; } return 0; }
Port the provided Python code into C++ while preserving the original functionality.
from sympy import sieve def nonpairsums(include1=False, limit=20_000): tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve) for i in range(limit+2)] if include1: tpri[1] = True twinsums = [False] * (limit * 2) for i in range(limit): for j in range(limit-i+1): if tpri[i] and tpri[j]: twinsums[i + j] = True return [i for i in range(2, limit+1, 2) if not twinsums[i]] print('Non twin prime sums:') for k, p in enumerate(nonpairsums()): print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '') print('\n\nNon twin prime sums (including 1):') for k, p in enumerate(nonpairsums(include1=True)): print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
#include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(int limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3, sq = 9; sq < limit; p += 2) { if (sieve[p]) { for (int q = sq; q < limit; q += p << 1) sieve[q] = false; } sq += (p + 1) << 2; } return sieve; } void print_non_twin_prime_sums(const std::vector<bool>& sums) { int count = 0; for (size_t i = 2; i < sums.size(); i += 2) { if (!sums[i]) { ++count; std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' '); } } std::cout << "\nFound " << count << '\n'; } int main() { const int limit = 100001; std::vector<bool> sieve = prime_sieve(limit + 2); for (size_t i = 0; i < limit; ++i) { if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2])) sieve[i] = false; } std::vector<bool> twin_prime_sums(limit, false); for (size_t i = 0; i < limit; ++i) { if (sieve[i]) { for (size_t j = i; i + j < limit; ++j) { if (sieve[j]) twin_prime_sums[i + j] = true; } } } std::cout << "Non twin prime sums:\n"; print_non_twin_prime_sums(twin_prime_sums); sieve[1] = true; for (size_t i = 1; i + 1 < limit; ++i) { if (sieve[i]) twin_prime_sums[i + 1] = true; } std::cout << "\nNon twin prime sums (including 1):\n"; print_non_twin_prime_sums(twin_prime_sums); }
Transform the following Python implementation into C++, maintaining the same output and logic.
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] nonlocal.x = nonlocal.x - 1 l[nonlocal.x] = u for u in range(len(g)): visit(u) c = [0]*size def assign(u, root): if vis[u]: vis[u] = False c[u] = root for v in t[u]: assign(v, root) for u in l: assign(u, u) return c g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]] print kosaraju(g)
#include <functional> #include <iostream> #include <ostream> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto it = v.cbegin(); auto end = v.cend(); os << "["; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << "]"; } std::vector<int> kosaraju(std::vector<std::vector<int>>& g) { auto size = g.size(); std::vector<bool> vis(size); std::vector<int> l(size); auto x = size; std::vector<std::vector<int>> t(size); std::function<void(int)> visit; visit = [&](int u) { if (!vis[u]) { vis[u] = true; for (auto v : g[u]) { visit(v); t[v].push_back(u); } l[--x] = u; } }; for (int i = 0; i < g.size(); ++i) { visit(i); } std::vector<int> c(size); std::function<void(int, int)> assign; assign = [&](int u, int root) { if (vis[u]) { vis[u] = false; c[u] = root; for (auto v : t[u]) { assign(v, root); } } }; for (auto u : l) { assign(u, u); } return c; } std::vector<std::vector<int>> g = { {1}, {2}, {0}, {1, 2, 4}, {3, 5}, {2, 6}, {5}, {4, 6, 7}, }; int main() { using namespace std; cout << kosaraju(g) << endl; return 0; }
Change the programming language of this snippet from Python to C++ without modifying what it does.
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
int a;
Port the following code from Python to C++ with equivalent syntax and logic.
from numpy import ndarray from math import isqrt def pritchard(limit): members = ndarray(limit + 1, dtype=bool) members.fill(False) members[1] = True steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2 primes = [] while prime <= rtlim: if steplength < limit: for w in range(1, len(members)): if members[w]: n = w + steplength while n <= nlimit: members[n] = True n += steplength steplength = nlimit np = 5 mcpy = members.copy() for w in range(1, len(members)): if mcpy[w]: if np == 5 and w > prime: np = w n = prime * w if n > nlimit: break members[n] = False if np < prime: break primes.append(prime) prime = 3 if prime == 2 else np nlimit = min(steplength * prime, limit) newprimes = [i for i in range(2, len(members)) if members[i]] return sorted(primes + newprimes) print(pritchard(150)) print('Number of primes up to 1,000,000:', len(pritchard(1000000)))
#include <cstring> #include <string> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <ctime> void Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) { uint32_t i, j, x; i = 0; j = w_end; x = length + 1; while (x <= n) { w[++j] = x; d[x] = false; x = length + w[++i]; } length = n; w_end = j; if (w_end > w_end_max) w_end_max = w_end; } void Delete (uint32_t w[], uint32_t length, uint32_t p, bool d[], uint32_t &imaxf) { uint32_t i, x; i = 0; x = p; while (x <= length) { d[x] = true; x = p*w[++i]; } imaxf = i-1; } void Compress(uint32_t w[], bool d[], uint32_t to, uint32_t &w_end) { uint32_t i, j; j = 0; for (i=1; i <= to; i++) { if (!d[w[i]]) { w[++j] = w[i]; } } if (to == w_end) { w_end = j; } else { for (uint32_t k=j+1; k <= to; k++) w[k] = 0; } } void Sift(uint32_t N, bool printPrimes, uint32_t &nrPrimes, uint32_t &vBound) { uint32_t *w = new uint32_t[N/4+5]; bool *d = new bool[N+1]; uint32_t w_end, length; uint32_t w_end_max, p, imaxf; w_end = 0; w[0] = 1; w_end_max = 0; length = 2; nrPrimes = 1; if (printPrimes) printf("%d", 2); p = 3; while (p*p <= N) { nrPrimes++; if (printPrimes) printf(" %d", p); if (length < N) { Extend (w, w_end, length, std::min(p*length,N), d, w_end_max); } Delete(w, length, p, d, imaxf); Compress(w, d, (length < N ? w_end : imaxf), w_end); p = w[1]; if (p == 0) break; } if (length < N) { Extend (w, w_end, length, N, d, w_end_max); } for (uint32_t i=1; i <= w_end; i++) { if (w[i] == 0 || d[w[i]]) continue; if (printPrimes) printf(" %d", w[i]); nrPrimes++; } vBound = w_end_max+1; } int main (int argc, char *argw[]) { bool error = false; bool printPrimes = false; uint32_t N, nrPrimes, vBound; if (argc == 3) { if (strcmp(argw[2], "-p") == 0) { printPrimes = true; argc--; } else { error = true; } } if (argc == 2) { N = atoi(argw[1]); if (N < 2 || N > 1000000000) error = true; } else { error = true; } if (error) { printf("call with: %s N -p where 2 <= N <= 1000000000 and -p to print the primes is optional \n", argw[0]); exit(1); } int start_s = clock(); Sift(N, printPrimes, nrPrimes, vBound); int stop_s=clock(); printf("\n%d primes up to %lu found in %.3f ms using array w[%d]\n", nrPrimes, (unsigned long)N, (stop_s-start_s)*1E3/double(CLOCKS_PER_SEC), vBound); }
Rewrite the snippet below in C++ so it works the same as the original Python code.
from __future__ import annotations import functools import math import os from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union T = TypeVar("T") class Writer(Generic[T]): def __init__(self, value: Union[T, Writer[T]], *msgs: str): if isinstance(value, Writer): self.value: T = value.value self.msgs: List[str] = value.msgs + list(msgs) else: self.value = value self.msgs = list(f"{msg}: {self.value}" for msg in msgs) def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: writer = func(self.value) return Writer(writer, *self.msgs) def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: return self.bind(func) def __str__(self): return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}" def __repr__(self): return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")" def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]: @functools.wraps(func) def wrapped(value): return Writer(func(value), msg) return wrapped if __name__ == "__main__": square_root = lift(math.sqrt, "square root") add_one = lift(lambda x: x + 1, "add one") half = lift(lambda x: x / 2, "div two") print(Writer(5, "initial") >> square_root >> add_one >> half)
#include <cmath> #include <iostream> #include <string> using namespace std; struct LoggingMonad { double Value; string Log; }; auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingMonad{result.Value, monad.Log + "\n" + result.Log}; } auto Root = [](double x){ return sqrt(x); }; auto AddOne = [](double x){ return x + 1; }; auto Half = [](double x){ return x / 2.0; }; auto MakeWriter = [](auto f, string message) { return [=](double x){return LoggingMonad(f(x), message);}; }; auto writerRoot = MakeWriter(Root, "Taking square root"); auto writerAddOne = MakeWriter(AddOne, "Adding 1"); auto writerHalf = MakeWriter(Half, "Dividing by 2"); int main() { auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf; cout << result.Log << "\nResult: " << result.Value; }
Convert the following code from Python to C++, ensuring the logic remains intact.
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d) missed.extend(f'?? for x in substruct if type(x) is not tuple and x not in i2d) return tuple(_inject_payload(x, i2d, used, missed) if type(x) is tuple else i2d.get(x, f'?? for x in substruct) ans = _inject_payload(self.structure, id2data, self.used_payloads, self.missed_payloads) self.unused_payloads = sorted(set(id2data.values()) - set(self.used_payloads)) self.missed_payloads = sorted(set(self.missed_payloads)) return ans if __name__ == '__main__': index2data = {p: f'Payload print(" print('\n '.join(list(index2data.values()))) for structure in [ (((1, 2), (3, 4, 1), 5),), (((1, 2), (10, 4, 1), 5),)]: print("\n\n pp(structure, width=13) print("\n TEMPLATE WITH PAYLOADS:") t = Template(structure) out = t.inject_payload(index2data) pp(out) print("\n UNUSED PAYLOADS:\n ", end='') unused = t.unused_payloads print('\n '.join(unused) if unused else '-') print(" MISSING PAYLOADS:\n ", end='') missed = t.missed_payloads print('\n '.join(missed) if missed else '-')
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) cout << ", "; } template<typename P, typename... Ts> void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true) { std::apply ( [&payloads, isLast](Ts const&... tupleArgs) { size_t n{0}; cout << "["; (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...); cout << "]"; cout << (isLast ? "\n" : ",\n"); }, nestedTuple ); } void FindUniqueIndexes(set<int> &indexes, int index) { indexes.insert(index); } template<typename... Ts> void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple) { std::apply ( [&indexes](Ts const&... tupleArgs) { (FindUniqueIndexes(indexes, tupleArgs),...); }, nestedTuple ); } template<typename P> void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads) { for(size_t i = 0; i < size(payloads); i++) { if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n"; } } int main() { vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"}; const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; auto tpl = make_tuple(make_tuple( make_tuple(1, 2), make_tuple(3, 4, 1), 5)); cout << "Mapping indexes to payloads:\n"; PrintPayloads(payloads, tpl); cout << "\nFinding unused payloads:\n"; set<int> usedIndexes; FindUniqueIndexes(usedIndexes, tpl); PrintUnusedPayloads(usedIndexes, payloads); cout << "\nMapping to some out of range payloads:\n"; PrintPayloads(shortPayloads, tpl); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d) missed.extend(f'?? for x in substruct if type(x) is not tuple and x not in i2d) return tuple(_inject_payload(x, i2d, used, missed) if type(x) is tuple else i2d.get(x, f'?? for x in substruct) ans = _inject_payload(self.structure, id2data, self.used_payloads, self.missed_payloads) self.unused_payloads = sorted(set(id2data.values()) - set(self.used_payloads)) self.missed_payloads = sorted(set(self.missed_payloads)) return ans if __name__ == '__main__': index2data = {p: f'Payload print(" print('\n '.join(list(index2data.values()))) for structure in [ (((1, 2), (3, 4, 1), 5),), (((1, 2), (10, 4, 1), 5),)]: print("\n\n pp(structure, width=13) print("\n TEMPLATE WITH PAYLOADS:") t = Template(structure) out = t.inject_payload(index2data) pp(out) print("\n UNUSED PAYLOADS:\n ", end='') unused = t.unused_payloads print('\n '.join(unused) if unused else '-') print(" MISSING PAYLOADS:\n ", end='') missed = t.missed_payloads print('\n '.join(missed) if missed else '-')
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) cout << ", "; } template<typename P, typename... Ts> void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true) { std::apply ( [&payloads, isLast](Ts const&... tupleArgs) { size_t n{0}; cout << "["; (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...); cout << "]"; cout << (isLast ? "\n" : ",\n"); }, nestedTuple ); } void FindUniqueIndexes(set<int> &indexes, int index) { indexes.insert(index); } template<typename... Ts> void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple) { std::apply ( [&indexes](Ts const&... tupleArgs) { (FindUniqueIndexes(indexes, tupleArgs),...); }, nestedTuple ); } template<typename P> void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads) { for(size_t i = 0; i < size(payloads); i++) { if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n"; } } int main() { vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"}; const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; auto tpl = make_tuple(make_tuple( make_tuple(1, 2), make_tuple(3, 4, 1), 5)); cout << "Mapping indexes to payloads:\n"; PrintPayloads(payloads, tpl); cout << "\nFinding unused payloads:\n"; set<int> usedIndexes; FindUniqueIndexes(usedIndexes, tpl); PrintUnusedPayloads(usedIndexes, payloads); cout << "\nMapping to some out of range payloads:\n"; PrintPayloads(shortPayloads, tpl); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
from pyprimesieve import primes def digitsum(num): return sum(int(c) for c in str(num)) def generate_honaker(limit=5_000_000): honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)] for hcount, (ppi, pri) in enumerate(honaker): yield hcount + 1, ppi, pri print('First 50 Honaker primes:') for p in generate_honaker(): if p[0] < 51: print(f'{str(p):16}', end='\n' if p[0] % 5 == 0 else '') elif p[0] == 10_000: print(f'\nThe 10,000th Honaker prime is the {p[1]:,}th one, which is {p[2]:,}.') break
#include <iomanip> #include <iostream> #include <sstream> #include <utility> #include <primesieve.hpp> uint64_t digit_sum(uint64_t n) { uint64_t sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } class honaker_prime_generator { public: std::pair<uint64_t, uint64_t> next(); private: primesieve::iterator pi_; uint64_t index_ = 0; }; std::pair<uint64_t, uint64_t> honaker_prime_generator::next() { for (;;) { uint64_t prime = pi_.next_prime(); ++index_; if (digit_sum(index_) == digit_sum(prime)) return std::make_pair(index_, prime); } } std::ostream& operator<<(std::ostream& os, const std::pair<uint64_t, uint64_t>& p) { std::ostringstream str; str << '(' << p.first << ", " << p.second << ')'; return os << str.str(); } int main() { honaker_prime_generator hpg; std::cout << "First 50 Honaker primes (index, prime):\n"; int i = 1; for (; i <= 50; ++i) std::cout << std::setw(11) << hpg.next() << (i % 5 == 0 ? '\n' : ' '); for (; i < 10000; ++i) hpg.next(); std::cout << "\nTen thousandth: " << hpg.next() << '\n'; }
Convert this Python snippet to C++ and keep its semantics consistent.
from sympy import isprime from math import log from numpy import ndarray max_value = 1_000_000 all_primes = [i for i in range(max_value + 1) if isprime(i)] powers_of_2 = [2**i for i in range(int(log(max_value, 2)))] allvalues = ndarray(max_value, dtype=bool) allvalues[:] = True for i in all_primes: for j in powers_of_2: if i + j < max_value: allvalues[i + j] = False dePolignac = [n for n in range(1, max_value) if n & 1 == 1 and allvalues[n]] print('First fifty de Polignac numbers:') for i, n in enumerate(dePolignac[:50]): print(f'{n:5}', end='\n' if (i + 1) % 10 == 0 else '') print(f'\nOne thousandth: {dePolignac[999]:,}') print(f'\nTen thousandth: {dePolignac[9999]:,}')
#include <iomanip> #include <iostream> bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } bool is_depolignac_number(int n) { for (int p = 1; p < n; p <<= 1) { if (is_prime(n - p)) return false; } return true; } int main() { std::cout.imbue(std::locale("")); std::cout << "First 50 de Polignac numbers:\n"; for (int n = 1, count = 0; count < 10000; n += 2) { if (is_depolignac_number(n)) { ++count; if (count <= 50) std::cout << std::setw(5) << n << (count % 10 == 0 ? '\n' : ' '); else if (count == 1000) std::cout << "\nOne thousandth: " << n << '\n'; else if (count == 10000) std::cout << "\nTen thousandth: " << n << '\n'; } } }
Translate this program into C++ but keep the logic exactly as in Python.
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min_val, max_val): while True: user_input = input(prompt) try: user_input = int(user_input) except ValueError: continue if min_val <= user_input <= max_val: return user_input def play_game(): print("Welcome to Mastermind.") print("You will need to guess a random code.") print("For each guess, you will receive a hint.") print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.") print() number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20) code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10) letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters] code = ''.join(random.choices(letters, k=code_length)) guesses = [] while True: print() guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip() if len(guess) != code_length or any([char not in letters for char in guess]): continue elif guess == code: print(f"\nYour guess {guess} was correct!") break else: guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}") for i_guess in guesses: print("------------------------------------") print(i_guess) print("------------------------------------") if __name__ == '__main__': play_game()
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector> typedef std::vector<char> vecChar; class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST"; if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10; if( !rpt && clr_count < code_len ) clr_count = code_len; if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20; if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20; codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt; for( size_t s = 0; s < colorsCnt; s++ ) { colors.append( 1, color.at( s ) ); } } void play() { bool win = false; combo = getCombo(); while( guessCnt ) { showBoard(); if( checkInput( getInput() ) ) { win = true; break; } guessCnt--; } if( win ) { std::cout << "\n\n--------------------------------\n" << "Very well done!\nYou found the code: " << combo << "\n--------------------------------\n\n"; } else { std::cout << "\n\n--------------------------------\n" << "I am sorry, you couldn't make it!\nThe code was: " << combo << "\n--------------------------------\n\n"; } } private: void showBoard() { vecChar::iterator y; for( int x = 0; x < guesses.size(); x++ ) { std::cout << "\n--------------------------------\n"; std::cout << x + 1 << ": "; for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) { std::cout << *y << " "; } std::cout << " : "; for( y = results[x].begin(); y != results[x].end(); y++ ) { std::cout << *y << " "; } int z = codeLen - results[x].size(); if( z > 0 ) { for( int x = 0; x < z; x++ ) std::cout << "- "; } } std::cout << "\n\n"; } std::string getInput() { std::string a; while( true ) { std::cout << "Enter your guess (" << colors << "): "; a = ""; std::cin >> a; std::transform( a.begin(), a.end(), a.begin(), ::toupper ); if( a.length() > codeLen ) a.erase( codeLen ); bool r = true; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { if( colors.find( *x ) == std::string::npos ) { r = false; break; } } if( r ) break; } return a; } bool checkInput( std::string a ) { vecChar g; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { g.push_back( *x ); } guesses.push_back( g ); int black = 0, white = 0; std::vector<bool> gmatch( codeLen, false ); std::vector<bool> cmatch( codeLen, false ); for( int i = 0; i < codeLen; i++ ) { if( a.at( i ) == combo.at( i ) ) { gmatch[i] = true; cmatch[i] = true; black++; } } for( int i = 0; i < codeLen; i++ ) { if (gmatch[i]) continue; for( int j = 0; j < codeLen; j++ ) { if (i == j || cmatch[j]) continue; if( a.at( i ) == combo.at( j ) ) { cmatch[j] = true; white++; break; } } } vecChar r; for( int b = 0; b < black; b++ ) r.push_back( 'X' ); for( int w = 0; w < white; w++ ) r.push_back( 'O' ); results.push_back( r ); return ( black == codeLen ); } std::string getCombo() { std::string c, clr = colors; int l, z; for( size_t s = 0; s < codeLen; s++ ) { z = rand() % ( int )clr.length(); c.append( 1, clr[z] ); if( !repeatClr ) clr.erase( z, 1 ); } return c; } size_t codeLen, colorsCnt, guessCnt; bool repeatClr; std::vector<vecChar> guesses, results; std::string colors, combo; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); master m( 4, 8, 12, false ); m.play(); return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from math import gcd from sympy import divisors def zsig(num, aint, bint): assert aint > bint dexpms = [aint**i - bint**i for i in range(1, num)] dexpn = aint**num - bint**num return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)]) tests = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (3, 2), (5, 3), (7, 3), (7, 5)] for (a, b) in tests: print(f'\nZsigmondy(n, {a}, {b}):', ', '.join( [str(zsig(n, a, b)) for n in range(1, 21)]))
#include <algorithm> #include <cstdint> #include <iostream> #include <numeric> #include <vector> std::vector<uint64_t> divisors(uint64_t n) { std::vector<uint64_t> result{1}; uint64_t power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) result.push_back(power); for (uint64_t p = 3; p * p <= n; p += 2) { size_t size = result.size(); for (power = p; n % p == 0; power *= p, n /= p) for (size_t i = 0; i != size; ++i) result.push_back(power * result[i]); } if (n > 1) { size_t size = result.size(); for (size_t i = 0; i != size; ++i) result.push_back(n * result[i]); } sort(result.begin(), result.end()); return result; } uint64_t ipow(uint64_t base, uint64_t exp) { if (exp == 0) return 1; if ((exp & 1) == 0) return ipow(base * base, exp >> 1); return base * ipow(base * base, (exp - 1) >> 1); } uint64_t zsigmondy(uint64_t n, uint64_t a, uint64_t b) { auto p = ipow(a, n) - ipow(b, n); auto d = divisors(p); if (d.size() == 2) return p; std::vector<uint64_t> dms(n - 1); for (uint64_t m = 1; m < n; ++m) dms[m - 1] = ipow(a, m) - ipow(b, m); for (auto i = d.rbegin(); i != d.rend(); ++i) { uint64_t z = *i; if (all_of(dms.begin(), dms.end(), [z](uint64_t x) { return std::gcd(x, z) == 1; })) return z; } return 1; } void test(uint64_t a, uint64_t b) { std::cout << "Zsigmondy(n, " << a << ", " << b << "):\n"; for (uint64_t n = 1; n <= 20; ++n) { std::cout << zsigmondy(n, a, b) << ' '; } std::cout << "\n\n"; } int main() { test(2, 1); test(3, 1); test(4, 1); test(5, 1); test(6, 1); test(7, 1); test(3, 2); test(5, 3); test(7, 3); test(7, 5); }
Write the same algorithm in C++ as shown in this Python implementation.
from multiset import Multiset def tokenizetext(txt): arr = [] for wrd in txt.lower().split(' '): arr += ([wrd] if len(wrd) == 1 else [wrd[i:i+2] for i in range(len(wrd)-1)]) return Multiset(arr) def sorenson_dice(text1, text2): bc1, bc2 = tokenizetext(text1), tokenizetext(text2) return 2 * len(bc1 & bc2) / (len(bc1) + len(bc2)) with open('tasklist_sorenson.txt', 'r') as fd: alltasks = fd.read().split('\n') for testtext in ['Primordial primes', 'Sunkist-Giuliani formula', 'Sieve of Euripides', 'Chowder numbers']: taskvalues = sorted([(sorenson_dice(testtext, t), t) for t in alltasks], reverse=True) print(f'\n{testtext}:') for (val, task) in taskvalues[:5]: print(f' {val:.6f} {task}')
#include <algorithm> #include <cctype> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <sstream> #include <string> #include <vector> using bigram = std::pair<char, char>; std::multiset<bigram> bigrams(const std::string& phrase) { std::multiset<bigram> result; std::istringstream is(phrase); std::string word; while (is >> word) { for (char& ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); } size_t length = word.size(); if (length == 1) { result.emplace(word[0], '\0'); } else { for (size_t i = 0; i + 1 < length; ++i) { result.emplace(word[i], word[i + 1]); } } } return result; } double sorensen(const std::string& s1, const std::string& s2) { auto a = bigrams(s1); auto b = bigrams(s2); std::multiset<bigram> c; std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.begin())); return (2.0 * c.size()) / (a.size() + b.size()); } int main() { std::vector<std::string> tasks; std::ifstream is("tasks.txt"); if (!is) { std::cerr << "Cannot open tasks file.\n"; return EXIT_FAILURE; } std::string task; while (getline(is, task)) { tasks.push_back(task); } const size_t tc = tasks.size(); const std::string tests[] = {"Primordial primes", "Sunkist-Giuliani formula", "Sieve of Euripides", "Chowder numbers"}; std::vector<std::pair<double, size_t>> sdi(tc); std::cout << std::fixed; for (const std::string& test : tests) { for (size_t i = 0; i != tc; ++i) { sdi[i] = std::make_pair(sorensen(tasks[i], test), i); } std::partial_sort(sdi.begin(), sdi.begin() + 5, sdi.end(), [](const std::pair<double, size_t>& a, const std::pair<double, size_t>& b) { return a.first > b.first; }); std::cout << test << " >\n"; for (size_t i = 0; i < 5 && i < tc; ++i) { std::cout << " " << sdi[i].first << ' ' << tasks[sdi[i].second] << '\n'; } std::cout << '\n'; } return EXIT_SUCCESS; }
Please provide an equivalent version of this C# code in C.
public class AverageLoopLength { private static int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.Next(n); } var seen = new HashSet<double>(n); int current = 0; int length = 0; while (seen.Add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void Main(string[] args) { Console.WriteLine(" N average analytical (error)"); Console.WriteLine("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { var average = AverageLoopLength.average(i); var analytical = AverageLoopLength.analytical(i); Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
Please provide an equivalent version of this C# code in C.
class Program { static void Main() { string extra = "little"; string formatted = $"Mary had a {extra} lamb."; System.Console.WriteLine(formatted); } }
#include <stdio.h> int main() { const char *extra = "little"; printf("Mary had a %s lamb.\n", extra); return 0; }
Write the same algorithm in C as shown in this C# implementation.
using System; class Program { const long Lm = (long)1e18; const string Fm = "D18"; struct LI { public long lo, ml, mh, hi, tp; } static void inc(ref LI d, LI s) { if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; } if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; } if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; } if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; } d.tp += s.tp; } static void dec(ref LI d, LI s) { if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; } if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; } if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; } if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; } d.tp -= s.tp; } static LI set(long s) { LI d; d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; } static string fmt(LI x) { if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm); return x.lo.ToString(); } static LI partcount(int n) { var P = new LI[n + 1]; P[0] = set(1); for (int i = 1; i <= n; i++) { int k = 0, d = -2, j = i; LI x = set(0); while (true) { if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break; if ((j -= ++k) >= 0) inc(ref x, P[j]); else break; if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break; if ((j -= ++k) >= 0) dec(ref x, P[j]); else break; } P[i] = x; } return P[n]; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew (); var res = partcount(6666); sw.Stop(); Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds); } }
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <gmp.h> mpz_t* partition(uint64_t n) { mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t)); mpz_init_set_ui(pn[0], 1); mpz_init_set_ui(pn[1], 1); for (uint64_t i = 2; i < n + 2; i ++) { mpz_init(pn[i]); for (uint64_t k = 1, penta; ; k++) { penta = k * (3 * k - 1) >> 1; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); penta += k; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); } } mpz_t *tmp = &pn[n + 1]; for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]); free(pn); return tmp; } int main(int argc, char const *argv[]) { clock_t start = clock(); mpz_t *p = partition(6666); gmp_printf("%Zd\n", p); printf("Elapsed time: %.04f seconds\n", (double)(clock() - start) / (double)CLOCKS_PER_SEC); return 0; }
Produce a functionally identical C code for the snippet given in C#.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
Write the same algorithm in C as shown in this C# implementation.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
Translate this program into C but keep the logic exactly as in C#.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
Write the same algorithm in C as shown in this C# implementation.
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 0; }
Convert this C# snippet to C and keep its semantics consistent.
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 0; }
Change the programming language of this snippet from C# to C without modifying what it does.
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Math.Round(a, 4); Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad }; Func<double, double>[,] convert = { { a => a, DegToGrad, DegToMil, DegToRad }, { GradToDeg, a => a, GradToMil, GradToRad }, { MilToDeg, MilToGrad, a => a, MilToRad }, { RadToDeg, RadToGrad, RadToMil, a => a } }; Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{ "Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}"); foreach (double angle in angles) { for (int i = 0; i < 4; i++) { double nAngle = normal[i](angle); Console.WriteLine($@"{ rnd(angle),-12}{ rnd(nAngle),-12}{ names[i],-12}{ rnd(convert[i, 0](nAngle)),-12}{ rnd(convert[i, 1](nAngle)),-12}{ rnd(convert[i, 2](nAngle)),-12}{ rnd(convert[i, 3](nAngle)),-12}"); } } } public static double NormalizeDeg(double angle) => Normalize(angle, 360); public static double NormalizeGrad(double angle) => Normalize(angle, 400); public static double NormalizeMil(double angle) => Normalize(angle, 6400); public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI); private static double Normalize(double angle, double N) { while (angle <= -N) angle += N; while (angle >= N) angle -= N; return angle; } public static double DegToGrad(double angle) => angle * 10 / 9; public static double DegToMil(double angle) => angle * 160 / 9; public static double DegToRad(double angle) => angle * Math.PI / 180; public static double GradToDeg(double angle) => angle * 9 / 10; public static double GradToMil(double angle) => angle * 16; public static double GradToRad(double angle) => angle * Math.PI / 200; public static double MilToDeg(double angle) => angle * 9 / 160; public static double MilToGrad(double angle) => angle / 16; public static double MilToRad(double angle) => angle * Math.PI / 3200; public static double RadToDeg(double angle) => angle * 180 / Math.PI; public static double RadToGrad(double angle) => angle * 200 / Math.PI; public static double RadToMil(double angle) => angle * 3200 / Math.PI; }
#define PI 3.141592653589793 #define TWO_PI 6.283185307179586 double normalize2deg(double a) { while (a < 0) a += 360; while (a >= 360) a -= 360; return a; } double normalize2grad(double a) { while (a < 0) a += 400; while (a >= 400) a -= 400; return a; } double normalize2mil(double a) { while (a < 0) a += 6400; while (a >= 6400) a -= 6400; return a; } double normalize2rad(double a) { while (a < 0) a += TWO_PI; while (a >= TWO_PI) a -= TWO_PI; return a; } double deg2grad(double a) {return a * 10 / 9;} double deg2mil(double a) {return a * 160 / 9;} double deg2rad(double a) {return a * PI / 180;} double grad2deg(double a) {return a * 9 / 10;} double grad2mil(double a) {return a * 16;} double grad2rad(double a) {return a * PI / 200;} double mil2deg(double a) {return a * 9 / 160;} double mil2grad(double a) {return a / 16;} double mil2rad(double a) {return a * PI / 3200;} double rad2deg(double a) {return a * 180 / PI;} double rad2grad(double a) {return a * 200 / PI;} double rad2mil(double a) {return a * 3200 / PI;}
Transform the following C# implementation into C, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( ); foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } } return CommonPath; } } }
#include <stdio.h> int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue; while (pos > 0 && names[0][--pos] != sep); return pos; } } return 0; } int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]); return 0; }
Translate this program into C but keep the logic exactly as in C#.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
Please provide an equivalent version of this C# code in C.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
Port the provided C# code into C while preserving the original functionality.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
Generate an equivalent C version of this C# code.
using System; using System.Runtime.InteropServices; public unsafe class Program { public static unsafe void HeapMemory() { const int HEAP_ZERO_MEMORY = 0x00000008; const int size = 1000; int ph = GetProcessHeap(); void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if (pointer == null) throw new OutOfMemoryException(); Console.WriteLine(HeapSize(ph, 0, pointer)); HeapFree(ph, 0, pointer); } public static unsafe void StackMemory() { byte* buffer = stackalloc byte[1000]; } public static void Main(string[] args) { HeapMemory(); StackMemory(); } [DllImport("kernel32")] static extern void* HeapAlloc(int hHeap, int flags, int size); [DllImport("kernel32")] static extern bool HeapFree(int hHeap, int flags, void* block); [DllImport("kernel32")] static extern int GetProcessHeap(); [DllImport("kernel32")] static extern int HeapSize(int hHeap, int flags, void* block); }
#include <stdlib.h> #define SIZEOF_MEMB (sizeof(int)) #define NMEMB 100 int main() { int *ints = malloc(SIZEOF_MEMB*NMEMB); ints = realloc(ints, sizeof(int)*(NMEMB+1)); int *int2 = calloc(NMEMB, SIZEOF_MEMB); free(ints); free(int2); return 0; }
Port the following code from C# to C with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const int Computer = 0; const int Human = 1; static int[] GameBoard = new int[9]; static int[] corners = new int[] { 0, 2, 6, 8 }; static int[][] wins = new int[][] { new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); initializeGameBoard(); displayGameBoard(); int currentPlayer = rnd.Next(0, 2); Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); while (true) { int thisMove = getMoveFor(currentPlayer); if (thisMove == Unplayed) { Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); break; } playMove(thisMove, currentPlayer); displayGameBoard(); if (isGameWon()) { Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); break; } else if (isGameTied()) { Console.WriteLine("Cat game ... we have a tie."); break; } currentPlayer = getNextPlayer(currentPlayer); } if (!playAgain()) return; } } static int getMoveFor(int player) { if (player == Human) return getManualMove(player); else { int selectedMove = getSemiRandomMove(player); Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); return selectedMove; } } static int getManualMove(int player) { while (true) { Console.Write("{0}, enter you move (number): ", playerName(player)); ConsoleKeyInfo keyInfo = Console.ReadKey(); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape) return Unplayed; if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) { int move = keyInfo.KeyChar - '1'; if (GameBoard[move] == Unplayed) return move; else Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); } else Console.WriteLine("Illegal move, please select again.\n"); } } static int getRandomMove(int player) { int movesLeft = GameBoard.Count(position => position == Unplayed); int x = rnd.Next(0, movesLeft); for (int i = 0; i < GameBoard.Length; i++) { if (GameBoard[i] == Unplayed && x < 0) return i; x--; } return Unplayed; } static int getSemiRandomMove(int player) { int posToPlay; if (checkForWinningMove(player, out posToPlay)) return posToPlay; if (checkForBlockingMove(player, out posToPlay)) return posToPlay; return getRandomMove(player); } static int getBestMove(int player) { return -1; } static bool checkForWinningMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(player, line, out posToPlay)) return true; return false; } static bool checkForBlockingMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) return true; return false; } static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) { int cnt = 0; posToPlay = int.MinValue; foreach (int pos in line) { if (GameBoard[pos] == player) cnt++; else if (GameBoard[pos] == Unplayed) posToPlay = pos; } return cnt == 2 && posToPlay >= 0; } static void playMove(int boardPosition, int player) { GameBoard[boardPosition] = player; } static bool isGameWon() { return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); } static bool takenBySamePlayer(int a, int b, int c) { return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; } static bool isGameTied() { return !GameBoard.Any(spot => spot == Unplayed); } static Random rnd = new Random(); static void initializeGameBoard() { for (int i = 0; i < GameBoard.Length; i++) GameBoard[i] = Unplayed; } static string playerName(int player) { return Players[player][0]; } static string playerToken(int player) { return Players[player][1]; } static int getNextPlayer(int player) { return (player + 1) % 2; } static void displayGameBoard() { Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); Console.WriteLine(); } static string pieceAt(int boardPosition) { if (GameBoard[boardPosition] == Unplayed) return (boardPosition + 1).ToString(); return playerToken(GameBoard[boardPosition]); } private static bool playAgain() { Console.WriteLine("\nDo you want to play again?"); return Console.ReadKey(false).Key == ConsoleKey.Y; } } }
#include <stdio.h> #include <stdlib.h> int b[3][3]; int check_winner() { int i; for (i = 0; i < 3; i++) { if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]; if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]; } if (!b[1][1]) return 0; if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]; if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]; return 0; } void showboard() { const char *t = "X O"; int i, j; for (i = 0; i < 3; i++, putchar('\n')) for (j = 0; j < 3; j++) printf("%c ", t[ b[i][j] + 1 ]); printf("-----\n"); } #define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) int best_i, best_j; int test_move(int val, int depth) { int i, j, score; int best = -1, changed = 0; if ((score = check_winner())) return (score == val) ? 1 : -1; for_ij { if (b[i][j]) continue; changed = b[i][j] = val; score = -test_move(-val, depth + 1); b[i][j] = 0; if (score <= best) continue; if (!depth) { best_i = i; best_j = j; } best = score; } return changed ? best : 0; } const char* game(int user) { int i, j, k, move, win = 0; for_ij b[i][j] = 0; printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n"); printf("You have O, I have X.\n\n"); for (k = 0; k < 9; k++, user = !user) { while(user) { printf("your move: "); if (!scanf("%d", &move)) { scanf("%*s"); continue; } if (--move < 0 || move >= 9) continue; if (b[i = move / 3][j = move % 3]) continue; b[i][j] = 1; break; } if (!user) { if (!k) { best_i = rand() % 3; best_j = rand() % 3; } else test_move(-1, 0); b[best_i][best_j] = -1; printf("My move: %d\n", best_i * 3 + best_j + 1); } showboard(); if ((win = check_winner())) return win == 1 ? "You win.\n\n": "I win.\n\n"; } return "A draw.\n\n"; } int main() { int first = 0; while (1) printf("%s", game(first = !first)); return 0; }