Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from Python to C++.
from itertools import groupby, permutations def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(sorted(str(number), reverse=True)) ) def A036058_length(numberstring='0', printit=False): iterations, last_three, queue_index = 1, ([None] * 3), 0 def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(number) ) while True: if printit: print(" %2i %s" % (iterations, numberstring)) numberstring = ''.join(sorted(numberstring, reverse=True)) if numberstring in last_three: break assert iterations < 1000000 last_three[queue_index], numberstring = numberstring, A036058(numberstring) iterations += 1 queue_index +=1 queue_index %=3 return iterations def max_A036058_length( start_range=range(11) ): already_done = set() max_len = (-1, []) for n in start_range: sn = str(n) sns = tuple(sorted(sn, reverse=True)) if sns not in already_done: already_done.add(sns) size = A036058_length(sns) if size > max_len[0]: max_len = (size, [n]) elif size == max_len[0]: max_len[1].append(n) return max_len lenmax, starts = max_A036058_length( range(1000000) ) allstarts = [] for n in starts: allstarts += [int(''.join(x)) for x in set(k for k in permutations(str(n), 4) if k[0] != '0')] allstarts = [x for x in sorted(allstarts) if x < 1000000] print ( % (lenmax, allstarts) ) print ( ) for n in starts: print() A036058_length(str(n), printit=True)
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> std::map<char, int> _map; std::vector<std::string> _result; size_t longest = 0; void make_sequence( std::string n ) { _map.clear(); for( std::string::iterator i = n.begin(); i != n.end(); i++ ) _map.insert( std::make_pair( *i, _map[*i]++ ) ); std::string z; for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) { char c = ( *i ).second + 48; z.append( 1, c ); z.append( 1, i->first ); } if( longest <= z.length() ) { longest = z.length(); if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) { _result.push_back( z ); make_sequence( z ); } } } int main( int argc, char* argv[] ) { std::vector<std::string> tests; tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" ); for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) { make_sequence( *i ); std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n"; for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) { std::cout << *j << "\n"; } std::cout << "\n\n"; } return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
irregularOrdinals = { "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } def num2ordinal(n): conversion = int(float(n)) num = spell_integer(conversion) hyphen = num.rsplit("-", 1) num = num.rsplit(" ", 1) delim = " " if len(num[-1]) > len(hyphen[-1]): num = hyphen delim = "-" if num[-1] in irregularOrdinals: num[-1] = delim + irregularOrdinals[num[-1]] elif num[-1].endswith("y"): num[-1] = delim + num[-1][:-1] + "ieth" else: num[-1] = delim + num[-1] + "th" return "".join(num) if __name__ == "__main__": tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split() for num in tests: print("{} => {}".format(num, num2ordinal(num))) TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num)
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; integer number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string number_name(integer n, bool ordinal) { std::string result; if (n < 20) result = get_name(small[n], ordinal); else if (n < 100) { if (n % 10 == 0) { result = get_name(tens[n/10 - 2], ordinal); } else { result = get_name(tens[n/10 - 2], false); result += "-"; result += get_name(small[n % 10], ordinal); } } else { const named_number& num = get_named_number(n); integer p = num.number; result = number_name(n/p, false); result += " "; if (n % p == 0) { result += get_name(num, ordinal); } else { result += get_name(num, false); result += " "; result += number_name(n % p, ordinal); } } return result; } void test_ordinal(integer n) { std::cout << n << ": " << number_name(n, true) << '\n'; } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
Convert the following code from Python to C++, ensuring the logic remains intact.
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
#include <iostream> typedef unsigned long long bigint; using namespace std; class sdn { public: bool check( bigint n ) { int cc = digitsCount( n ); return compare( n, cc ); } void displayAll( bigint s ) { for( bigint y = 1; y < s; y++ ) if( check( y ) ) cout << y << " is a Self-Describing Number." << endl; } private: bool compare( bigint n, int cc ) { bigint a; while( cc ) { cc--; a = n % 10; if( dig[cc] != a ) return false; n -= a; n /= 10; } return true; } int digitsCount( bigint n ) { int cc = 0; bigint a; memset( dig, 0, sizeof( dig ) ); while( n ) { a = n % 10; dig[a]++; cc++ ; n -= a; n /= 10; } return cc; } int dig[10]; }; int main( int argc, char* argv[] ) { sdn s; s. displayAll( 1000000000000 ); cout << endl << endl; system( "pause" ); bigint n; while( true ) { system( "cls" ); cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n; if( !n ) return 0; if( s.check( n ) ) cout << n << " is"; else cout << n << " is NOT"; cout << " a Self-Describing Number!" << endl << endl; system( "pause" ); } return 0; }
Transform the following Python implementation into C++, maintaining the same output and logic.
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): if i > pos: return min_len, 0 res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len) res2 = try_perm(i + 1, pos, seq, n, res1[0]) if res2[0] < res1[0]: return res2 if res2[0] == res1[0]: return res2[0], res1[1] + res2[1] raise Exception("try_perm exception") def init_try_perm(x): return try_perm(0, 0, [1], x, 12) def find_brauer(num): res = init_try_perm(num) print print "N = ", num print "Minimum length of chains: L(n) = ", res[0] print "Number of minimum length Brauer chains: ", res[1] nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379] for i in nums: find_brauer(i)
#include <iostream> #include <tuple> #include <vector> std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int); std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) { if (pos > minLen || seq[0] > n) return { minLen, 0 }; else if (seq[0] == n) return { pos, 1 }; else if (pos < minLen) return tryPerm(0, pos, seq, n, minLen); else return { minLen, 0 }; } std::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) { if (i > pos) return { minLen, 0 }; std::vector<int> seq2{ seq[0] + seq[i] }; seq2.insert(seq2.end(), seq.cbegin(), seq.cend()); auto res1 = checkSeq(pos + 1, seq2, n, minLen); auto res2 = tryPerm(i + 1, pos, seq, n, res1.first); if (res2.first < res1.first) return res2; else if (res2.first == res1.first) return { res2.first, res1.second + res2.second }; else throw std::runtime_error("tryPerm exception"); } std::pair<int, int> initTryPerm(int x) { return tryPerm(0, 0, { 1 }, x, 12); } void findBrauer(int num) { auto res = initTryPerm(num); std::cout << '\n'; std::cout << "N = " << num << '\n'; std::cout << "Minimum length of chains: L(n)= " << res.first << '\n'; std::cout << "Number of minimum length Brauer chains: " << res.second << '\n'; } int main() { std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; for (int i : nums) { findBrauer(i); } return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
template <typename Function> void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--) f(); }
Rewrite the snippet below in C++ so it works the same as the original Python code.
bar = '▁▂▃▄▅▆▇█' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __name__ == '__main__': import re for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;" "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;" "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'): print("\nNumbers:", line) numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] mn, mx, sp = sparkline(numbers) print(' min: %5f; max: %5f' % (mn, mx)) print(" " + sp)
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = ", "; std::vector<float> data; std::string::size_type last = spark.find_first_not_of(delim, 0); std::string::size_type pos = spark.find_first_of(delim, last); while( pos != std::string::npos || last != std::string::npos ){ std::string tok = spark.substr(last, pos-last); std::stringstream ss(tok); float entry; ss >> entry; data.push_back( entry ); last = spark.find_first_not_of(delim, pos); pos = spark.find_first_of(delim, last); } float min = *std::min_element( data.begin(), data.end() ); float max = *std::max_element( data.begin(), data.end() ); float skip = (charset.length()-1) / (max - min); std::wcout<<L"Min: "<<min<<L"; Max: "<<max<<L"; Range: "<<(max-min)<<std::endl; std::vector<float>::const_iterator it; for(it = data.begin(); it != data.end(); it++){ float v = ( (*it) - min ) * skip; std::wcout<<charset[ (int)floor( v ) ]; } std::wcout<<std::endl; } private: std::wstring &charset; }; int main( int argc, char **argv ){ std::wstring charset = L"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"; std::locale::global(std::locale("en_US.utf8")); Sparkline sl(charset); sl.print("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"); sl.print("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"); return 0; }
Port the following code from Python to C++ with equivalent syntax and logic.
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m >>> modinv(42, 2017) 1969 >>>
#include <iostream> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { std::cout << mul_inv(42, 2017) << std::endl; return 0; }
Translate this program into C++ but keep the logic exactly as in Python.
from turtle import * from math import * iter = 3000 diskRatio = .5 factor = .5 + sqrt(1.25) screen = getscreen() (winWidth, winHeight) = screen.screensize() x = 0.0 y = 0.0 maxRad = pow(iter,factor)/iter; bgcolor("light blue") hideturtle() tracer(0, 0) for i in range(iter+1): r = pow(i,factor)/iter; if r/maxRad < diskRatio: pencolor("black") else: pencolor("yellow") theta = 2*pi*factor*i; up() setposition(x + r*sin(theta), y + r*cos(theta)) down() circle(10.0 * i/(1.0*iter)) update() done()
#include <cmath> #include <fstream> #include <iostream> bool sunflower(const char* filename) { std::ofstream out(filename); if (!out) return false; constexpr int size = 600; constexpr int seeds = 5 * size; constexpr double pi = 3.14159265359; constexpr double phi = 1.61803398875; out << "<svg xmlns='http: out << "' height='" << size << "' style='stroke:gold'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << std::setprecision(2) << std::fixed; for (int i = 1; i <= seeds; ++i) { double r = 2 * std::pow(i, phi)/seeds; double theta = 2 * pi * phi * i; double x = r * std::sin(theta) + size/2; double y = r * std::cos(theta) + size/2; double radius = std::sqrt(i)/13; out << "<circle cx='" << x << "' cy='" << y << "' r='" << radius << "'/>\n"; } out << "</svg>\n"; return true; } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; } if (!sunflower(argv[1])) { std::cerr << "image generation failed\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Generate an equivalent C++ version of this Python code.
from collections import defaultdict costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print "\t", n, print cost = 0 for g in sorted(costs): print g, "\t", for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print "\t", print print "\n\nTotal Cost = ", cost
#include <iostream> #include <numeric> #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> demand = { 30, 20, 70, 30, 60 }; std::vector<int> supply = { 50, 60, 50, 50 }; std::vector<std::vector<int>> costs = { {16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11} }; int nRows = supply.size(); int nCols = demand.size(); std::vector<bool> rowDone(nRows, false); std::vector<bool> colDone(nCols, false); std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0)); std::vector<int> diff(int j, int len, bool isRow) { int min1 = INT_MAX; int min2 = INT_MAX; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) { continue; } int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) { min2 = c; } } return { min2 - min1, min1, minP }; } std::vector<int> maxPenalty(int len1, int len2, bool isRow) { int md = INT_MIN; int pc = -1; int pm = -1; int mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) { continue; } std::vector<int> res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; pm = i; mc = res[1]; pc = res[2]; } } return isRow ? std::vector<int> { pm, pc, mc, md } : std::vector<int>{ pc, pm, mc, md }; } std::vector<int> nextCell() { auto res1 = maxPenalty(nRows, nCols, true); auto res2 = maxPenalty(nCols, nRows, false); if (res1[3] == res2[3]) { return res1[2] < res2[2] ? res1 : res2; } return res1[3] > res2[3] ? res2 : res1; } int main() { int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; }); int totalCost = 0; while (supplyLeft > 0) { auto cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = std::min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) { colDone[c] = true; } supply[r] -= quantity; if (supply[r] == 0) { rowDone[r] = true; } result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } for (auto &a : result) { std::cout << a << '\n'; } std::cout << "Total cost: " << totalCost; return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert 84.162 == molar_mass('C6H12') assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 == molar_mass('C6H4O2(OH)4') assert 386.664 == molar_mass('C27H46O') assert 315 == molar_mass('Uue')
#include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> std::map<std::string, double> atomicMass = { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; double evaluate(std::string s) { s += '['; double sum = 0.0; std::string symbol; std::string number; for (auto c : s) { if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = stoi(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c; number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { std::string msg = "Unexpected symbol "; msg += c; msg += " in molecule"; throw std::runtime_error(msg); } } return sum; } std::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) { auto pos = text.find(search); if (pos == std::string::npos) { return text; } auto beg = text.substr(0, pos); auto end = text.substr(pos + search.length()); return beg + replace + end; } std::string replaceParens(std::string s) { char letter = 'a'; while (true) { auto start = s.find("("); if (start == std::string::npos) { break; } for (size_t i = start + 1; i < s.length(); i++) { if (s[i] == ')') { auto expr = s.substr(start + 1, i - start - 1); std::string symbol = "@"; symbol += letter; auto search = s.substr(start, i + 1 - start); s = replaceFirst(s, search, symbol); atomicMass[symbol] = evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } int main() { std::vector<std::string> molecules = { "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; for (auto molecule : molecules) { auto mass = evaluate(replaceParens(molecule)); std::cout << std::setw(17) << molecule << " -> " << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\n'; } return 0; }
Generate a C++ translation of this Python snippet without changing its computational steps.
from operator import itemgetter DEBUG = False def spermutations(n): sign = 1 p = [[i, 0 if i == 0 else -1] for i in range(n)] if DEBUG: print ' yield tuple(pp[0] for pp in p), sign while any(pp[1] for pp in p): i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]), key=itemgetter(1)) sign *= -1 if d1 == -1: i2 = i1 - 1 p[i1], p[i2] = p[i2], p[i1] if i2 == 0 or p[i2 - 1][0] > n1: p[i2][1] = 0 elif d1 == 1: i2 = i1 + 1 p[i1], p[i2] = p[i2], p[i1] if i2 == n - 1 or p[i2 + 1][0] > n1: p[i2][1] = 0 if DEBUG: print ' yield tuple(pp[0] for pp in p), sign for i3, pp in enumerate(p): n3, d3 = pp if n3 > n1: pp[1] = 1 if i3 < i2 else -1 if DEBUG: print ' if __name__ == '__main__': from itertools import permutations for n in (3, 4): print '\nPermutations and sign of %i items' % n sp = set() for i in spermutations(n): sp.add(i[0]) print('Perm: %r Sign: %2i' % i) p = set(permutations(range(n))) assert sp == p, 'Two methods of generating permutations do not agree'
#include <iostream> #include <vector> using namespace std; vector<int> UpTo(int n, int offset = 0) { vector<int> retval(n); for (int ii = 0; ii < n; ++ii) retval[ii] = ii + offset; return retval; } struct JohnsonTrotterState_ { vector<int> values_; vector<int> positions_; vector<bool> directions_; int sign_; JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {} int LargestMobile() const { for (int r = values_.size(); r > 0; --r) { const int loc = positions_[r] + (directions_[r] ? 1 : -1); if (loc >= 0 && loc < values_.size() && values_[loc] < r) return r; } return 0; } bool IsComplete() const { return LargestMobile() == 0; } void operator++() { const int r = LargestMobile(); const int rLoc = positions_[r]; const int lLoc = rLoc + (directions_[r] ? 1 : -1); const int l = values_[lLoc]; swap(values_[lLoc], values_[rLoc]); swap(positions_[l], positions_[r]); sign_ = -sign_; for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd) *pd = !*pd; } }; int main(void) { JohnsonTrotterState_ state(4); do { for (auto v : state.values_) cout << v << " "; cout << "\n"; ++state; } while (!state.IsComplete()); }
Write a version of this Python function in C++ with identical behavior.
from itertools import count, islice def a131382(): return ( elemIndex(x)( productDigitSums(x) ) for x in count(1) ) def productDigitSums(n): return (digitSum(n * x) for x in count(0)) def main(): print( table(10)([ str(x) for x in islice( a131382(), 40 ) ]) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitSum(n): return sum(int(x) for x in list(str(n))) def elemIndex(x): def go(xs): try: return next( i for i, v in enumerate(xs) if x == v ) except StopIteration: return None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' '); break; } } } }
Change the programming language of this snippet from Python to C++ without modifying what it does.
from itertools import count, islice def a131382(): return ( elemIndex(x)( productDigitSums(x) ) for x in count(1) ) def productDigitSums(n): return (digitSum(n * x) for x in count(0)) def main(): print( table(10)([ str(x) for x in islice( a131382(), 40 ) ]) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitSum(n): return sum(int(x) for x in list(str(n))) def elemIndex(x): def go(xs): try: return next( i for i, v in enumerate(xs) if x == v ) except StopIteration: return None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' '); break; } } } }
Transform the following Python implementation into C++, maintaining the same output and logic.
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i] if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { aabb[aa + b * b] = true; } } for (int c = 1; c <= N; ++c) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } } cout << "The values of d <= " << N << " which can't be represented:" << endl; for (int d = 1; d <= N; ++d) { if (!found[d]) { cout << d << " "; } } cout << endl; return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
print("working...") print("Steady squares under 10.000 are:") limit = 10000 for n in range(1,limit): nstr = str(n) nlen = len(nstr) square = str(pow(n,2)) rn = square[-nlen:] if nstr == rn: print(str(n) + " " + str(square)) print("done...")
#include <iostream> using namespace std; bool steady(int n) { int mask = 1; for (int d = n; d != 0; d /= 10) mask *= 10; return (n * n) % mask == n; } int main() { for (int i = 1; i < 10000; i++) if (steady(i)) printf("%4d^2 = %8d\n", i, i * i); }
Preserve the algorithm and functionality while converting the code from Python to C++.
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
Generate an equivalent C++ version of this Python code.
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
Write the same algorithm in C++ as shown in this Python implementation.
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_sides1, n_dice1) c2, p2 = gen_dict(n_sides2, n_dice2) p12 = float(p1 * p2) return sum(p[1] * q[1] / p12 for p, q in product(enumerate(c1), enumerate(c2)) if p[0] > q[0]) print beating_probability(4, 9, 6, 6) print beating_probability(10, 5, 7, 6)
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; } double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; } int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
Please provide an equivalent version of this Python code in C++.
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_sides1, n_dice1) c2, p2 = gen_dict(n_sides2, n_dice2) p12 = float(p1 * p2) return sum(p[1] * q[1] / p12 for p, q in product(enumerate(c1), enumerate(c2)) if p[0] > q[0]) print beating_probability(4, 9, 6, 6) print beating_probability(10, 5, 7, 6)
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; } double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; } int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
from logpy import * from logpy.core import lall import time def lefto(q, p, list): return membero((q,p), zip(list, list[1:])) def nexto(q, p, list): return conde([lefto(q, p, list)], [lefto(p, q, list)]) houses = var() zebraRules = lall( (eq, (var(), var(), var(), var(), var()), houses), (membero, ('Englishman', var(), var(), var(), 'red'), houses), (membero, ('Swede', var(), var(), 'dog', var()), houses), (membero, ('Dane', var(), 'tea', var(), var()), houses), (lefto, (var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), (membero, (var(), var(), 'coffee', var(), 'green'), houses), (membero, (var(), 'Pall Mall', var(), 'birds', var()), houses), (membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses), (eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), (eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), (nexto, (var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), (membero, (var(), 'Blue Master', 'beer', var(), var()), houses), (membero, ('German', 'Prince', var(), var(), var()), houses), (nexto, ('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), (membero, (var(), var(), var(), 'zebra', var()), houses) ) t0 = time.time() solutions = run(0, houses, zebraRules) t1 = time.time() dur = t1-t0 count = len(solutions) zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0] print "%i solutions in %.2f seconds" % (count, dur) print "The %s is the owner of the zebra" % zebraOwner print "Here are all the houses:" for line in solutions[0]: print str(line)
#include <stdio.h> #include <string.h> #define defenum(name, val0, val1, val2, val3, val4) \ enum name { val0, val1, val2, val3, val4 }; \ const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 } defenum( Attrib, Color, Man, Drink, Animal, Smoke ); defenum( Colors, Red, Green, White, Yellow, Blue ); defenum( Mans, English, Swede, Dane, German, Norwegian ); defenum( Drinks, Tea, Coffee, Milk, Beer, Water ); defenum( Animals, Dog, Birds, Cats, Horse, Zebra ); defenum( Smokes, PallMall, Dunhill, Blend, BlueMaster, Prince ); void printHouses(int ha[5][5]) { const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str}; printf("%-10s", "House"); for (const char *name : Attrib_str) printf("%-10s", name); printf("\n"); for (int i = 0; i < 5; i++) { printf("%-10d", i); for (int j = 0; j < 5; j++) printf("%-10s", attr_names[j][ha[i][j]]); printf("\n"); } } struct HouseNoRule { int houseno; Attrib a; int v; } housenos[] = { {2, Drink, Milk}, {0, Man, Norwegian} }; struct AttrPairRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] >= 0 && ha[i][a2] >= 0) && ((ha[i][a1] == v1 && ha[i][a2] != v2) || (ha[i][a1] != v1 && ha[i][a2] == v2)); } } pairs[] = { {Man, English, Color, Red}, {Man, Swede, Animal, Dog}, {Man, Dane, Drink, Tea}, {Color, Green, Drink, Coffee}, {Smoke, PallMall, Animal, Birds}, {Smoke, Dunhill, Color, Yellow}, {Smoke, BlueMaster, Drink, Beer}, {Man, German, Smoke, Prince} }; struct NextToRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] == v1) && ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) || (i == 4 && ha[i - 1][a2] != v2) || (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2)); } } nexttos[] = { {Smoke, Blend, Animal, Cats}, {Smoke, Dunhill, Animal, Horse}, {Man, Norwegian, Color, Blue}, {Smoke, Blend, Drink, Water} }; struct LeftOfRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5]) { return (ha[0][a2] == v2) || (ha[4][a1] == v1); } bool invalid(int ha[5][5], int i) { return ((i > 0 && ha[i][a1] >= 0) && ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) || (ha[i - 1][a1] != v1 && ha[i][a2] == v2))); } } leftofs[] = { {Color, Green, Color, White} }; bool invalid(int ha[5][5]) { for (auto &rule : leftofs) if (rule.invalid(ha)) return true; for (int i = 0; i < 5; i++) { #define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true; eval_rules(pairs); eval_rules(nexttos); eval_rules(leftofs); } return false; } void search(bool used[5][5], int ha[5][5], const int hno, const int attr) { int nexthno, nextattr; if (attr < 4) { nextattr = attr + 1; nexthno = hno; } else { nextattr = 0; nexthno = hno + 1; } if (ha[hno][attr] != -1) { search(used, ha, nexthno, nextattr); } else { for (int i = 0; i < 5; i++) { if (used[attr][i]) continue; used[attr][i] = true; ha[hno][attr] = i; if (!invalid(ha)) { if ((hno == 4) && (attr == 4)) { printHouses(ha); } else { search(used, ha, nexthno, nextattr); } } used[attr][i] = false; } ha[hno][attr] = -1; } } int main() { bool used[5][5] = {}; int ha[5][5]; memset(ha, -1, sizeof(ha)); for (auto &rule : housenos) { ha[rule.houseno][rule.a] = rule.v; used[rule.a][rule.v] = true; } search(used, ha, 0, 0); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
#include <array> #include <iostream> int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y ); const std::array values{x, y, z}; const std::array inverses{xi, yi, zi}; auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; }; for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\n"; } }
Produce a language-to-language conversion: from Python to C++, same semantics.
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
#include <array> #include <iostream> int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y ); const std::array values{x, y, z}; const std::array inverses{xi, yi, zi}; auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; }; for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\n"; } }
Generate a C++ translation of this Python snippet without changing its computational steps.
from array import array from collections import deque import psyco data = [] nrows = 0 px = py = 0 sdata = "" ddata = "" def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data) maps = {' ':' ', '.': '.', '@':' ', ' mapd = {' ':' ', '.': ' ', '@':'@', ' for r, row in enumerate(data): for c, ch in enumerate(row): sdata += maps[ch] ddata += mapd[ch] if ch == '@': px = c py = r def push(x, y, dx, dy, data): if sdata[(y+2*dy) * nrows + x+2*dx] == ' data[(y+2*dy) * nrows + x+2*dx] != ' ': return None data2 = array("c", data) data2[y * nrows + x] = ' ' data2[(y+dy) * nrows + x+dx] = '@' data2[(y+2*dy) * nrows + x+2*dx] = '*' return data2.tostring() def is_solved(data): for i in xrange(len(data)): if (sdata[i] == '.') != (data[i] == '*'): return False return True def solve(): open = deque([(ddata, "", px, py)]) visited = set([ddata]) dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'), (0, 1, 'd', 'D'), (-1, 0, 'l', 'L')) lnrows = nrows while open: cur, csol, x, y = open.popleft() for di in dirs: temp = cur dx, dy = di[0], di[1] if temp[(y+dy) * lnrows + x+dx] == '*': temp = push(x, y, dx, dy, temp) if temp and temp not in visited: if is_solved(temp): return csol + di[3] open.append((temp, csol + di[3], x+dx, y+dy)) visited.add(temp) else: if sdata[(y+dy) * lnrows + x+dx] == ' temp[(y+dy) * lnrows + x+dx] != ' ': continue data2 = array("c", temp) data2[y * lnrows + x] = ' ' data2[(y+dy) * lnrows + x+dx] = '@' temp = data2.tostring() if temp not in visited: if is_solved(temp): return csol + di[2] open.append((temp, csol + di[2], x+dx, y+dy)) visited.add(temp) return "No solution" level = """\ psyco.full() init(level) print level, "\n\n", solve()
#include <iostream> #include <string> #include <vector> #include <queue> #include <regex> #include <tuple> #include <set> #include <array> using namespace std; class Board { public: vector<vector<char>> sData, dData; int px, py; Board(string b) { regex pattern("([^\\n]+)\\n?"); sregex_iterator end, iter(b.begin(), b.end(), pattern); int w = 0; vector<string> data; for(; iter != end; ++iter){ data.push_back((*iter)[1]); w = max(w, (*iter)[1].length()); } for(int v = 0; v < data.size(); ++v){ vector<char> sTemp, dTemp; for(int u = 0; u < w; ++u){ if(u > data[v].size()){ sTemp.push_back(' '); dTemp.push_back(' '); }else{ char s = ' ', d = ' ', c = data[v][u]; if(c == '#') s = '#'; else if(c == '.' || c == '*' || c == '+') s = '.'; if(c == '@' || c == '+'){ d = '@'; px = u; py = v; }else if(c == '$' || c == '*') d = '*'; sTemp.push_back(s); dTemp.push_back(d); } } sData.push_back(sTemp); dData.push_back(dTemp); } } bool move(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') return false; data[y][x] = ' '; data[y+dy][x+dx] = '@'; return true; } bool push(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ') return false; data[y][x] = ' '; data[y+dy][x+dx] = '@'; data[y+2*dy][x+2*dx] = '*'; return true; } bool isSolved(const vector<vector<char>> &data) { for(int v = 0; v < data.size(); ++v) for(int u = 0; u < data[v].size(); ++u) if((sData[v][u] == '.') ^ (data[v][u] == '*')) return false; return true; } string solve() { set<vector<vector<char>>> visited; queue<tuple<vector<vector<char>>, string, int, int>> open; open.push(make_tuple(dData, "", px, py)); visited.insert(dData); array<tuple<int, int, char, char>, 4> dirs; dirs[0] = make_tuple(0, -1, 'u', 'U'); dirs[1] = make_tuple(1, 0, 'r', 'R'); dirs[2] = make_tuple(0, 1, 'd', 'D'); dirs[3] = make_tuple(-1, 0, 'l', 'L'); while(open.size() > 0){ vector<vector<char>> temp, cur = get<0>(open.front()); string cSol = get<1>(open.front()); int x = get<2>(open.front()); int y = get<3>(open.front()); open.pop(); for(int i = 0; i < 4; ++i){ temp = cur; int dx = get<0>(dirs[i]); int dy = get<1>(dirs[i]); if(temp[y+dy][x+dx] == '*'){ if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<3>(dirs[i]); open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<2>(dirs[i]); open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } } } return "No solution"; } }; int main() { string level = "#######\n" "# #\n" "# #\n" "#. # #\n" "#. $$ #\n" "#.$$ #\n" "#.# @#\n" "#######"; Board b(level); cout << level << endl << endl << b.solve() << endl; return 0; }
Please provide an equivalent version of this Python code in C++.
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
Translate the given Python code snippet into C++ without altering its behavior.
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
Maintain the same structure and functionality when rewriting this code in C++.
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
Generate an equivalent C++ version of this Python code.
from itertools import chain, cycle, accumulate, combinations from typing import List, Tuple def factors5(n: int) -> List[int]: def prime_powers(n): for c in accumulate(chain([2, 1, 2], cycle([2,4]))): if c*c > n: break if n%c: continue d,p = (), c while not n%c: n,p,d = n//c, p*c, d + (p,) yield(d) if n > 1: yield((n,)) r = [1] for e in prime_powers(n): r += [a*b for a in r for b in e] return r[:-1] def powerset(s: List[int]) -> List[Tuple[int, ...]]: return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1)) def is_practical(x: int) -> bool: if x == 1: return True if x %2: return False f = factors5(x) ps = powerset(f) found = {y for y in {sum(i) for i in ps} if 1 <= y < x} return len(found) == x - 1 if __name__ == '__main__': n = 333 p = [x for x in range(1, n + 1) if is_practical(x)] print(f"There are {len(p)} Practical numbers from 1 to {n}:") print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1]) x = 666 print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
#include <algorithm> #include <iostream> #include <numeric> #include <sstream> #include <vector> template <typename iterator> bool sum_of_any_subset(int n, iterator begin, iterator end) { if (begin == end) return false; if (std::find(begin, end, n) != end) return true; int total = std::accumulate(begin, end, 0); if (n == total) return true; if (n > total) return false; --end; int d = n - *end; return (d > 0 && sum_of_any_subset(d, begin, end)) || sum_of_any_subset(n, begin, end); } std::vector<int> factors(int n) { std::vector<int> f{1}; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { f.push_back(i); if (i * i != n) f.push_back(n / i); } } std::sort(f.begin(), f.end()); return f; } bool is_practical(int n) { std::vector<int> f = factors(n); for (int i = 1; i < n; ++i) { if (!sum_of_any_subset(i, f.begin(), f.end())) return false; } return true; } std::string shorten(const std::vector<int>& v, size_t n) { std::ostringstream out; size_t size = v.size(), i = 0; if (n > 0 && size > 0) out << v[i++]; for (; i < n && i < size; ++i) out << ", " << v[i]; if (size > i + n) { out << ", ..."; i = size - n; } for (; i < size; ++i) out << ", " << v[i]; return out.str(); } int main() { std::vector<int> practical; for (int n = 1; n <= 333; ++n) { if (is_practical(n)) practical.push_back(n); } std::cout << "Found " << practical.size() << " practical numbers:\n" << shorten(practical, 10) << '\n'; for (int n : {666, 6666, 66666, 672, 720, 222222}) std::cout << n << " is " << (is_practical(n) ? "" : "not ") << "a practical number.\n"; return 0; }
Change the programming language of this snippet from Python to C++ without modifying what it does.
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff < old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list)
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp> void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::cout << '\n'; } int main() { std::cout.imbue(std::locale("")); std::vector<uint64_t> asc, desc; std::vector<std::vector<uint64_t>> max_asc, max_desc; size_t max_asc_len = 0, max_desc_len = 0; uint64_t prime; const uint64_t limit = 1000000; for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) { size_t alen = asc.size(); if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2]) asc.erase(asc.begin(), asc.end() - 1); asc.push_back(prime); if (asc.size() >= max_asc_len) { if (asc.size() > max_asc_len) { max_asc_len = asc.size(); max_asc.clear(); } max_asc.push_back(asc); } size_t dlen = desc.size(); if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2]) desc.erase(desc.begin(), desc.end() - 1); desc.push_back(prime); if (desc.size() >= max_desc_len) { if (desc.size() > max_desc_len) { max_desc_len = desc.size(); max_desc.clear(); } max_desc.push_back(desc); } } std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n"; for (const auto& v : max_asc) print_diffs(v); std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n"; for (const auto& v : max_desc) print_diffs(v); return 0; }
Produce a functionally identical C++ code for the snippet given in Python.
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff < old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list)
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp> void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::cout << '\n'; } int main() { std::cout.imbue(std::locale("")); std::vector<uint64_t> asc, desc; std::vector<std::vector<uint64_t>> max_asc, max_desc; size_t max_asc_len = 0, max_desc_len = 0; uint64_t prime; const uint64_t limit = 1000000; for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) { size_t alen = asc.size(); if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2]) asc.erase(asc.begin(), asc.end() - 1); asc.push_back(prime); if (asc.size() >= max_asc_len) { if (asc.size() > max_asc_len) { max_asc_len = asc.size(); max_asc.clear(); } max_asc.push_back(asc); } size_t dlen = desc.size(); if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2]) desc.erase(desc.begin(), desc.end() - 1); desc.push_back(prime); if (desc.size() >= max_desc_len) { if (desc.size() > max_desc_len) { max_desc_len = desc.size(); max_desc.clear(); } max_desc.push_back(desc); } } std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n"; for (const auto& v : max_asc) print_diffs(v); std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n"; for (const auto& v : max_desc) print_diffs(v); return 0; }
Change the programming language of this snippet from Python to C++ without modifying what it does.
2.3 .3 .3e4 .3e+34 .3e-34 2.e34
#include <iostream> int main() { auto double1 = 2.5; auto float1 = 2.5f; auto longdouble1 = 2.5l; auto double2 = 2.5e-3; auto float2 = 2.5e3f; auto double3 = 0x1p4; auto float3 = 0xbeefp-8f; std::cout << "\ndouble1: " << double1; std::cout << "\nfloat1: " << float1; std::cout << "\nlongdouble1: " << longdouble1; std::cout << "\ndouble2: " << double2; std::cout << "\nfloat2: " << float2; std::cout << "\ndouble3: " << double3; std::cout << "\nfloat3: " << float3; std::cout << "\n"; }
Change the following Python code into C++ without altering its purpose.
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false); for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; } solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } } private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true; node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; } for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == 0) { arr[a + b * wid].val = w; if (search(a, b, w + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; } hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int a = x + dx[xx], b = y + dy[xx]; if (a < 0 || b < 0 || a >= wid || b >= hei) continue; if (arr[a + b * wid].val > -1) retval.set(xx); } return retval; } void solveIt() { int x, y, z; findStart(x, y, z); if (z == 99999) { cout << "\nCan't find start point!\n"; return; } search(x, y, z + 1, 1); if (z > 1) search(x, y, z - 1, -1); } void findStart(int& x, int& y, int& z) { z = 99999; for (int b = 0; b < hei; b++) for (int a = 0; a < wid; a++) if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z) { x = a; y = b; z = arr[a + wid * b].val; } } vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; }; int main(int argc, char* argv[]) { int wid; string p; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; istringstream iss(p); vector<string> puzz; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz)); nSolver s; s.solve(puzz, wid); int c = 0; for (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }
Port the provided Python code into C++ while preserving the original functionality.
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false); for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; } solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } } private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true; node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; } for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == 0) { arr[a + b * wid].val = w; if (search(a, b, w + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; } hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int a = x + dx[xx], b = y + dy[xx]; if (a < 0 || b < 0 || a >= wid || b >= hei) continue; if (arr[a + b * wid].val > -1) retval.set(xx); } return retval; } void solveIt() { int x, y, z; findStart(x, y, z); if (z == 99999) { cout << "\nCan't find start point!\n"; return; } search(x, y, z + 1, 1); if (z > 1) search(x, y, z - 1, -1); } void findStart(int& x, int& y, int& z) { z = 99999; for (int b = 0; b < hei; b++) for (int a = 0; a < wid; a++) if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z) { x = a; y = b; z = arr[a + wid * b].val; } } vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; }; int main(int argc, char* argv[]) { int wid; string p; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; istringstream iss(p); vector<string> puzz; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz)); nSolver s; s.solve(puzz, wid); int c = 0; for (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }
Convert this Python block to C++, preserving its control flow and logic.
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; }; } auto Add(auto a, auto b) { return [=](auto f) { return [=](auto x) { return a(f)(b(f)(x)); }; }; } auto Multiply(auto a, auto b) { return [=](auto f) { return a(b(f)); }; } auto Exp(auto a, auto b) { return b(a); } auto IsZero(auto a){ return a([](auto){ return False; })(True); } auto Predecessor(auto a) { return [=](auto f) { return [=](auto x) { return a( [=](auto g) { return [=](auto h){ return h(g(f)); }; } )([=](auto){ return x; })([](auto y){ return y; }); }; }; } auto Subtract(auto a, auto b) { { return b([](auto c){ return Predecessor(c); })(a); }; } namespace { auto Divr(decltype(Zero), auto) { return Zero; } auto Divr(auto a, auto b) { auto a_minus_b = Subtract(a, b); auto isZero = IsZero(a_minus_b); return isZero (Zero) (Successor(Divr(isZero(Zero)(a_minus_b), b))); } } auto Divide(auto a, auto b) { return Divr(Successor(a), b); } template <int N> constexpr auto ToChurch() { if constexpr(N<=0) return Zero; else return Successor(ToChurch<N-1>()); } int ToInt(auto church) { return church([](int n){ return n + 1; })(0); } int main() { auto three = Successor(Successor(Successor(Zero))); auto four = Successor(three); auto six = ToChurch<6>(); auto ten = ToChurch<10>(); auto thousand = Exp(ten, three); std::cout << "\n 3 + 4 = " << ToInt(Add(three, four)); std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four)); std::cout << "\n 3^4 = " << ToInt(Exp(three, four)); std::cout << "\n 4^3 = " << ToInt(Exp(four, three)); std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero)); std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three)); std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four)); std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three)); std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six)); auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand)); auto looloolool = Successor(looloolooo); std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool); std::cout << "\n golden ratio = " << thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n"; }
Translate the given Python code snippet into C++ without altering its behavior.
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; }; } auto Add(auto a, auto b) { return [=](auto f) { return [=](auto x) { return a(f)(b(f)(x)); }; }; } auto Multiply(auto a, auto b) { return [=](auto f) { return a(b(f)); }; } auto Exp(auto a, auto b) { return b(a); } auto IsZero(auto a){ return a([](auto){ return False; })(True); } auto Predecessor(auto a) { return [=](auto f) { return [=](auto x) { return a( [=](auto g) { return [=](auto h){ return h(g(f)); }; } )([=](auto){ return x; })([](auto y){ return y; }); }; }; } auto Subtract(auto a, auto b) { { return b([](auto c){ return Predecessor(c); })(a); }; } namespace { auto Divr(decltype(Zero), auto) { return Zero; } auto Divr(auto a, auto b) { auto a_minus_b = Subtract(a, b); auto isZero = IsZero(a_minus_b); return isZero (Zero) (Successor(Divr(isZero(Zero)(a_minus_b), b))); } } auto Divide(auto a, auto b) { return Divr(Successor(a), b); } template <int N> constexpr auto ToChurch() { if constexpr(N<=0) return Zero; else return Successor(ToChurch<N-1>()); } int ToInt(auto church) { return church([](int n){ return n + 1; })(0); } int main() { auto three = Successor(Successor(Successor(Zero))); auto four = Successor(three); auto six = ToChurch<6>(); auto ten = ToChurch<10>(); auto thousand = Exp(ten, three); std::cout << "\n 3 + 4 = " << ToInt(Add(three, four)); std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four)); std::cout << "\n 3^4 = " << ToInt(Exp(three, four)); std::cout << "\n 4^3 = " << ToInt(Exp(four, three)); std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero)); std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three)); std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four)); std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three)); std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six)); auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand)); auto looloolool = Successor(looloolooo); std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool); std::cout << "\n golden ratio = " << thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n"; }
Write the same algorithm in C++ as shown in this Python implementation.
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Produce a functionally identical C++ code for the snippet given in Python.
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Generate a C++ translation of this Python snippet without changing its computational steps.
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};
Change the following Python code into C++ without altering its purpose.
import re from random import shuffle, randint dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25 class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)] self.solutions = [] def read_words(filename): max_len = max(n_rows, n_cols) words = [] with open(filename, "r") as file: for line in file: s = line.strip().lower() if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None: words.append(s) return words def place_message(grid, msg): msg = re.sub(r'[^A-Z]', "", msg.upper()) message_len = len(msg) if 0 < message_len < grid_size: gap_size = grid_size // message_len for i in range(0, message_len): pos = i * gap_size + randint(0, gap_size) grid.cells[pos // n_cols][pos % n_cols] = msg[i] return message_len return 0 def try_location(grid, word, direction, pos): r = pos // n_cols c = pos % n_cols length = len(word) if (dirs[direction][0] == 1 and (length + c) > n_cols) or \ (dirs[direction][0] == -1 and (length - 1) > c) or \ (dirs[direction][1] == 1 and (length + r) > n_rows) or \ (dirs[direction][1] == -1 and (length - 1) > r): return 0 rr = r cc = c i = 0 overlaps = 0 while i < length: if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]: return 0 cc += dirs[direction][0] rr += dirs[direction][1] i += 1 rr = r cc = c i = 0 while i < length: if grid.cells[rr][cc] == word[i]: overlaps += 1 else: grid.cells[rr][cc] = word[i] if i < length - 1: cc += dirs[direction][0] rr += dirs[direction][1] i += 1 letters_placed = length - overlaps if letters_placed > 0: grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr)) return letters_placed def try_place_word(grid, word): rand_dir = randint(0, len(dirs)) rand_pos = randint(0, grid_size) for direction in range(0, len(dirs)): direction = (direction + rand_dir) % len(dirs) for pos in range(0, grid_size): pos = (pos + rand_pos) % grid_size letters_placed = try_location(grid, word, direction, pos) if letters_placed > 0: return letters_placed return 0 def create_word_search(words): grid = None num_attempts = 0 while num_attempts < 100: num_attempts += 1 shuffle(words) grid = Grid() message_len = place_message(grid, "Rosetta Code") target = grid_size - message_len cells_filled = 0 for word in words: cells_filled += try_place_word(grid, word) if cells_filled == target: if len(grid.solutions) >= min_words: grid.num_attempts = num_attempts return grid else: break return grid def print_result(grid): if grid is None or grid.num_attempts == 0: print("No grid to display") return size = len(grid.solutions) print("Attempts: {0}".format(grid.num_attempts)) print("Number of words: {0}".format(size)) print("\n 0 1 2 3 4 5 6 7 8 9\n") for r in range(0, n_rows): print("{0} ".format(r), end='') for c in range(0, n_cols): print(" %c " % grid.cells[r][c], end='') print() print() for i in range(0, size - 1, 2): print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1])) if size % 2 == 1: print(grid.solutions[size - 1]) if __name__ == "__main__": print_result(create_word_search(read_words("unixdict.txt")))
#include <iomanip> #include <ctime> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25; class Cell { public: Cell() : val( 0 ), cntOverlap( 0 ) {} char val; int cntOverlap; }; class Word { public: Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {} bool operator ==( const std::string& s ) { return 0 == word.compare( s ); } std::string word; int cols, rows, cole, rowe, dx, dy; }; class words { public: void create( std::string& file ) { std::ifstream f( file.c_str(), std::ios_base::in ); std::string word; while( f >> word ) { if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue; if( word.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) != word.npos ) continue; dictionary.push_back( word ); } f.close(); std::random_shuffle( dictionary.begin(), dictionary.end() ); buildPuzzle(); } void printOut() { std::cout << "\t"; for( int x = 0; x < WID; x++ ) std::cout << x << " "; std::cout << "\n\n"; for( int y = 0; y < HEI; y++ ) { std::cout << y << "\t"; for( int x = 0; x < WID; x++ ) std::cout << puzzle[x][y].val << " "; std::cout << "\n"; } size_t wid1 = 0, wid2 = 0; for( size_t x = 0; x < used.size(); x++ ) { if( x & 1 ) { if( used[x].word.length() > wid1 ) wid1 = used[x].word.length(); } else { if( used[x].word.length() > wid2 ) wid2 = used[x].word.length(); } } std::cout << "\n"; std::vector<Word>::iterator w = used.begin(); while( w != used.end() ) { std::cout << std::right << std::setw( wid1 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\t"; w++; if( w == used.end() ) break; std::cout << std::setw( wid2 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\n"; w++; } std::cout << "\n\n"; } private: void addMsg() { std::string msg = "ROSETTACODE"; int stp = 9, p = rand() % stp; for( size_t x = 0; x < msg.length(); x++ ) { puzzle[p % WID][p / HEI].val = msg.at( x ); p += rand() % stp + 4; } } int getEmptySpaces() { int es = 0; for( int y = 0; y < HEI; y++ ) { for( int x = 0; x < WID; x++ ) { if( !puzzle[x][y].val ) es++; } } return es; } bool check( std::string word, int c, int r, int dc, int dr ) { for( size_t a = 0; a < word.length(); a++ ) { if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false; if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false; c += dc; r += dr; } return true; } bool setWord( std::string word, int c, int r, int dc, int dr ) { if( !check( word, c, r, dc, dr ) ) return false; int sx = c, sy = r; for( size_t a = 0; a < word.length(); a++ ) { if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a ); else puzzle[c][r].cntOverlap++; c += dc; r += dr; } used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) ); return true; } bool add2Puzzle( std::string word ) { int x = rand() % WID, y = rand() % HEI, z = rand() % 8; for( int d = z; d < z + 8; d++ ) { switch( d % 8 ) { case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break; case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break; case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break; case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break; case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break; case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break; case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break; case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break; } } return false; } void clearWord() { if( used.size() ) { Word lastW = used.back(); used.pop_back(); for( size_t a = 0; a < lastW.word.length(); a++ ) { if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) { puzzle[lastW.cols][lastW.rows].val = 0; } if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) { puzzle[lastW.cols][lastW.rows].cntOverlap--; } lastW.cols += lastW.dx; lastW.rows += lastW.dy; } } } void buildPuzzle() { addMsg(); int es = 0, cnt = 0; size_t idx = 0; do { for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) { if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue; if( add2Puzzle( *w ) ) { es = getEmptySpaces(); if( !es && used.size() >= MIN_WORD_CNT ) return; } } clearWord(); std::random_shuffle( dictionary.begin(), dictionary.end() ); } while( ++cnt < 100 ); } std::vector<Word> used; std::vector<std::string> dictionary; Cell puzzle[WID][HEI]; }; int main( int argc, char* argv[] ) { unsigned s = unsigned( time( 0 ) ); srand( s ); words w; w.create( std::string( "unixdict.txt" ) ); w.printOut(); return 0; }
Please provide an equivalent version of this Python code in C++.
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
import pickle class Entity: def __init__(self): self.name = "Entity" def printName(self): print self.name class Person(Entity): def __init__(self): self.name = "Cletus" instance1 = Person() instance1.printName() instance2 = Entity() instance2.printName() target = file("objects.dat", "w") pickle.dump((instance1, instance2), target) target.close() print "Serialized..." target = file("objects.dat") i1, i2 = pickle.load(target) print "Unserialized..." i1.printName() i2.printName()
#include <string> #include <fstream> #include <boost/serialization/string.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/base_object.hpp> #include <iostream> class Employee { public : Employee( ) { } Employee ( const std::string &dep , const std::string &namen ) : department( dep ) , name( namen ) { my_id = count++ ; } std::string getName( ) const { return name ; } std::string getDepartment( ) const { return department ; } int getId( ) const { return my_id ; } void setDepartment( const std::string &dep ) { department.assign( dep ) ; } virtual void print( ) { std::cout << "Name: " << name << '\n' ; std::cout << "Id: " << my_id << '\n' ; std::cout << "Department: " << department << '\n' ; } virtual ~Employee( ) { } static int count ; private : std::string name ; std::string department ; int my_id ; friend class boost::serialization::access ; template <class Archive> void serialize( Archive &ar, const unsigned int version ) { ar & my_id ; ar & name ; ar & department ; } } ; class Worker : public Employee { public : Worker( const std::string & dep, const std::string &namen , double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { } Worker( ) { } double getSalary( ) { return salary ; } void setSalary( double pay ) { if ( pay > 0 ) salary = pay ; } virtual void print( ) { Employee::print( ) ; std::cout << "wage per hour: " << salary << '\n' ; } private : double salary ; friend class boost::serialization::access ; template <class Archive> void serialize ( Archive & ar, const unsigned int version ) { ar & boost::serialization::base_object<Employee>( *this ) ; ar & salary ; } } ; int Employee::count = 0 ; int main( ) { std::ofstream storefile( "/home/ulrich/objects.dat" ) ; const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ; const Employee emp2( "maintenance" , "John Berry" ) ; const Employee emp3( "repair" , "Pawel Lichatschow" ) ; const Employee emp4( "IT" , "Marian Niculescu" ) ; const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ; const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ; boost::archive::text_oarchive oar ( storefile ) ; oar << emp1 ; oar << emp2 ; oar << emp3 ; oar << emp4 ; oar << worker1 ; oar << worker2 ; storefile.close( ) ; std::cout << "Reading out the data again\n" ; Employee e1 , e2 , e3 , e4 ; Worker w1, w2 ; std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ; boost::archive::text_iarchive iar( sourcefile ) ; iar >> e1 >> e2 >> e3 >> e4 ; iar >> w1 >> w2 ; sourcefile.close( ) ; std::cout << "And here are the data after deserialization!( abridged):\n" ; e1.print( ) ; e3.print( ) ; w2.print( ) ; return 0 ; }
Write a version of this Python function in C++ with identical behavior.
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
Write a version of this Python function in C++ with identical behavior.
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
Port the following code from Python to C++ with equivalent syntax and logic.
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
from datetime import date def longYear(y): return 52 < date(y, 12, 28).isocalendar()[1] def main(): for year in [ x for x in range(2000, 1 + 2100) if longYear(x) ]: print(year) if __name__ == '__main__': main()
#include <stdio.h> #include <math.h> int p(int year) { return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7; } int is_long_year(int year) { return p(year) == 4 || p(year - 1) == 3; } void print_long_years(int from, int to) { for (int year = from; year <= to; ++year) { if (is_long_year(year)) { printf("%d ", year); } } } int main() { printf("Long (53 week) years between 1800 and 2100\n\n"); print_long_years(1800, 2100); printf("\n"); return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from sympy import divisors from sympy.combinatorics.subsets import Subset def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True return False def printZumkellers(N, oddonly=False): nprinted = 0 for n in range(1, 10**5): if (oddonly == False or n % 2) and isZumkeller(n): print(f'{n:>8}', end='') nprinted += 1 if nprinted % 10 == 0: print() if nprinted >= N: return print("220 Zumkeller numbers:") printZumkellers(220) print("\n\n40 odd Zumkeller numbers:") printZumkellers(40, True)
#include <iostream"> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> #include <numeric> using namespace std; const uint* binary(uint n, uint length); uint sum_subset_unrank_bin(const vector<uint>& d, uint r); vector<uint> factors(uint x); bool isPrime(uint number); bool isZum(uint n); ostream& operator<<(ostream& os, const vector<uint>& zumz) { for (uint i = 0; i < zumz.size(); i++) { if (i % 10 == 0) os << endl; os << setw(10) << zumz[i] << ' '; } return os; } int main() { cout << "First 220 Zumkeller numbers:" << endl; vector<uint> zumz; for (uint n = 2; zumz.size() < 220; n++) if (isZum(n)) zumz.push_back(n); cout << zumz << endl << endl; cout << "First 40 odd Zumkeller numbers:" << endl; vector<uint> zumz2; for (uint n = 2; zumz2.size() < 40; n++) if (n % 2 && isZum(n)) zumz2.push_back(n); cout << zumz2 << endl << endl; cout << "First 40 odd Zumkeller numbers not ending in 5:" << endl; vector<uint> zumz3; for (uint n = 2; zumz3.size() < 40; n++) if (n % 2 && (n % 10) != 5 && isZum(n)) zumz3.push_back(n); cout << zumz3 << endl << endl; return 0; } const uint* binary(uint n, uint length) { uint* bin = new uint[length]; fill(bin, bin + length, 0); for (uint i = 0; n > 0; i++) { uint rem = n % 2; n /= 2; if (rem) bin[length - 1 - i] = 1; } return bin; } uint sum_subset_unrank_bin(const vector<uint>& d, uint r) { vector<uint> subset; const uint* bits = binary(r, d.size() - 1); for (uint i = 0; i < d.size() - 1; i++) if (bits[i]) subset.push_back(d[i]); delete[] bits; return accumulate(subset.begin(), subset.end(), 0u); } vector<uint> factors(uint x) { vector<uint> result; for (uint i = 1; i * i <= x; i++) { if (x % i == 0) { result.push_back(i); if (x / i != i) result.push_back(x / i); } } sort(result.begin(), result.end()); return result; } bool isPrime(uint number) { if (number < 2) return false; if (number == 2) return true; if (number % 2 == 0) return false; for (uint i = 3; i * i <= number; i += 2) if (number % i == 0) return false; return true; } bool isZum(uint n) { if (isPrime(n)) return false; const auto d = factors(n); uint s = accumulate(d.begin(), d.end(), 0u); if (s % 2 || s < 2 * n) return false; if (n % 2 || d.size() >= 24) return true; if (!(s % 2) && d[d.size() - 1] <= s / 2) for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) if (sum_subset_unrank_bin(d, x) == s / 2) return true; return false; }
Preserve the algorithm and functionality while converting the code from Python to C++.
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; map original{ {"name", "Rocket Skates"}, {"price", "12.75"}, {"color", "yellow"} }; map update{ {"price", "15.25"}, {"color", "red"}, {"year", "1974"} }; map merged(merge(original, update)); for (auto&& i : merged) std::cout << "key: " << i.first << ", value: " << i.second << '\n'; return 0; }
Write a version of this Python function in C++ with identical behavior.
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; map original{ {"name", "Rocket Skates"}, {"price", "12.75"}, {"color", "yellow"} }; map update{ {"price", "15.25"}, {"color", "red"}, {"year", "1974"} }; map merged(merge(original, update)); for (auto&& i : merged) std::cout << "key: " << i.first << ", value: " << i.second << '\n'; return 0; }
Write the same algorithm in C++ as shown in this Python implementation.
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; } template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } } int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1); return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; } template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } } int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1); return 0; }
Write the same algorithm in C++ as shown in this Python implementation.
import random, sys def makerule(data, context): rule = {} words = data.split(' ') index = context for word in words[index:]: key = ' '.join(words[index-context:index]) if key in rule: rule[key].append(word) else: rule[key] = [word] index += 1 return rule def makestring(rule, length): oldwords = random.choice(list(rule.keys())).split(' ') string = ' '.join(oldwords) + ' ' for i in range(length): try: key = ' '.join(oldwords) newword = random.choice(rule[key]) string += newword + ' ' for word in range(len(oldwords)): oldwords[word] = oldwords[(word + 1) % len(oldwords)] oldwords[-1] = newword except KeyError: return string return string if __name__ == '__main__': with open(sys.argv[1], encoding='utf8') as f: data = f.read() rule = makerule(data, int(sys.argv[2])) string = makestring(rule, int(sys.argv[3])) print(string)
#include <ctime> #include <iostream> #include <algorithm> #include <fstream> #include <string> #include <vector> #include <map> class markov { public: void create( std::string& file, unsigned int keyLen, unsigned int words ) { std::ifstream f( file.c_str(), std::ios_base::in ); fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() ); f.close(); if( fileBuffer.length() < 1 ) return; createDictionary( keyLen ); createText( words - keyLen ); } private: void createText( int w ) { std::string key, first, second; size_t next; std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin(); std::advance( it, rand() % dictionary.size() ); key = ( *it ).first; std::cout << key; while( true ) { std::vector<std::string> d = dictionary[key]; if( d.size() < 1 ) break; second = d[rand() % d.size()]; if( second.length() < 1 ) break; std::cout << " " << second; if( --w < 0 ) break; next = key.find_first_of( 32, 0 ); first = key.substr( next + 1 ); key = first + " " + second; } std::cout << "\n"; } void createDictionary( unsigned int kl ) { std::string w1, key; size_t wc = 0, pos, next; next = fileBuffer.find_first_not_of( 32, 0 ); if( next == std::string::npos ) return; while( wc < kl ) { pos = fileBuffer.find_first_of( ' ', next ); w1 = fileBuffer.substr( next, pos - next ); key += w1 + " "; next = fileBuffer.find_first_not_of( 32, pos + 1 ); if( next == std::string::npos ) return; wc++; } key = key.substr( 0, key.size() - 1 ); while( true ) { next = fileBuffer.find_first_not_of( 32, pos + 1 ); if( next == std::string::npos ) return; pos = fileBuffer.find_first_of( 32, next ); w1 = fileBuffer.substr( next, pos - next ); if( w1.size() < 1 ) break; if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) dictionary[key].push_back( w1 ); key = key.substr( key.find_first_of( 32 ) + 1 ) + " " + w1; } } std::string fileBuffer; std::map<std::string, std::vector<std::string> > dictionary; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); markov m; m.create( std::string( "alice_oz.txt" ), 3, 200 ); return 0; }
Convert this Python snippet to C++ and keep its semantics consistent.
from collections import namedtuple, deque from pprint import pprint as pp inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost']) class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges} def dijkstra(self, source, dest): assert source in self.vertices dist = {vertex: inf for vertex in self.vertices} previous = {vertex: None for vertex in self.vertices} dist[source] = 0 q = self.vertices.copy() neighbours = {vertex: set() for vertex in self.vertices} for start, end, cost in self.edges: neighbours[start].add((end, cost)) neighbours[end].add((start, cost)) while q: u = min(q, key=lambda vertex: dist[vertex]) q.remove(u) if dist[u] == inf or u == dest: break for v, cost in neighbours[u]: alt = dist[u] + cost if alt < dist[v]: dist[v] = alt previous[v] = u s, u = deque(), dest while previous[u]: s.appendleft(u) u = previous[u] s.appendleft(u) return s graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10), ("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6), ("e", "f", 9)]) pp(graph.dijkstra("a", "e"))
#include <iostream> #include <vector> #include <string> #include <list> #include <limits> #include <set> #include <utility> #include <algorithm> #include <iterator> typedef int vertex_t; typedef double weight_t; const weight_t max_weight = std::numeric_limits<double>::infinity(); struct neighbor { vertex_t target; weight_t weight; neighbor(vertex_t arg_target, weight_t arg_weight) : target(arg_target), weight(arg_weight) { } }; typedef std::vector<std::vector<neighbor> > adjacency_list_t; void DijkstraComputePaths(vertex_t source, const adjacency_list_t &adjacency_list, std::vector<weight_t> &min_distance, std::vector<vertex_t> &previous) { int n = adjacency_list.size(); min_distance.clear(); min_distance.resize(n, max_weight); min_distance[source] = 0; previous.clear(); previous.resize(n, -1); std::set<std::pair<weight_t, vertex_t> > vertex_queue; vertex_queue.insert(std::make_pair(min_distance[source], source)); while (!vertex_queue.empty()) { weight_t dist = vertex_queue.begin()->first; vertex_t u = vertex_queue.begin()->second; vertex_queue.erase(vertex_queue.begin()); const std::vector<neighbor> &neighbors = adjacency_list[u]; for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin(); neighbor_iter != neighbors.end(); neighbor_iter++) { vertex_t v = neighbor_iter->target; weight_t weight = neighbor_iter->weight; weight_t distance_through_u = dist + weight; if (distance_through_u < min_distance[v]) { vertex_queue.erase(std::make_pair(min_distance[v], v)); min_distance[v] = distance_through_u; previous[v] = u; vertex_queue.insert(std::make_pair(min_distance[v], v)); } } } } std::list<vertex_t> DijkstraGetShortestPathTo( vertex_t vertex, const std::vector<vertex_t> &previous) { std::list<vertex_t> path; for ( ; vertex != -1; vertex = previous[vertex]) path.push_front(vertex); return path; } int main() { adjacency_list_t adjacency_list(6); adjacency_list[0].push_back(neighbor(1, 7)); adjacency_list[0].push_back(neighbor(2, 9)); adjacency_list[0].push_back(neighbor(5, 14)); adjacency_list[1].push_back(neighbor(0, 7)); adjacency_list[1].push_back(neighbor(2, 10)); adjacency_list[1].push_back(neighbor(3, 15)); adjacency_list[2].push_back(neighbor(0, 9)); adjacency_list[2].push_back(neighbor(1, 10)); adjacency_list[2].push_back(neighbor(3, 11)); adjacency_list[2].push_back(neighbor(5, 2)); adjacency_list[3].push_back(neighbor(1, 15)); adjacency_list[3].push_back(neighbor(2, 11)); adjacency_list[3].push_back(neighbor(4, 6)); adjacency_list[4].push_back(neighbor(3, 6)); adjacency_list[4].push_back(neighbor(5, 9)); adjacency_list[5].push_back(neighbor(0, 14)); adjacency_list[5].push_back(neighbor(2, 2)); adjacency_list[5].push_back(neighbor(4, 9)); std::vector<weight_t> min_distance; std::vector<vertex_t> previous; DijkstraComputePaths(0, adjacency_list, min_distance, previous); std::cout << "Distance from 0 to 4: " << min_distance[4] << std::endl; std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous); std::cout << "Path : "; std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, " ")); std::cout << std::endl; return 0; }
Generate an equivalent C++ version of this Python code.
import copy, random def bitcount(n): return bin(n).count("1") def reoderingSign(i, j): k = i >> 1 sum = 0 while k != 0: sum += bitcount(k & j) k = k >> 1 return 1.0 if ((sum & 1) == 0) else -1.0 class Vector: def __init__(self, da): self.dims = da def dot(self, other): return (self * other + other * self) * 0.5 def __getitem__(self, i): return self.dims[i] def __setitem__(self, i, v): self.dims[i] = v def __neg__(self): return self * -1.0 def __add__(self, other): result = copy.copy(other.dims) for i in xrange(0, len(self.dims)): result[i] += self.dims[i] return Vector(result) def __mul__(self, other): if isinstance(other, Vector): result = [0.0] * 32 for i in xrange(0, len(self.dims)): if self.dims[i] != 0.0: for j in xrange(0, len(self.dims)): if other.dims[j] != 0.0: s = reoderingSign(i, j) * self.dims[i] * other.dims[j] k = i ^ j result[k] += s return Vector(result) else: result = copy.copy(self.dims) for i in xrange(0, len(self.dims)): self.dims[i] *= other return Vector(result) def __str__(self): return str(self.dims) def e(n): assert n <= 4, "n must be less than 5" result = Vector([0.0] * 32) result[1 << n] = 1.0 return result def randomVector(): result = Vector([0.0] * 32) for i in xrange(0, 5): result += Vector([random.uniform(0, 1)]) * e(i) return result def randomMultiVector(): result = Vector([0.0] * 32) for i in xrange(0, 32): result[i] = random.uniform(0, 1) return result def main(): for i in xrange(0, 5): for j in xrange(0, 5): if i < j: if e(i).dot(e(j))[0] != 0.0: print "Unexpected non-null scalar product" return elif i == j: if e(i).dot(e(j))[0] == 0.0: print "Unexpected non-null scalar product" a = randomMultiVector() b = randomMultiVector() c = randomMultiVector() x = randomVector() print (a * b) * c print a * (b * c) print print a * (b + c) print a * b + a * c print print (a + b) * c print a * c + b * c print print x * x main()
#include <algorithm> #include <iostream> #include <random> #include <vector> double uniform01() { static std::default_random_engine generator; static std::uniform_real_distribution<double> distribution(0.0, 1.0); return distribution(generator); } int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } double reorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += bitCount(k & j); k = k >> 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } struct MyVector { public: MyVector(const std::vector<double> &da) : dims(da) { } double &operator[](size_t i) { return dims[i]; } const double &operator[](size_t i) const { return dims[i]; } MyVector operator+(const MyVector &rhs) const { std::vector<double> temp(dims); for (size_t i = 0; i < rhs.dims.size(); ++i) { temp[i] += rhs[i]; } return MyVector(temp); } MyVector operator*(const MyVector &rhs) const { std::vector<double> temp(dims.size(), 0.0); for (size_t i = 0; i < dims.size(); i++) { if (dims[i] != 0.0) { for (size_t j = 0; j < dims.size(); j++) { if (rhs[j] != 0.0) { auto s = reorderingSign(i, j) * dims[i] * rhs[j]; auto k = i ^ j; temp[k] += s; } } } } return MyVector(temp); } MyVector operator*(double scale) const { std::vector<double> temp(dims); std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; }); return MyVector(temp); } MyVector operator-() const { return *this * -1.0; } MyVector dot(const MyVector &rhs) const { return (*this * rhs + rhs * *this) * 0.5; } friend std::ostream &operator<<(std::ostream &, const MyVector &); private: std::vector<double> dims; }; std::ostream &operator<<(std::ostream &os, const MyVector &v) { auto it = v.dims.cbegin(); auto end = v.dims.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } MyVector e(int n) { if (n > 4) { throw new std::runtime_error("n must be less than 5"); } auto result = MyVector(std::vector<double>(32, 0.0)); result[1 << n] = 1.0; return result; } MyVector randomVector() { auto result = MyVector(std::vector<double>(32, 0.0)); for (int i = 0; i < 5; i++) { result = result + MyVector(std::vector<double>(1, uniform01())) * e(i); } return result; } MyVector randomMultiVector() { auto result = MyVector(std::vector<double>(32, 0.0)); for (int i = 0; i < 32; i++) { result[i] = uniform01(); } return result; } int main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (e(i).dot(e(j))[0] != 0.0) { std::cout << "Unexpected non-null scalar product."; return 1; } else if (i == j) { if (e(i).dot(e(j))[0] == 0.0) { std::cout << "Unexpected null scalar product."; } } } } } auto a = randomMultiVector(); auto b = randomMultiVector(); auto c = randomMultiVector(); auto x = randomVector(); std::cout << ((a * b) * c) << '\n'; std::cout << (a * (b * c)) << "\n\n"; std::cout << (a * (b + c)) << '\n'; std::cout << (a * b + a * c) << "\n\n"; std::cout << ((a + b) * c) << '\n'; std::cout << (a * c + b * c) << "\n\n"; std::cout << (x * x) << '\n'; return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { std::vector<Node> nodes; SuffixTree(const std::string& str) { nodes.push_back(Node{}); for (size_t i = 0; i < str.length(); i++) { addSuffix(str.substr(i)); } } void visualize() { if (nodes.size() == 0) { std::cout << "<empty>\n"; return; } std::function<void(int, const std::string&)> f; f = [&](int n, const std::string & pre) { auto children = nodes[n].ch; if (children.size() == 0) { std::cout << "- " << nodes[n].sub << '\n'; return; } std::cout << "+ " << nodes[n].sub << '\n'; auto it = std::begin(children); if (it != std::end(children)) do { if (std::next(it) == std::end(children)) break; std::cout << pre << "+-"; f(*it, pre + "| "); it = std::next(it); } while (true); std::cout << pre << "+-"; f(children[children.size() - 1], pre + " "); }; f(0, ""); } private: void addSuffix(const std::string & suf) { int n = 0; size_t i = 0; while (i < suf.length()) { char b = suf[i]; int x2 = 0; int n2; while (true) { auto children = nodes[n].ch; if (x2 == children.size()) { n2 = nodes.size(); nodes.push_back(Node(suf.substr(i), {})); nodes[n].ch.push_back(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } auto sub2 = nodes[n2].sub; size_t j = 0; while (j < sub2.size()) { if (suf[i + j] != sub2[j]) { auto n3 = n2; n2 = nodes.size(); nodes.push_back(Node(sub2.substr(0, j), { n3 })); nodes[n3].sub = sub2.substr(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } }; int main() { SuffixTree("banana$").visualize(); }
Generate an equivalent C++ version of this Python code.
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { std::vector<Node> nodes; SuffixTree(const std::string& str) { nodes.push_back(Node{}); for (size_t i = 0; i < str.length(); i++) { addSuffix(str.substr(i)); } } void visualize() { if (nodes.size() == 0) { std::cout << "<empty>\n"; return; } std::function<void(int, const std::string&)> f; f = [&](int n, const std::string & pre) { auto children = nodes[n].ch; if (children.size() == 0) { std::cout << "- " << nodes[n].sub << '\n'; return; } std::cout << "+ " << nodes[n].sub << '\n'; auto it = std::begin(children); if (it != std::end(children)) do { if (std::next(it) == std::end(children)) break; std::cout << pre << "+-"; f(*it, pre + "| "); it = std::next(it); } while (true); std::cout << pre << "+-"; f(children[children.size() - 1], pre + " "); }; f(0, ""); } private: void addSuffix(const std::string & suf) { int n = 0; size_t i = 0; while (i < suf.length()) { char b = suf[i]; int x2 = 0; int n2; while (true) { auto children = nodes[n].ch; if (x2 == children.size()) { n2 = nodes.size(); nodes.push_back(Node(suf.substr(i), {})); nodes[n].ch.push_back(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } auto sub2 = nodes[n2].sub; size_t j = 0; while (j < sub2.size()) { if (suf[i + j] != sub2[j]) { auto n3 = n2; n2 = nodes.size(); nodes.push_back(Node(sub2.substr(0, j), { n3 })); nodes[n3].sub = sub2.substr(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } }; int main() { SuffixTree("banana$").visualize(); }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
myDict = { "hello": 13, "world": 31, "!" : 71 } for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value)) for key in myDict: print ("key = %s" % key) for key in myDict.keys(): print ("key = %s" % key) for value in myDict.values(): print ("value = %s" % value)
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> dict { {"One", 1}, {"Two", 2}, {"Three", 7} }; dict["Three"] = 3; std::cout << "One: " << dict["One"] << std::endl; std::cout << "Key/Value pairs: " << std::endl; for(auto& kv: dict) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } return 0; }
Translate the given Python code snippet into C++ without altering its behavior.
>>> class num(int): def __init__(self, b): if 1 <= b <= 10: return int.__init__(self+0) else: raise ValueError,"Value %s should be >=0 and <= 10" % b >>> x = num(3) >>> x = num(11) Traceback (most recent call last): File "<pyshell x = num(11) File "<pyshell raise ValueError,"Value %s should be >=0 and <= 10" % b ValueError: Value 11 should be >=0 and <= 10 >>> x 3 >>> type(x) <class '__main__.num'> >>>
#include <stdexcept> class tiny_int { public: tiny_int(int i): value(i) { if (value < 1) throw std::out_of_range("tiny_int: value smaller than 1"); if (value > 10) throw std::out_of_range("tiny_int: value larger than 10"); } operator int() const { return value; } tiny_int& operator+=(int i) { *this = value + i; return *this; } tiny_int& operator-=(int i) { *this = value - i; return *this; } tiny_int& operator*=(int i) { *this = value * i; return *this; } tiny_int& operator/=(int i) { *this = value / i; return *this; } tiny_int& operator<<=(int i) { *this = value << i; return *this; } tiny_int& operator>>=(int i) { *this = value >> i; return *this; } tiny_int& operator&=(int i) { *this = value & i; return *this; } tiny_int& operator|=(int i) { *this = value | i; return *this; } private: unsigned char value; };
Preserve the algorithm and functionality while converting the code from Python to C++.
from sympy.ntheory import factorint def D(n): if n < 0: return -D(-n) elif n < 2: return 0 else: fdict = factorint(n) if len(fdict) == 1 and 1 in fdict: return 1 return sum([n * e // p for p, e in fdict.items()]) for n in range(-99, 101): print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '') print() for m in range(1, 21): print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
#include <iomanip> #include <iostream> #include <boost/multiprecision/cpp_int.hpp> template <typename IntegerType> IntegerType arithmetic_derivative(IntegerType n) { bool negative = n < 0; if (negative) n = -n; if (n < 2) return 0; IntegerType sum = 0, count = 0, m = n; while ((m & 1) == 0) { m >>= 1; count += n; } if (count > 0) sum += count / 2; for (IntegerType p = 3, sq = 9; sq <= m; p += 2) { count = 0; while (m % p == 0) { m /= p; count += n; } if (count > 0) sum += count / p; sq += (p + 1) << 2; } if (m > 1) sum += n / m; if (negative) sum = -sum; return sum; } int main() { using boost::multiprecision::int128_t; for (int n = -99, i = 0; n <= 100; ++n, ++i) { std::cout << std::setw(4) << arithmetic_derivative(n) << ((i + 1) % 10 == 0 ? '\n' : ' '); } int128_t p = 10; std::cout << '\n'; for (int i = 0; i < 20; ++i, p *= 10) { std::cout << "D(10^" << std::setw(2) << i + 1 << ") / 7 = " << arithmetic_derivative(p) / 7 << '\n'; } }
Convert this Python block to C++, preserving its control flow and logic.
from itertools import permutations numList = [2,3,1] baseList = [] for i in numList: for j in range(0,i): baseList.append(i) stringDict = {'A':2,'B':3,'C':1} baseString="" for i in stringDict: for j in range(0,stringDict[i]): baseString+=i print("Permutations for " + str(baseList) + " : ") [print(i) for i in set(permutations(baseList))] print("Permutations for " + baseString + " : ") [print(i) for i in set(permutations(baseString))]
#include <algorithm> #include <iostream> int main() { std::string str("AABBBC"); int count = 0; do { std::cout << str << (++count % 10 == 0 ? '\n' : ' '); } while (std::next_permutation(str.begin(), str.end())); }
Port the following code from Python to C++ with equivalent syntax and logic.
def penrose(depth): print( <g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)"> <use href=" <use href=" </g> <g id="B{d+1}"> <use href=" <use href=" </g> <g id="G"> <use href=" <use href=" </g> </defs> <g transform="scale(2, 2)"> <use href=" <use href=" <use href=" <use href=" <use href=" </g> </svg>''') penrose(6)
#include <cmath> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <sstream> #include <stack> #include <string> #include <tuple> int main() { std::ofstream out("penrose_tiling.svg"); if (!out) { std::cerr << "Cannot open output file.\n"; return EXIT_FAILURE; } std::string penrose("[N]++[N]++[N]++[N]++[N]"); for (int i = 1; i <= 4; ++i) { std::string next; for (char ch : penrose) { switch (ch) { case 'A': break; case 'M': next += "OA++PA----NA[-OA----MA]++"; break; case 'N': next += "+OA--PA[---MA--NA]+"; break; case 'O': next += "-MA++NA[+++OA++PA]-"; break; case 'P': next += "--OA++++MA[+PA++++NA]--NA"; break; default: next += ch; break; } } penrose = std::move(next); } const double r = 30; const double pi5 = 0.628318530717959; double x = r * 8, y = r * 8, theta = pi5; std::set<std::string> svg; std::stack<std::tuple<double, double, double>> stack; for (char ch : penrose) { switch (ch) { case 'A': { double nx = x + r * std::cos(theta); double ny = y + r * std::sin(theta); std::ostringstream line; line << std::fixed << std::setprecision(3) << "<line x1='" << x << "' y1='" << y << "' x2='" << nx << "' y2='" << ny << "'/>"; svg.insert(line.str()); x = nx; y = ny; } break; case '+': theta += pi5; break; case '-': theta -= pi5; break; case '[': stack.push({x, y, theta}); break; case ']': std::tie(x, y, theta) = stack.top(); stack.pop(); break; } } out << "<svg xmlns='http: << "' width='" << r * 16 << "'>\n" << "<rect height='100%' width='100%' fill='black'/>\n" << "<g stroke='rgb(255,165,0)'>\n"; for (const auto& line : svg) out << line << '\n'; out << "</g>\n</svg>\n"; return EXIT_SUCCESS; }
Write the same code in C++ as shown below in Python.
from sympy import factorint sphenics1m, sphenic_triplets1m = [], [] for i in range(3, 1_000_000): d = factorint(i) if len(d) == 3 and sum(d.values()) == 3: sphenics1m.append(i) if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1: sphenic_triplets1m.append(i) print('Sphenic numbers less than 1000:') for i, n in enumerate(sphenics1m): if n < 1000: print(f'{n : 5}', end='\n' if (i + 1) % 15 == 0 else '') else: break print('\n\nSphenic triplets less than 10_000:') for i, n in enumerate(sphenic_triplets1m): if n < 10_000: print(f'({n - 2} {n - 1} {n})', end='\n' if (i + 1) % 3 == 0 else ' ') else: break print('\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m), 'sphenic triplets less than 1 million.') S2HK = sphenics1m[200_000 - 1] T5K = sphenic_triplets1m[5000 - 1] print(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.') print(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')
#include <algorithm> #include <cassert> #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; } std::vector<int> prime_factors(int n) { std::vector<int> factors; if (n > 1 && (n & 1) == 0) { factors.push_back(2); while ((n & 1) == 0) n >>= 1; } for (int p = 3; p * p <= n; p += 2) { if (n % p == 0) { factors.push_back(p); while (n % p == 0) n /= p; } } if (n > 1) factors.push_back(n); return factors; } int main() { const int limit = 1000000; const int imax = limit / 6; std::vector<bool> sieve = prime_sieve(imax + 1); std::vector<bool> sphenic(limit + 1, false); for (int i = 0; i <= imax; ++i) { if (!sieve[i]) continue; int jmax = std::min(imax, limit / (i * i)); if (jmax <= i) break; for (int j = i + 1; j <= jmax; ++j) { if (!sieve[j]) continue; int p = i * j; int kmax = std::min(imax, limit / p); if (kmax <= j) break; for (int k = j + 1; k <= kmax; ++k) { if (!sieve[k]) continue; assert(p * k <= limit); sphenic[p * k] = true; } } } std::cout << "Sphenic numbers < 1000:\n"; for (int i = 0, n = 0; i < 1000; ++i) { if (!sphenic[i]) continue; ++n; std::cout << std::setw(3) << i << (n % 15 == 0 ? '\n' : ' '); } std::cout << "\nSphenic triplets < 10,000:\n"; for (int i = 0, n = 0; i < 10000; ++i) { if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) { ++n; std::cout << "(" << i - 2 << ", " << i - 1 << ", " << i << ")" << (n % 3 == 0 ? '\n' : ' '); } } int count = 0, triplets = 0, s200000 = 0, t5000 = 0; for (int i = 0; i < limit; ++i) { if (!sphenic[i]) continue; ++count; if (count == 200000) s200000 = i; if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) { ++triplets; if (triplets == 5000) t5000 = i; } } std::cout << "\nNumber of sphenic numbers < 1,000,000: " << count << '\n'; std::cout << "Number of sphenic triplets < 1,000,000: " << triplets << '\n'; auto factors = prime_factors(s200000); assert(factors.size() == 3); std::cout << "The 200,000th sphenic number: " << s200000 << " = " << factors[0] << " * " << factors[1] << " * " << factors[2] << '\n'; std::cout << "The 5,000th sphenic triplet: (" << t5000 - 2 << ", " << t5000 - 1 << ", " << t5000 << ")\n"; }
Keep all operations the same but rewrite the snippet in C++.
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: index -=1 break index += 1 return (index, so_far) if depth > 1 else so_far if __name__ == "__main__": from pprint import pformat def pnest(nest:list, width: int=9) -> str: text = pformat(nest, width=width).replace('\n', '\n ') print(f" OR {text}\n") exercises = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3], ] for flat in exercises: nest = to_tree(flat) print(f"{flat} NESTS TO: {nest}") pnest(nest)
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { tree.push_back(*first); ++first; } else { tree.push_back(MakeTree(first, last, depth + 1)); first = find(first + 1, last, depth); } } return tree; } void PrintTree(input_iterator auto first, input_iterator auto last) { cout << "["; for(auto it = first; it != last; ++it) { if(it != first) cout << ", "; if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>) { cout << *it; } else { if(it->type() == typeid(unsigned int)) { cout << any_cast<unsigned int>(*it); } else { const auto& subTree = any_cast<vector<any>>(*it); PrintTree(subTree.begin(), subTree.end()); } } } cout << "]"; } int main(void) { auto execises = vector<vector<unsigned int>> { {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3} }; for(const auto& e : execises) { auto tree = MakeTree(e.begin(), e.end()); PrintTree(e.begin(), e.end()); cout << " Nests to:\n"; PrintTree(tree.begin(), tree.end()); cout << "\n\n"; } }
Generate an equivalent C++ version of this Python code.
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: index -=1 break index += 1 return (index, so_far) if depth > 1 else so_far if __name__ == "__main__": from pprint import pformat def pnest(nest:list, width: int=9) -> str: text = pformat(nest, width=width).replace('\n', '\n ') print(f" OR {text}\n") exercises = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3], ] for flat in exercises: nest = to_tree(flat) print(f"{flat} NESTS TO: {nest}") pnest(nest)
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { tree.push_back(*first); ++first; } else { tree.push_back(MakeTree(first, last, depth + 1)); first = find(first + 1, last, depth); } } return tree; } void PrintTree(input_iterator auto first, input_iterator auto last) { cout << "["; for(auto it = first; it != last; ++it) { if(it != first) cout << ", "; if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>) { cout << *it; } else { if(it->type() == typeid(unsigned int)) { cout << any_cast<unsigned int>(*it); } else { const auto& subTree = any_cast<vector<any>>(*it); PrintTree(subTree.begin(), subTree.end()); } } } cout << "]"; } int main(void) { auto execises = vector<vector<unsigned int>> { {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3} }; for(const auto& e : execises) { auto tree = MakeTree(e.begin(), e.end()); PrintTree(e.begin(), e.end()); cout << " Nests to:\n"; PrintTree(tree.begin(), tree.end()); cout << "\n\n"; } }
Change the following Python code into C++ without altering its purpose.
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: index -=1 break index += 1 return (index, so_far) if depth > 1 else so_far if __name__ == "__main__": from pprint import pformat def pnest(nest:list, width: int=9) -> str: text = pformat(nest, width=width).replace('\n', '\n ') print(f" OR {text}\n") exercises = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3], ] for flat in exercises: nest = to_tree(flat) print(f"{flat} NESTS TO: {nest}") pnest(nest)
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { tree.push_back(*first); ++first; } else { tree.push_back(MakeTree(first, last, depth + 1)); first = find(first + 1, last, depth); } } return tree; } void PrintTree(input_iterator auto first, input_iterator auto last) { cout << "["; for(auto it = first; it != last; ++it) { if(it != first) cout << ", "; if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>) { cout << *it; } else { if(it->type() == typeid(unsigned int)) { cout << any_cast<unsigned int>(*it); } else { const auto& subTree = any_cast<vector<any>>(*it); PrintTree(subTree.begin(), subTree.end()); } } } cout << "]"; } int main(void) { auto execises = vector<vector<unsigned int>> { {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3} }; for(const auto& e : execises) { auto tree = MakeTree(e.begin(), e.end()); PrintTree(e.begin(), e.end()); cout << " Nests to:\n"; PrintTree(tree.begin(), tree.end()); cout << "\n\n"; } }
Translate the given Python code snippet into C++ without altering its behavior.
from __future__ import print_function import os import hashlib import datetime def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"): knownFiles = {} for root, dirs, files in os.walk(pth): for fina in files: fullFina = os.path.join(root, fina) isSymLink = os.path.islink(fullFina) if isSymLink: continue si = os.path.getsize(fullFina) if si < minSize: continue if si not in knownFiles: knownFiles[si] = {} h = hashlib.new(hashName) h.update(open(fullFina, "rb").read()) hashed = h.digest() if hashed in knownFiles[si]: fileRec = knownFiles[si][hashed] fileRec.append(fullFina) else: knownFiles[si][hashed] = [fullFina] sizeList = list(knownFiles.keys()) sizeList.sort(reverse=True) for si in sizeList: filesAtThisSize = knownFiles[si] for hashVal in filesAtThisSize: if len(filesAtThisSize[hashVal]) < 2: continue fullFinaLi = filesAtThisSize[hashVal] print ("=======Duplicate=======") for fullFina in fullFinaLi: st = os.stat(fullFina) isHardLink = st.st_nlink > 1 infoStr = [] if isHardLink: infoStr.append("(Hard linked)") fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ') print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr)) if __name__=="__main__": FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
#include<iostream> #include<string> #include<boost/filesystem.hpp> #include<boost/format.hpp> #include<boost/iostreams/device/mapped_file.hpp> #include<optional> #include<algorithm> #include<iterator> #include<execution> #include"dependencies/xxhash.hpp" template<typename T, typename V, typename F> size_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) { size_t partitions = 0; while (begin != end) { auto const& value = getvalue(*begin); auto current = begin; while (++current != end && getvalue(*current) == value); callback(begin, current, value); ++partitions; begin = current; } return partitions; } namespace bi = boost::iostreams; namespace fs = boost::filesystem; struct file_entry { public: explicit file_entry(fs::directory_entry const & entry) : path_{entry.path()}, size_{fs::file_size(entry)} {} auto size() const { return size_; } auto const& path() const { return path_; } auto get_hash() { if (!hash_) hash_ = compute_hash(); return *hash_; } private: xxh::hash64_t compute_hash() { bi::mapped_file_source source; source.open<fs::wpath>(this->path()); if (!source.is_open()) { std::cerr << "Cannot open " << path() << std::endl; throw std::runtime_error("Cannot open file"); } xxh::hash_state64_t hash_stream; hash_stream.update(source.data(), size_); return hash_stream.digest(); } private: fs::wpath path_; uintmax_t size_; std::optional<xxh::hash64_t> hash_; }; using vector_type = std::vector<file_entry>; using iterator_type = vector_type::iterator; auto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) { size_t found = 0, ignored = 0; if (!fs::is_directory(path)) { std::cerr << path << " is not a directory!" << std::endl; } else { std::cerr << "Searching " << path << std::endl; for (auto& e : fs::recursive_directory_iterator(path)) { ++found; if (fs::is_regular_file(e) && fs::file_size(e) >= min_size) file_vector.emplace_back(e); else ++ignored; } } return std::make_tuple(found, ignored); } int main(int argn, char* argv[]) { vector_type files; for (auto i = 1; i < argn; ++i) { fs::wpath path(argv[i]); auto [found, ignored] = find_files_in_dir(path, files); std::cerr << boost::format{ " %1$6d files found\n" " %2$6d files ignored\n" " %3$6d files added\n" } % found % ignored % (found - ignored) << std::endl; } std::cerr << "Found " << files.size() << " regular files" << std::endl; std::sort(std::execution::par_unseq, files.begin(), files.end() , [](auto const& a, auto const& b) { return a.size() > b.size(); } ); for_each_adjacent_range( std::begin(files) , std::end(files) , [](vector_type::value_type const& f) { return f.size(); } , [](auto start, auto end, auto file_size) { size_t nr_of_files = std::distance(start, end); if (nr_of_files > 1) { std::sort(start, end, [](auto& a, auto& b) { auto const& ha = a.get_hash(); auto const& hb = b.get_hash(); auto const& pa = a.path(); auto const& pb = b.path(); return std::tie(ha, pa) < std::tie(hb, pb); }); for_each_adjacent_range( start , end , [](vector_type::value_type& f) { return f.get_hash(); } , [file_size](auto hstart, auto hend, auto hash) { size_t hnr_of_files = std::distance(hstart, hend); if (hnr_of_files > 1) { std::cout << boost::format{ "%1$3d files with hash %3$016x and size %2$d\n" } % hnr_of_files % file_size % hash; std::for_each(hstart, hend, [hash, file_size](auto& e) { std::cout << '\t' << e.path() << '\n'; } ); } } ); } } ); return 0; }
Write the same algorithm in C++ as shown in this Python implementation.
from functools import reduce from itertools import count, islice def sylvester(): def go(n): return 1 + reduce( lambda a, x: a * go(x), range(0, n), 1 ) if 0 != n else 2 return map(go, count(0)) def main(): print("First 10 terms of OEIS A000058:") xs = list(islice(sylvester(), 10)) print('\n'.join([ str(x) for x in xs ])) print("\nSum of the reciprocals of the first 10 terms:") print( reduce(lambda a, x: a + 1 / x, xs, 0) ) if __name__ == '__main__': main()
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> using integer = boost::multiprecision::cpp_int; using rational = boost::rational<integer>; integer sylvester_next(const integer& n) { return n * n - n + 1; } int main() { std::cout << "First 10 elements in Sylvester's sequence:\n"; integer term = 2; rational sum = 0; for (int i = 1; i <= 10; ++i) { std::cout << std::setw(2) << i << ": " << term << '\n'; sum += rational(1, term); term = sylvester_next(term); } std::cout << "Sum of reciprocals: " << sum << '\n'; }
Produce a functionally identical C++ code for the snippet given in Python.
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Please provide an equivalent version of this Python code in C++.
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Write a version of this Python function in C++ with identical behavior.
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Keep all operations the same but rewrite the snippet in C++.
from __future__ import print_function def order_disjoint_list_items(data, items): itemindices = [] for item in set(items): itemcount = items.count(item) lastindex = [-1] for i in range(itemcount): lastindex.append(data.index(item, lastindex[-1] + 1)) itemindices += lastindex[1:] itemindices.sort() for index, item in zip(itemindices, items): data[index] = item if __name__ == '__main__': tostring = ' '.join for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')), (str.split('the cat sat on the mat'), str.split('cat mat')), (list('ABCABCABC'), list('CACA')), (list('ABCABDABE'), list('EADA')), (list('AB'), list('B')), (list('AB'), list('BA')), (list('ABBA'), list('BA')), (list(''), list('')), (list('A'), list('A')), (list('AB'), list('')), (list('ABBA'), list('AB')), (list('ABAB'), list('AB')), (list('ABAB'), list('BABA')), (list('ABCCBA'), list('ACAC')), (list('ABCCBA'), list('CACA')), ]: print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ') order_disjoint_list_items(data, items) print("-> M' %r" % tostring(data))
#include <iostream> #include <vector> #include <algorithm> #include <string> template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; } template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) { std::vector<T*> M_p(std::size(M)); for (auto i = 0; i < std::size(M_p); ++i) { M_p[i] = &M[i]; } for (auto e : N) { auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool { if (c != nullptr) { if (*c == e) return true; } return false; }); if (i != std::end(M_p)) { *i = nullptr; } } for (auto i = 0; i < std::size(N); ++i) { auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool { return c == nullptr; }); if (j != std::end(M_p)) { *j = &M[std::distance(std::begin(M_p), j)]; **j = N[i]; } } return M; } int main() { std::vector<std::vector<std::vector<std::string>>> l = { { { "the", "cat", "sat", "on", "the", "mat" }, { "mat", "cat" } }, { { "the", "cat", "sat", "on", "the", "mat" },{ "cat", "mat" } }, { { "A", "B", "C", "A", "B", "C", "A", "B", "C" },{ "C", "A", "C", "A" } }, { { "A", "B", "C", "A", "B", "D", "A", "B", "E" },{ "E", "A", "D", "A" } }, { { "A", "B" },{ "B" } }, { { "A", "B" },{ "B", "A" } }, { { "A", "B", "B", "A" },{ "B", "A" } } }; for (const auto& e : l) { std::cout << "M: "; print(e[0]); std::cout << ", N: "; print(e[1]); std::cout << ", M': "; auto res = orderDisjointArrayItems<std::string>(e[0], e[1]); print(res); std::cout << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
Convert this Python block to C++, preserving its control flow and logic.
print()
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either opening or closing parentheses, a backslash, a tab, a vertical tab, a form feed, or a newline. It ends with a closing parenthesis (')'), the identifer (if you used one), and a double-quote. All characters are okay in a raw string, no escape sequences are necessary or recognized, and all whitespace is preserved. )EOF"; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
print()
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either opening or closing parentheses, a backslash, a tab, a vertical tab, a form feed, or a newline. It ends with a closing parenthesis (')'), the identifer (if you used one), and a double-quote. All characters are okay in a raw string, no escape sequences are necessary or recognized, and all whitespace is preserved. )EOF"; }
Transform the following Python implementation into C++, maintaining the same output and logic.
print()
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either opening or closing parentheses, a backslash, a tab, a vertical tab, a form feed, or a newline. It ends with a closing parenthesis (')'), the identifer (if you used one), and a double-quote. All characters are okay in a raw string, no escape sequences are necessary or recognized, and all whitespace is preserved. )EOF"; }
Convert this Python block to C++, preserving its control flow and logic.
print()
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either opening or closing parentheses, a backslash, a tab, a vertical tab, a form feed, or a newline. It ends with a closing parenthesis (')'), the identifer (if you used one), and a double-quote. All characters are okay in a raw string, no escape sequences are necessary or recognized, and all whitespace is preserved. )EOF"; }
Generate an equivalent C++ version of this Python code.
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")] table2 = [("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] for row in hashJoin(table1, 1, table2, 0): print(row)
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"} , {"Alan", "Zombies"} , {"Glory", "Buffy"} }; std::ostream& operator<<(std::ostream& o, const tab_t& t) { for(size_t i = 0; i < t.size(); ++i) { o << i << ":"; for(const auto& e : t[i]) o << '\t' << e; o << std::endl; } return o; } tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) { std::unordered_multimap<std::string, size_t> hashmap; for(size_t i = 0; i < a.size(); ++i) { hashmap.insert(std::make_pair(a[i][columna], i)); } tab_t result; for(size_t i = 0; i < b.size(); ++i) { auto range = hashmap.equal_range(b[i][columnb]); for(auto it = range.first; it != range.second; ++it) { tab_t::value_type row; row.insert(row.end() , a[it->second].begin() , a[it->second].end()); row.insert(row.end() , b[i].begin() , b[i].end()); result.push_back(std::move(row)); } } return result; } int main(int argc, char const *argv[]) { using namespace std; int ret = 0; cout << "Table A: " << endl << tab1 << endl; cout << "Table B: " << endl << tab2 << endl; auto tab3 = Join(tab1, 1, tab2, 0); cout << "Joined tables: " << endl << tab3 << endl; return ret; }
Produce a language-to-language conversion: from Python to C++, same semantics.
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")] table2 = [("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] for row in hashJoin(table1, 1, table2, 0): print(row)
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"} , {"Alan", "Zombies"} , {"Glory", "Buffy"} }; std::ostream& operator<<(std::ostream& o, const tab_t& t) { for(size_t i = 0; i < t.size(); ++i) { o << i << ":"; for(const auto& e : t[i]) o << '\t' << e; o << std::endl; } return o; } tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) { std::unordered_multimap<std::string, size_t> hashmap; for(size_t i = 0; i < a.size(); ++i) { hashmap.insert(std::make_pair(a[i][columna], i)); } tab_t result; for(size_t i = 0; i < b.size(); ++i) { auto range = hashmap.equal_range(b[i][columnb]); for(auto it = range.first; it != range.second; ++it) { tab_t::value_type row; row.insert(row.end() , a[it->second].begin() , a[it->second].end()); row.insert(row.end() , b[i].begin() , b[i].end()); result.push_back(std::move(row)); } } return result; } int main(int argc, char const *argv[]) { using namespace std; int ret = 0; cout << "Table A: " << endl << tab1 << endl; cout << "Table B: " << endl << tab2 << endl; auto tab3 = Join(tab1, 1, tab2, 0); cout << "Joined tables: " << endl << tab3 << endl; return ret; }
Produce a language-to-language conversion: from Python to C++, same semantics.
from math import gcd from sympy import factorint def is_Achilles(n): p = factorint(n).values() return all(i > 1 for i in p) and gcd(*p) == 1 def is_strong_Achilles(n): return is_Achilles(n) and is_Achilles(totient(n)) def test_strong_Achilles(nachilles, nstrongachilles): print('First', nachilles, 'Achilles numbers:') n, found = 0, 0 while found < nachilles: if is_Achilles(n): found += 1 print(f'{n: 8,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nFirst', nstrongachilles, 'strong Achilles numbers:') n, found = 0, 0 while found < nstrongachilles: if is_strong_Achilles(n): found += 1 print(f'{n: 9,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nCount of Achilles numbers for various intervals:') intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]] for interval in intervals: print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval))) test_strong_Achilles(50, 100)
#include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::uint128_t; template <typename T> void unique_sort(std::vector<T>& vector) { std::sort(vector.begin(), vector.end()); vector.erase(std::unique(vector.begin(), vector.end()), vector.end()); } auto perfect_powers(uint128_t n) { std::vector<uint128_t> result; for (uint128_t i = 2, s = sqrt(n); i <= s; ++i) for (uint128_t p = i * i; p < n; p *= i) result.push_back(p); unique_sort(result); return result; } auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) { std::vector<uint128_t> result; auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4))); auto s = sqrt(to / 8); for (uint128_t b = 2; b <= c; ++b) { uint128_t b3 = b * b * b; for (uint128_t a = 2; a <= s; ++a) { uint128_t p = b3 * a * a; if (p >= to) break; if (p >= from && !binary_search(pps.begin(), pps.end(), p)) result.push_back(p); } } unique_sort(result); return result; } uint128_t totient(uint128_t n) { uint128_t tot = n; if ((n & 1) == 0) { while ((n & 1) == 0) n >>= 1; tot -= tot >> 1; } for (uint128_t p = 3; p * p <= n; p += 2) { if (n % p == 0) { while (n % p == 0) n /= p; tot -= tot / p; } } if (n > 1) tot -= tot / n; return tot; } int main() { auto start = std::chrono::high_resolution_clock::now(); const uint128_t limit = 1000000000000000; auto pps = perfect_powers(limit); auto ach = achilles(1, 1000000, pps); std::cout << "First 50 Achilles numbers:\n"; for (size_t i = 0; i < 50 && i < ach.size(); ++i) std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' '); std::cout << "\nFirst 50 strong Achilles numbers:\n"; for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i) if (binary_search(ach.begin(), ach.end(), totient(ach[i]))) std::cout << std::setw(6) << ach[i] << (++count % 10 == 0 ? '\n' : ' '); int digits = 2; std::cout << "\nNumber of Achilles numbers with:\n"; for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) { size_t count = achilles(from, to, pps).size(); std::cout << std::setw(2) << digits << " digits: " << count << '\n'; from = to; } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Translate this program into C++ but keep the logic exactly as in Python.
from math import gcd from sympy import factorint def is_Achilles(n): p = factorint(n).values() return all(i > 1 for i in p) and gcd(*p) == 1 def is_strong_Achilles(n): return is_Achilles(n) and is_Achilles(totient(n)) def test_strong_Achilles(nachilles, nstrongachilles): print('First', nachilles, 'Achilles numbers:') n, found = 0, 0 while found < nachilles: if is_Achilles(n): found += 1 print(f'{n: 8,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nFirst', nstrongachilles, 'strong Achilles numbers:') n, found = 0, 0 while found < nstrongachilles: if is_strong_Achilles(n): found += 1 print(f'{n: 9,}', end='\n' if found % 10 == 0 else '') n += 1 print('\nCount of Achilles numbers for various intervals:') intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]] for interval in intervals: print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval))) test_strong_Achilles(50, 100)
#include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::uint128_t; template <typename T> void unique_sort(std::vector<T>& vector) { std::sort(vector.begin(), vector.end()); vector.erase(std::unique(vector.begin(), vector.end()), vector.end()); } auto perfect_powers(uint128_t n) { std::vector<uint128_t> result; for (uint128_t i = 2, s = sqrt(n); i <= s; ++i) for (uint128_t p = i * i; p < n; p *= i) result.push_back(p); unique_sort(result); return result; } auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) { std::vector<uint128_t> result; auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4))); auto s = sqrt(to / 8); for (uint128_t b = 2; b <= c; ++b) { uint128_t b3 = b * b * b; for (uint128_t a = 2; a <= s; ++a) { uint128_t p = b3 * a * a; if (p >= to) break; if (p >= from && !binary_search(pps.begin(), pps.end(), p)) result.push_back(p); } } unique_sort(result); return result; } uint128_t totient(uint128_t n) { uint128_t tot = n; if ((n & 1) == 0) { while ((n & 1) == 0) n >>= 1; tot -= tot >> 1; } for (uint128_t p = 3; p * p <= n; p += 2) { if (n % p == 0) { while (n % p == 0) n /= p; tot -= tot / p; } } if (n > 1) tot -= tot / n; return tot; } int main() { auto start = std::chrono::high_resolution_clock::now(); const uint128_t limit = 1000000000000000; auto pps = perfect_powers(limit); auto ach = achilles(1, 1000000, pps); std::cout << "First 50 Achilles numbers:\n"; for (size_t i = 0; i < 50 && i < ach.size(); ++i) std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' '); std::cout << "\nFirst 50 strong Achilles numbers:\n"; for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i) if (binary_search(ach.begin(), ach.end(), totient(ach[i]))) std::cout << std::setw(6) << ach[i] << (++count % 10 == 0 ? '\n' : ' '); int digits = 2; std::cout << "\nNumber of Achilles numbers with:\n"; for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) { size_t count = achilles(from, to, pps).size(); std::cout << std::setw(2) << digits << " digits: " << count << '\n'; from = to; } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Transform the following Python implementation into C++, maintaining the same output and logic.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): continue print(p*q, end = " ");
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; } int main() { const int n = 1000; std::cout << "Odd square-free semiprimes < " << n << ":\n"; int count = 0; for (int i = 1; i < n; i += 2) { if (odd_square_free_semiprime(i)) { ++count; std::cout << std::setw(4) << i; if (count % 20 == 0) std::cout << '\n'; } } std::cout << "\nCount: " << count << '\n'; return 0; }
Keep all operations the same but rewrite the snippet in C++.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): continue print(p*q, end = " ");
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; } int main() { const int n = 1000; std::cout << "Odd square-free semiprimes < " << n << ":\n"; int count = 0; for (int i = 1; i < n; i += 2) { if (odd_square_free_semiprime(i)) { ++count; std::cout << std::setw(4) << i; if (count % 20 == 0) std::cout << '\n'; } } std::cout << "\nCount: " << count << '\n'; return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void sierpinski_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length/std::sqrt(2.0); y_ = 2 * x_; angle_ = 45; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "F--XF--F--XF"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string sierpinski_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { if (c == 'X') t += "XF+G+XF--F--XF+G+X"; else t += c; } return t; } void sierpinski_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ -= length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void sierpinski_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': case 'G': line(out); break; case '+': angle_ = (angle_ + 45) % 360; break; case '-': angle_ = (angle_ - 45) % 360; break; } } } int main() { std::ofstream out("sierpinski_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } sierpinski_curve s; s.write(out, 545, 7, 5); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb as hsv def curve(axiom, rules, angle, depth): for _ in range(depth): axiom = ''.join(rules[c] if c in rules else c for c in axiom) a, x, y = 0, [0], [0] for c in axiom: match c: case '+': a += 1 case '-': a -= 1 case 'F' | 'G': x.append(x[-1] + np.cos(a*angle*np.pi/180)) y.append(y[-1] + np.sin(a*angle*np.pi/180)) l = len(x) for i in range(l - 1): plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7])) plt.gca().set_aspect(1) plt.show() curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void sierpinski_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length/std::sqrt(2.0); y_ = 2 * x_; angle_ = 45; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "F--XF--F--XF"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string sierpinski_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { if (c == 'X') t += "XF+G+XF--F--XF+G+X"; else t += c; } return t; } void sierpinski_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ -= length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void sierpinski_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': case 'G': line(out); break; case '+': angle_ = (angle_ + 45) % 360; break; case '-': angle_ = (angle_ - 45) % 360; break; } } } int main() { std::ofstream out("sierpinski_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } sierpinski_curve s; s.write(out, 545, 7, 5); return 0; }
Convert this Python snippet to C++ and keep its semantics consistent.
import collections def MostFreqKHashing(inputString, K): occuDict = collections.defaultdict(int) for c in inputString: occuDict[c] += 1 occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True) outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K]) return outputStr def MostFreqKSimilarity(inputStr1, inputStr2): similarity = 0 for i in range(0, len(inputStr1), 2): c = inputStr1[i] cnt1 = int(inputStr1[i + 1]) for j in range(0, len(inputStr2), 2): if inputStr2[j] == c: cnt2 = int(inputStr2[j + 1]) similarity += cnt1 + cnt2 break return similarity def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance): return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
#include <string> #include <vector> #include <map> #include <iostream> #include <algorithm> #include <utility> #include <sstream> std::string mostFreqKHashing ( const std::string & input , int k ) { std::ostringstream oss ; std::map<char, int> frequencies ; for ( char c : input ) { frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ; } std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ; std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a , std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; } else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ; for ( int i = 0 ; i < letters.size( ) ; i++ ) { oss << std::get<0>( letters[ i ] ) ; oss << std::get<1>( letters[ i ] ) ; } std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ; if ( letters.size( ) >= k ) { return output ; } else { return output.append( "NULL0" ) ; } } int mostFreqKSimilarity ( const std::string & first , const std::string & second ) { int i = 0 ; while ( i < first.length( ) - 1 ) { auto found = second.find_first_of( first.substr( i , 2 ) ) ; if ( found != std::string::npos ) return std::stoi ( first.substr( i , 2 )) ; else i += 2 ; } return 0 ; } int mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) { return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ; } int main( ) { std::string s1("LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" ) ; std::string s2( "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" ) ; std::cout << "MostFreqKHashing( s1 , 2 ) = " << mostFreqKHashing( s1 , 2 ) << '\n' ; std::cout << "MostFreqKHashing( s2 , 2 ) = " << mostFreqKHashing( s2 , 2 ) << '\n' ; return 0 ; }
Translate this program into C++ but keep the logic exactly as in Python.
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) )) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit palindrome_generator(unsigned int base) : base_(base), upper_(base) {} unsigned int next_palindrome(); private: unsigned int base_; unsigned int lower_ = 1; unsigned int upper_; unsigned int next_ = 0; bool even_ = false; }; unsigned int palindrome_generator::next_palindrome() { ++next_; if (next_ == upper_) { if (even_) { lower_ = upper_; upper_ *= base_; } next_ = lower_; even_ = !even_; } return even_ ? next_ * upper_ + reverse(base_, next_) : next_ * lower_ + reverse(base_, next_ / base_); } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } std::string to_string(unsigned int base, unsigned int n) { assert(base <= 36); static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::string str; for (; n != 0; n /= base) str += digits[n % base]; std::reverse(str.begin(), str.end()); return str; } void print_palindromic_primes(unsigned int base, unsigned int limit) { auto width = static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base))); unsigned int count = 0; auto columns = 80 / (width + 1); std::cout << "Base " << base << " palindromic primes less than " << limit << ":\n"; palindrome_generator pgen(base); unsigned int palindrome; while ((palindrome = pgen.next_palindrome()) < limit) { if (is_prime(palindrome)) { ++count; std::cout << std::setw(width) << to_string(base, palindrome) << (count % columns == 0 ? '\n' : ' '); } } if (count % columns != 0) std::cout << '\n'; std::cout << "Count: " << count << '\n'; } void count_palindromic_primes(unsigned int base, unsigned int limit) { unsigned int count = 0; palindrome_generator pgen(base); unsigned int palindrome; while ((palindrome = pgen.next_palindrome()) < limit) if (is_prime(palindrome)) ++count; std::cout << "Number of base " << base << " palindromic primes less than " << limit << ": " << count << '\n'; } int main() { print_palindromic_primes(10, 1000); std::cout << '\n'; print_palindromic_primes(10, 100000); std::cout << '\n'; count_palindromic_primes(10, 1000000000); std::cout << '\n'; print_palindromic_primes(16, 500); }
Transform the following Python implementation into C++, maintaining the same output and logic.
from itertools import takewhile def palindromicPrimes(): def p(n): s = str(n) return s == s[::-1] return (n for n in primes() if p(n)) def main(): print('\n'.join( str(x) for x in takewhile( lambda n: 1000 > n, palindromicPrimes() ) )) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit palindrome_generator(unsigned int base) : base_(base), upper_(base) {} unsigned int next_palindrome(); private: unsigned int base_; unsigned int lower_ = 1; unsigned int upper_; unsigned int next_ = 0; bool even_ = false; }; unsigned int palindrome_generator::next_palindrome() { ++next_; if (next_ == upper_) { if (even_) { lower_ = upper_; upper_ *= base_; } next_ = lower_; even_ = !even_; } return even_ ? next_ * upper_ + reverse(base_, next_) : next_ * lower_ + reverse(base_, next_ / base_); } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } std::string to_string(unsigned int base, unsigned int n) { assert(base <= 36); static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::string str; for (; n != 0; n /= base) str += digits[n % base]; std::reverse(str.begin(), str.end()); return str; } void print_palindromic_primes(unsigned int base, unsigned int limit) { auto width = static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base))); unsigned int count = 0; auto columns = 80 / (width + 1); std::cout << "Base " << base << " palindromic primes less than " << limit << ":\n"; palindrome_generator pgen(base); unsigned int palindrome; while ((palindrome = pgen.next_palindrome()) < limit) { if (is_prime(palindrome)) { ++count; std::cout << std::setw(width) << to_string(base, palindrome) << (count % columns == 0 ? '\n' : ' '); } } if (count % columns != 0) std::cout << '\n'; std::cout << "Count: " << count << '\n'; } void count_palindromic_primes(unsigned int base, unsigned int limit) { unsigned int count = 0; palindrome_generator pgen(base); unsigned int palindrome; while ((palindrome = pgen.next_palindrome()) < limit) if (is_prime(palindrome)) ++count; std::cout << "Number of base " << base << " palindromic primes less than " << limit << ": " << count << '\n'; } int main() { print_palindromic_primes(10, 1000); std::cout << '\n'; print_palindromic_primes(10, 100000); std::cout << '\n'; count_palindromic_primes(10, 1000000000); std::cout << '\n'; print_palindromic_primes(16, 500); }
Preserve the algorithm and functionality while converting the code from Python to C++.
import urllib.request from collections import Counter 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)>10: frequency = Counter(word.lower()) if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1: print(word)
#include <bitset> #include <cctype> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> bool contains_all_vowels_once(const std::string& word) { std::bitset<5> vowels; for (char ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); size_t bit = 0; switch (ch) { case 'a': bit = 0; break; case 'e': bit = 1; break; case 'i': bit = 2; break; case 'o': bit = 3; break; case 'u': bit = 4; break; default: continue; } if (vowels.test(bit)) return false; vowels.set(bit); } return vowels.all(); } 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)) { if (word.size() > 10 && contains_all_vowels_once(word)) std::cout << std::setw(2) << ++n << ": " << word << '\n'; } return EXIT_SUCCESS; }
Generate a C++ translation of this Python snippet without changing its computational steps.
from numpy import Inf class MaxTropical: def __init__(self, x=0): self.x = x def __str__(self): return str(self.x) def __add__(self, other): return MaxTropical(max(self.x, other.x)) def __mul__(self, other): return MaxTropical(self.x + other.x) def __pow__(self, other): assert other.x // 1 == other.x and other.x > 0, "Invalid Operation" return MaxTropical(self.x * other.x) def __eq__(self, other): return self.x == other.x if __name__ == "__main__": a = MaxTropical(-2) b = MaxTropical(-1) c = MaxTropical(-0.5) d = MaxTropical(-0.001) e = MaxTropical(0) f = MaxTropical(0.5) g = MaxTropical(1) h = MaxTropical(1.5) i = MaxTropical(2) j = MaxTropical(5) k = MaxTropical(7) l = MaxTropical(8) m = MaxTropical(-Inf) print("2 * -2 == ", i * a) print("-0.001 + -Inf == ", d + m) print("0 * -Inf == ", e * m) print("1.5 + -1 == ", h + b) print("-0.5 * 0 == ", c * e) print("5**7 == ", j**k) print("5 * (8 + 7)) == ", j * (l + k)) print("5 * 8 + 5 * 7 == ", j * l + j * k) print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
#include <iostream> #include <optional> using namespace std; class TropicalAlgebra { optional<double> m_value; public: friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&); friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept; TropicalAlgebra() = default; explicit TropicalAlgebra(double value) noexcept : m_value{value} {} TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept { if(!m_value) { *this = rhs; } else if (!rhs.m_value) { } else { *m_value = max(*rhs.m_value, *m_value); } return *this; } TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept { if(!m_value) { } else if (!rhs.m_value) { *this = rhs; } else { *m_value += *rhs.m_value; } return *this; } }; inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept { lhs += rhs; return lhs; } inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept { lhs *= rhs; return lhs; } inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept { auto result = base; for(unsigned int i = 1; i < exponent; i++) { result *= base; } return result; } ostream& operator<<(ostream& os, const TropicalAlgebra& pt) { if(!pt.m_value) cout << "-Inf\n"; else cout << *pt.m_value << "\n"; return os; } int main(void) { const TropicalAlgebra a(-2); const TropicalAlgebra b(-1); const TropicalAlgebra c(-0.5); const TropicalAlgebra d(-0.001); const TropicalAlgebra e(0); const TropicalAlgebra h(1.5); const TropicalAlgebra i(2); const TropicalAlgebra j(5); const TropicalAlgebra k(7); const TropicalAlgebra l(8); const TropicalAlgebra m; cout << "2 * -2 == " << i * a; cout << "-0.001 + -Inf == " << d + m; cout << "0 * -Inf == " << e * m; cout << "1.5 + -1 == " << h + b; cout << "-0.5 * 0 == " << c * e; cout << "pow(5, 7) == " << pow(j, 7); cout << "5 * (8 + 7)) == " << j * (l + k); cout << "5 * 8 + 5 * 7 == " << j * l + j * k; }
Write the same algorithm in C++ as shown in this Python implementation.
from numpy import Inf class MaxTropical: def __init__(self, x=0): self.x = x def __str__(self): return str(self.x) def __add__(self, other): return MaxTropical(max(self.x, other.x)) def __mul__(self, other): return MaxTropical(self.x + other.x) def __pow__(self, other): assert other.x // 1 == other.x and other.x > 0, "Invalid Operation" return MaxTropical(self.x * other.x) def __eq__(self, other): return self.x == other.x if __name__ == "__main__": a = MaxTropical(-2) b = MaxTropical(-1) c = MaxTropical(-0.5) d = MaxTropical(-0.001) e = MaxTropical(0) f = MaxTropical(0.5) g = MaxTropical(1) h = MaxTropical(1.5) i = MaxTropical(2) j = MaxTropical(5) k = MaxTropical(7) l = MaxTropical(8) m = MaxTropical(-Inf) print("2 * -2 == ", i * a) print("-0.001 + -Inf == ", d + m) print("0 * -Inf == ", e * m) print("1.5 + -1 == ", h + b) print("-0.5 * 0 == ", c * e) print("5**7 == ", j**k) print("5 * (8 + 7)) == ", j * (l + k)) print("5 * 8 + 5 * 7 == ", j * l + j * k) print("5 * (8 + 7) == 5 * 8 + 5 * 7", j * (l + k) == j * l + j * k)
#include <iostream> #include <optional> using namespace std; class TropicalAlgebra { optional<double> m_value; public: friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&); friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept; TropicalAlgebra() = default; explicit TropicalAlgebra(double value) noexcept : m_value{value} {} TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept { if(!m_value) { *this = rhs; } else if (!rhs.m_value) { } else { *m_value = max(*rhs.m_value, *m_value); } return *this; } TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept { if(!m_value) { } else if (!rhs.m_value) { *this = rhs; } else { *m_value += *rhs.m_value; } return *this; } }; inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept { lhs += rhs; return lhs; } inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept { lhs *= rhs; return lhs; } inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept { auto result = base; for(unsigned int i = 1; i < exponent; i++) { result *= base; } return result; } ostream& operator<<(ostream& os, const TropicalAlgebra& pt) { if(!pt.m_value) cout << "-Inf\n"; else cout << *pt.m_value << "\n"; return os; } int main(void) { const TropicalAlgebra a(-2); const TropicalAlgebra b(-1); const TropicalAlgebra c(-0.5); const TropicalAlgebra d(-0.001); const TropicalAlgebra e(0); const TropicalAlgebra h(1.5); const TropicalAlgebra i(2); const TropicalAlgebra j(5); const TropicalAlgebra k(7); const TropicalAlgebra l(8); const TropicalAlgebra m; cout << "2 * -2 == " << i * a; cout << "-0.001 + -Inf == " << d + m; cout << "0 * -Inf == " << e * m; cout << "1.5 + -1 == " << h + b; cout << "-0.5 * 0 == " << c * e; cout << "pow(5, 7) == " << pow(j, 7); cout << "5 * (8 + 7)) == " << j * (l + k); cout << "5 * 8 + 5 * 7 == " << j * l + j * k; }
Translate the given Python code snippet into C++ without altering its behavior.
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
#include <windows.h> #include <iostream> #include <string> using namespace std; const int PLAYERS = 4, MAX_POINTS = 100; enum Moves { ROLL, HOLD }; class player { public: player() { current_score = round_score = 0; } void addCurrScore() { current_score += round_score; } int getCurrScore() { return current_score; } int getRoundScore() { return round_score; } void addRoundScore( int rs ) { round_score += rs; } void zeroRoundScore() { round_score = 0; } virtual int getMove() = 0; virtual ~player() {} protected: int current_score, round_score; }; class RAND_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; if( rand() % 10 < 5 ) return ROLL; if( round_score > 0 ) return HOLD; return ROLL; } }; class Q2WIN_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; int q = MAX_POINTS - current_score; if( q < 6 ) return ROLL; q /= 4; if( round_score < q ) return ROLL; return HOLD; } }; class AL20_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; if( round_score < 20 ) return ROLL; return HOLD; } }; class AL20T_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; int d = ( 100 * round_score ) / 20; if( round_score < 20 && d < rand() % 100 ) return ROLL; return HOLD; } }; class Auto_pigGame { public: Auto_pigGame() { _players[0] = new RAND_Player(); _players[1] = new Q2WIN_Player(); _players[2] = new AL20_Player(); _players[3] = new AL20T_Player(); } ~Auto_pigGame() { delete _players[0]; delete _players[1]; delete _players[2]; delete _players[3]; } void play() { int die, p = 0; bool endGame = false; while( !endGame ) { switch( _players[p]->getMove() ) { case ROLL: die = rand() % 6 + 1; if( die == 1 ) { cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl; nextTurn( p ); continue; } _players[p]->addRoundScore( die ); cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl; break; case HOLD: _players[p]->addCurrScore(); cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl; if( _players[p]->getCurrScore() >= MAX_POINTS ) endGame = true; else nextTurn( p ); } } showScore(); } private: void nextTurn( int& p ) { _players[p]->zeroRoundScore(); ++p %= PLAYERS; } void showScore() { cout << endl; cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl; cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl; cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl; cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl; system( "pause" ); } player* _players[PLAYERS]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); Auto_pigGame pg; pg.play(); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter playercount = 2 maxscore = 100 maxgames = 100000 Game = namedtuple('Game', 'players, maxscore, rounds') Round = namedtuple('Round', 'who, start, scores, safe') class Player(): def __init__(self, player_index): self.player_index = player_index def __repr__(self): return '%s(%i)' % (self.__class__.__name__, self.player_index) def __call__(self, safescore, scores, game): 'Returns boolean True to roll again' pass class RandPlay(Player): def __call__(self, safe, scores, game): 'Returns random boolean choice of whether to roll again' return bool(random.randint(0, 1)) class RollTo20(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20' return (((sum(scores) + safe[self.player_index]) < maxscore) and(sum(scores) < 20)) class Desparat(Player): def __call__(self, safe, scores, game): 'Roll again if this rounds score < 20 or someone is within 20 of winning' return (((sum(scores) + safe[self.player_index]) < maxscore) and( (sum(scores) < 20) or max(safe) >= (maxscore - 20))) def game__str__(self): 'Pretty printer for Game class' return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])" % (self.players, self.maxscore, ',\n '.join(repr(round) for round in self.rounds))) Game.__str__ = game__str__ def winningorder(players, safescores): 'Return (players in winning order, their scores)' return tuple(zip(*sorted(zip(players, safescores), key=lambda x: x[1], reverse=True))) def playpig(game): players, maxscore, rounds = game playercount = len(players) safescore = [0] * playercount player = 0 scores=[] while max(safescore) < maxscore: startscore = safescore[player] rolling = players[player](safescore, scores, game) if rolling: rolled = randint(1, 6) scores.append(rolled) if rolled == 1: round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) scores, player = [], (player + 1) % playercount else: safescore[player] += sum(scores) round = Round(who=players[player], start=startscore, scores=scores, safe=safescore[player]) rounds.append(round) if safescore[player] >= maxscore: break scores, player = [], (player + 1) % playercount return winningorder(players, safescore) if __name__ == '__main__': game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=20, rounds=[]) print('ONE GAME') print('Winning order: %r; Respective scores: %r\n' % playpig(game)) print(game) game = Game(players=tuple(RandPlay(i) for i in range(playercount)), maxscore=maxscore, rounds=[]) algos = (RollTo20, RandPlay, Desparat) print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES' % (', '.join(p.__name__ for p in algos), maxgames,)) winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i) for i in range(playercount)), rounds=[]))[0]) for i in range(maxgames)) print(' Players(position) winning on left; occurrences on right:\n %s' % ',\n '.join(str(w) for w in winners.most_common()))
#include <windows.h> #include <iostream> #include <string> using namespace std; const int PLAYERS = 4, MAX_POINTS = 100; enum Moves { ROLL, HOLD }; class player { public: player() { current_score = round_score = 0; } void addCurrScore() { current_score += round_score; } int getCurrScore() { return current_score; } int getRoundScore() { return round_score; } void addRoundScore( int rs ) { round_score += rs; } void zeroRoundScore() { round_score = 0; } virtual int getMove() = 0; virtual ~player() {} protected: int current_score, round_score; }; class RAND_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; if( rand() % 10 < 5 ) return ROLL; if( round_score > 0 ) return HOLD; return ROLL; } }; class Q2WIN_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; int q = MAX_POINTS - current_score; if( q < 6 ) return ROLL; q /= 4; if( round_score < q ) return ROLL; return HOLD; } }; class AL20_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; if( round_score < 20 ) return ROLL; return HOLD; } }; class AL20T_Player : public player { virtual int getMove() { if( round_score + current_score >= MAX_POINTS ) return HOLD; int d = ( 100 * round_score ) / 20; if( round_score < 20 && d < rand() % 100 ) return ROLL; return HOLD; } }; class Auto_pigGame { public: Auto_pigGame() { _players[0] = new RAND_Player(); _players[1] = new Q2WIN_Player(); _players[2] = new AL20_Player(); _players[3] = new AL20T_Player(); } ~Auto_pigGame() { delete _players[0]; delete _players[1]; delete _players[2]; delete _players[3]; } void play() { int die, p = 0; bool endGame = false; while( !endGame ) { switch( _players[p]->getMove() ) { case ROLL: die = rand() % 6 + 1; if( die == 1 ) { cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl; nextTurn( p ); continue; } _players[p]->addRoundScore( die ); cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl; break; case HOLD: _players[p]->addCurrScore(); cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl; if( _players[p]->getCurrScore() >= MAX_POINTS ) endGame = true; else nextTurn( p ); } } showScore(); } private: void nextTurn( int& p ) { _players[p]->zeroRoundScore(); ++p %= PLAYERS; } void showScore() { cout << endl; cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl; cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl; cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl; cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl; system( "pause" ); } player* _players[PLAYERS]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); Auto_pigGame pg; pg.play(); return 0; }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()) return; auto i = vec.begin(); std::cout << *i++; for (; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } int main() { std::map<integer, std::pair<bool, integer>> cache; std::vector<integer> seeds, related, palindromes; for (integer n = 1; n <= 10000; ++n) { std::pair<bool, integer> p(true, n); std::vector<integer> seen; integer rev = reverse(n); integer sum = n; for (int i = 0; i < 500; ++i) { sum += rev; rev = reverse(sum); if (rev == sum) { p.first = false; p.second = 0; break; } auto iter = cache.find(sum); if (iter != cache.end()) { p = iter->second; break; } seen.push_back(sum); } for (integer s : seen) cache.emplace(s, p); if (!p.first) continue; if (p.second == n) seeds.push_back(n); else related.push_back(n); if (n == reverse(n)) palindromes.push_back(n); } std::cout << "number of seeds: " << seeds.size() << '\n'; std::cout << "seeds: "; print_vector(seeds); std::cout << "number of related: " << related.size() << '\n'; std::cout << "palindromes: "; print_vector(palindromes); return 0; }
Translate the given Python code snippet into C++ without altering its behavior.
from __future__ import print_function def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums def reverse_int(num): return int(str(num)[::-1]) def split_roots_from_relateds(roots_and_relateds): roots = roots_and_relateds[::] i = 1 while i < len(roots): this = roots[i] if any(this.intersection(prev) for prev in roots[:i]): del roots[i] else: i += 1 root = [min(each_set) for each_set in roots] related = [min(each_set) for each_set in roots_and_relateds] related = [n for n in related if n not in root] return root, related def find_lychrel(maxn, max_reversions): 'Lychrel number generator' series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)] roots_and_relateds = [s for s in series if len(s) > max_reversions] return split_roots_from_relateds(roots_and_relateds) if __name__ == '__main__': maxn, reversion_limit = 10000, 500 print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds" % (maxn, reversion_limit)) lychrel, l_related = find_lychrel(maxn, reversion_limit) print(' Number of Lychrel numbers:', len(lychrel)) print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel)) print(' Number of Lychrel related:', len(l_related)) pals = [x for x in lychrel + l_related if x == reverse_int(x)] print(' Number of Lychrel palindromes:', len(pals)) print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()) return; auto i = vec.begin(); std::cout << *i++; for (; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } int main() { std::map<integer, std::pair<bool, integer>> cache; std::vector<integer> seeds, related, palindromes; for (integer n = 1; n <= 10000; ++n) { std::pair<bool, integer> p(true, n); std::vector<integer> seen; integer rev = reverse(n); integer sum = n; for (int i = 0; i < 500; ++i) { sum += rev; rev = reverse(sum); if (rev == sum) { p.first = false; p.second = 0; break; } auto iter = cache.find(sum); if (iter != cache.end()) { p = iter->second; break; } seen.push_back(sum); } for (integer s : seen) cache.emplace(s, p); if (!p.first) continue; if (p.second == n) seeds.push_back(n); else related.push_back(n); if (n == reverse(n)) palindromes.push_back(n); } std::cout << "number of seeds: " << seeds.size() << '\n'; std::cout << "seeds: "; print_vector(seeds); std::cout << "number of related: " << related.size() << '\n'; std::cout << "palindromes: "; print_vector(palindromes); return 0; }
Convert the following code from Python to C++, ensuring the logic remains intact.
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
#include <iomanip> #include <iostream> bool nondecimal(unsigned int n) { for (; n > 0; n >>= 4) { if ((n & 0xF) > 9) return true; } return false; } int main() { unsigned int count = 0; for (unsigned int n = 0; n < 501; ++n) { if (nondecimal(n)) { ++count; std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' '); } } std::cout << "\n\n" << count << " such numbers found.\n"; }
Port the following code from Python to C++ with equivalent syntax and logic.
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
#include <iomanip> #include <iostream> bool nondecimal(unsigned int n) { for (; n > 0; n >>= 4) { if ((n & 0xF) > 9) return true; } return false; } int main() { unsigned int count = 0; for (unsigned int n = 0; n < 501; ++n) { if (nondecimal(n)) { ++count; std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' '); } } std::cout << "\n\n" << count << " such numbers found.\n"; }
Maintain the same structure and functionality when rewriting this code in C++.
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
#include <iomanip> #include <iostream> bool nondecimal(unsigned int n) { for (; n > 0; n >>= 4) { if ((n & 0xF) > 9) return true; } return false; } int main() { unsigned int count = 0; for (unsigned int n = 0; n < 501; ++n) { if (nondecimal(n)) { ++count; std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' '); } } std::cout << "\n\n" << count << " such numbers found.\n"; }
Generate a C++ translation of this Python snippet without changing its computational steps.
class Sequence(): def __init__(self, sequence_string): self.ranges = self.to_ranges(sequence_string) assert self.ranges == sorted(self.ranges), "Sequence order error" def to_ranges(self, txt): return [[int(x) for x in r.strip().split('-')] for r in txt.strip().split(',') if r] def remove(self, rem): ranges = self.ranges for i, r in enumerate(ranges): if r[0] <= rem <= r[1]: if r[0] == rem: if r[1] > rem: r[0] += 1 else: del ranges[i] elif r[1] == rem: if r[0] < rem: r[1] -= 1 else: del ranges[i] else: r[1], splitrange = rem - 1, [rem + 1, r[1]] ranges.insert(i + 1, splitrange) break if r[0] > rem: break return self def add(self, add): ranges = self.ranges for i, r in enumerate(ranges): if r[0] <= add <= r[1]: break elif r[0] - 1 == add: r[0] = add break elif r[1] + 1 == add: r[1] = add break elif r[0] > add: ranges.insert(i, [add, add]) break else: ranges.append([add, add]) return self return self.consolidate() def consolidate(self): "Combine overlapping ranges" ranges = self.ranges for this, that in zip(ranges, ranges[1:]): if this[1] + 1 >= that[0]: if this[1] >= that[1]: this[:], that[:] = [], this else: this[:], that[:] = [], [this[0], that[1]] ranges[:] = [r for r in ranges if r] return self def __repr__(self): rr = self.ranges return ",".join(f"{r[0]}-{r[1]}" for r in rr) def demo(opp_txt): by_line = opp_txt.strip().split('\n') start = by_line.pop(0) ex = Sequence(start.strip().split()[-1][1:-1]) lines = [line.strip().split() for line in by_line] opps = [((ex.add if word[0] == "add" else ex.remove), int(word[1])) for word in lines] print(f"Start: \"{ex}\"") for op, val in opps: print(f" {op.__name__:>6} {val:2} => {op(val)}") print() if __name__ == '__main__': demo() demo() demo()
#include <algorithm> #include <iomanip> #include <iostream> #include <list> struct range { range(int lo, int hi) : low(lo), high(hi) {} int low; int high; }; std::ostream& operator<<(std::ostream& out, const range& r) { return out << r.low << '-' << r.high; } class ranges { public: ranges() {} explicit ranges(std::initializer_list<range> init) : ranges_(init) {} void add(int n); void remove(int n); bool empty() const { return ranges_.empty(); } private: friend std::ostream& operator<<(std::ostream& out, const ranges& r); std::list<range> ranges_; }; void ranges::add(int n) { for (auto i = ranges_.begin(); i != ranges_.end(); ++i) { if (n + 1 < i->low) { ranges_.emplace(i, n, n); return; } if (n > i->high + 1) continue; if (n + 1 == i->low) i->low = n; else if (n == i->high + 1) i->high = n; else return; if (i != ranges_.begin()) { auto prev = std::prev(i); if (prev->high + 1 == i->low) { i->low = prev->low; ranges_.erase(prev); } } auto next = std::next(i); if (next != ranges_.end() && next->low - 1 == i->high) { i->high = next->high; ranges_.erase(next); } return; } ranges_.emplace_back(n, n); } void ranges::remove(int n) { for (auto i = ranges_.begin(); i != ranges_.end(); ++i) { if (n < i->low) return; if (n == i->low) { if (++i->low > i->high) ranges_.erase(i); return; } if (n == i->high) { if (--i->high < i->low) ranges_.erase(i); return; } if (n > i->low & n < i->high) { int low = i->low; i->low = n + 1; ranges_.emplace(i, low, n - 1); return; } } } std::ostream& operator<<(std::ostream& out, const ranges& r) { if (!r.empty()) { auto i = r.ranges_.begin(); out << *i++; for (; i != r.ranges_.end(); ++i) out << ',' << *i; } return out; } void test_add(ranges& r, int n) { r.add(n); std::cout << " add " << std::setw(2) << n << " => " << r << '\n'; } void test_remove(ranges& r, int n) { r.remove(n); std::cout << " remove " << std::setw(2) << n << " => " << r << '\n'; } void test1() { ranges r; std::cout << "Start: \"" << r << "\"\n"; test_add(r, 77); test_add(r, 79); test_add(r, 78); test_remove(r, 77); test_remove(r, 78); test_remove(r, 79); } void test2() { ranges r{{1,3}, {5,5}}; std::cout << "Start: \"" << r << "\"\n"; test_add(r, 1); test_remove(r, 4); test_add(r, 7); test_add(r, 8); test_add(r, 6); test_remove(r, 7); } void test3() { ranges r{{1,5}, {10,25}, {27,30}}; std::cout << "Start: \"" << r << "\"\n"; test_add(r, 26); test_add(r, 9); test_add(r, 7); test_remove(r, 26); test_remove(r, 9); test_remove(r, 7); } int main() { test1(); std::cout << '\n'; test2(); std::cout << '\n'; test3(); return 0; }
Translate this program into C++ but keep the logic exactly as in Python.
from math import isqrt def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}") return i print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations") print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------") for k in range(20, 40): juggler(k, False) for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]: juggler(k)
#include <cassert> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> using big_int = mpz_class; auto juggler(int n) { assert(n >= 1); int count = 0, max_count = 0; big_int a = n, max = n; while (a != 1) { if (a % 2 == 0) a = sqrt(a); else a = sqrt(big_int(a * a * a)); ++count; if (a > max) { max = a; max_count = count; } } return std::make_tuple(count, max_count, max, max.get_str().size()); } int main() { std::cout.imbue(std::locale("")); std::cout << "n l[n] i[n] h[n]\n"; std::cout << "--------------------------------\n"; for (int n = 20; n < 40; ++n) { auto [count, max_count, max, digits] = juggler(n); std::cout << std::setw(2) << n << " " << std::setw(2) << count << " " << std::setw(2) << max_count << " " << max << '\n'; } std::cout << '\n'; std::cout << " n l[n] i[n] d[n]\n"; std::cout << "----------------------------------------\n"; for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963}) { auto [count, max_count, max, digits] = juggler(n); std::cout << std::setw(11) << n << " " << std::setw(3) << count << " " << std::setw(3) << max_count << " " << digits << '\n'; } }
Change the programming language of this snippet from Python to C++ without modifying what it does.
from math import isqrt def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}") return i print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations") print(" n l(n) i(n) h(n) or d(n)\n-------------------------------------------") for k in range(20, 40): juggler(k, False) for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]: juggler(k)
#include <cassert> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> using big_int = mpz_class; auto juggler(int n) { assert(n >= 1); int count = 0, max_count = 0; big_int a = n, max = n; while (a != 1) { if (a % 2 == 0) a = sqrt(a); else a = sqrt(big_int(a * a * a)); ++count; if (a > max) { max = a; max_count = count; } } return std::make_tuple(count, max_count, max, max.get_str().size()); } int main() { std::cout.imbue(std::locale("")); std::cout << "n l[n] i[n] h[n]\n"; std::cout << "--------------------------------\n"; for (int n = 20; n < 40; ++n) { auto [count, max_count, max, digits] = juggler(n); std::cout << std::setw(2) << n << " " << std::setw(2) << count << " " << std::setw(2) << max_count << " " << max << '\n'; } std::cout << '\n'; std::cout << " n l[n] i[n] d[n]\n"; std::cout << "----------------------------------------\n"; for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963}) { auto [count, max_count, max, digits] = juggler(n); std::cout << std::setw(11) << n << " " << std::setw(3) << count << " " << std::setw(3) << max_count << " " << digits << '\n'; } }
Transform the following Python implementation into C++, maintaining the same output and logic.
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = "" for c in axiom: if c in rules: a2 += rules[c] else: a2 += c axiom = a2 return axiom def draw_lsystem(axiom, rules, angle, iterations): xp = [1] yp = [1] direction = 0 for c in expand(axiom, rules, iterations): if c == "F": xn, yn = nextPoint(xp[-1], yp[-1], direction) xp.append(xn) yp.append(yn) elif c == "-": direction = direction - angle if direction < 0: direction = 360 + direction elif c == "+": direction = (direction + angle) % 360 plt.plot(xp, yp) plt.show() if __name__ == '__main__': s_axiom = "F+XF+F+XF" s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"} s_angle = 90 draw_lsystem(s_axiom, s_rules, s_angle, 3)
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_square { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void sierpinski_square::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = (size - length)/2; y_ = length; angle_ = 0; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "F+XF+F+XF"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string sierpinski_square::rewrite(const std::string& s) { std::string t; for (char c : s) { if (c == 'X') t += "XF-F+F-XF+F+XF-F+F-X"; else t += c; } return t; } void sierpinski_square::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void sierpinski_square::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } } int main() { std::ofstream out("sierpinski_square.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } sierpinski_square s; s.write(out, 635, 5, 5); return 0; }