Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the following Python code into C++ without altering its purpose.
import pyprimes def primorial_prime(_pmax=500): isprime = pyprimes.isprime n, primo = 0, 1 for prime in pyprimes.nprimes(_pmax): n, primo = n+1, primo * prime if isprime(primo-1) or isprime(primo+1): yield n if __name__ == '__main__': pyprimes.warn_probably = False for i, n in zip(range(20), primorial_prime()): print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
#include <cstdint> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_probably_prime(const integer& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } int main() { const unsigned int max = 20; integer primorial = 1; for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) { if (!is_prime(p)) continue; primorial *= p; ++index; if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) { if (count > 0) std::cout << ' '; std::cout << index; ++count; } } std::cout << '\n'; return 0; }
Convert the following code from Python to C++, ensuring the logic remains intact.
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Keep all operations the same but rewrite the snippet in C++.
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Port the provided Python code into C++ while preserving the original functionality.
import threading import random import time class Philosopher(threading.Thread): running = True def __init__(self, xname, forkOnLeft, forkOnRight): threading.Thread.__init__(self) self.name = xname self.forkOnLeft = forkOnLeft self.forkOnRight = forkOnRight def run(self): while(self.running): time.sleep( random.uniform(3,13)) print '%s is hungry.' % self.name self.dine() def dine(self): fork1, fork2 = self.forkOnLeft, self.forkOnRight while self.running: fork1.acquire(True) locked = fork2.acquire(False) if locked: break fork1.release() print '%s swaps forks' % self.name fork1, fork2 = fork2, fork1 else: return self.dining() fork2.release() fork1.release() def dining(self): print '%s starts eating '% self.name time.sleep(random.uniform(1,10)) print '%s finishes eating and leaves to think.' % self.name def DiningPhilosophers(): forks = [threading.Lock() for n in range(5)] philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel') philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \ for i in range(5)] random.seed(507129) Philosopher.running = True for p in philosophers: p.start() time.sleep(100) Philosopher.running = False print ("Now we're finishing.") DiningPhilosophers()
#include <algorithm> #include <array> #include <chrono> #include <iostream> #include <mutex> #include <random> #include <string> #include <string_view> #include <thread> const int timeScale = 42; void Message(std::string_view message) { static std::mutex cout_mutex; std::scoped_lock cout_lock(cout_mutex); std::cout << message << std::endl; } struct Fork { std::mutex mutex; }; struct Dinner { std::array<Fork, 5> forks; ~Dinner() { Message("Dinner is over"); } }; class Philosopher { std::mt19937 rng{std::random_device {}()}; const std::string name; Fork& left; Fork& right; std::thread worker; void live(); void dine(); void ponder(); public: Philosopher(std::string name_, Fork& l, Fork& r) : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this) {} ~Philosopher() { worker.join(); Message(name + " went to sleep."); } }; void Philosopher::live() { for(;;) { { std::scoped_lock dine_lock(left.mutex, right.mutex); dine(); } ponder(); } } void Philosopher::dine() { Message(name + " started eating."); thread_local std::array<const char*, 3> foods {"chicken", "rice", "soda"}; thread_local std::array<const char*, 3> reactions { "I like this %s!", "This %s is good.", "Mmm, %s..." }; thread_local std::uniform_int_distribution<> dist(1, 6); std::shuffle( foods.begin(), foods.end(), rng); std::shuffle(reactions.begin(), reactions.end(), rng); constexpr size_t buf_size = 64; char buffer[buf_size]; for(int i = 0; i < 3; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale)); snprintf(buffer, buf_size, reactions[i], foods[i]); Message(name + ": " + buffer); } std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale); Message(name + " finished and left."); } void Philosopher::ponder() { static constexpr std::array<const char*, 5> topics {{ "politics", "art", "meaning of life", "source of morality", "how many straws makes a bale" }}; thread_local std::uniform_int_distribution<> wait(1, 6); thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1); while(dist(rng) > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale)); Message(name + " is pondering about " + topics[dist(rng)] + "."); } std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale)); Message(name + " is hungry again!"); } int main() { Dinner dinner; Message("Dinner started!"); std::array<Philosopher, 5> philosophers {{ {"Aristotle", dinner.forks[0], dinner.forks[1]}, {"Democritus", dinner.forks[1], dinner.forks[2]}, {"Plato", dinner.forks[2], dinner.forks[3]}, {"Pythagoras", dinner.forks[3], dinner.forks[4]}, {"Socrates", dinner.forks[4], dinner.forks[0]}, }}; Message("It is dark outside..."); }
Maintain the same structure and functionality when rewriting this code in C++.
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Produce a language-to-language conversion: from Python to C++, same semantics.
import numpy as np import scipy.optimize as opt n0, K = 27, 7_800_000_000 def f(t, r): return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K)) y = [ 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652, ] x = np.linspace(0.0, 96, 97) r, cov = opt.curve_fit(f, x, y, [0.5]) print("The r for the world Covid-19 data is:", r, ", with covariance of", cov) print("The calculated R0 is then", np.exp(12 * r))
#include <cmath> #include <functional> #include <iostream> constexpr double K = 7.8e9; constexpr int n0 = 27; constexpr double actual[] = { 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652 }; double f(double r) { double sq = 0; constexpr size_t len = std::size(actual); for (size_t i = 0; i < len; ++i) { double eri = std::exp(r * i); double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K); double diff = guess - actual[i]; sq += diff * diff; } return sq; } double solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) { for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2; delta > epsilon && guess != guess - delta; delta *= factor) { double nf = fn(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else factor = 0.5; } } return guess; } int main() { double r = solve(f); double R0 = std::exp(12 * r); std::cout << "r = " << r << ", R0 = " << R0 << '\n'; return 0; }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
def merge_list(a, b): out = [] while len(a) and len(b): if a[0] < b[0]: out.append(a.pop(0)) else: out.append(b.pop(0)) out += a out += b return out def strand(a): i, s = 0, [a.pop(0)] while i < len(a): if a[i] > s[-1]: s.append(a.pop(i)) else: i += 1 return s def strand_sort(a): out = strand(a) while len(a): out = merge_list(out, strand(a)) return out print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])
#include <list> template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) { if (sorted.back() <= *it) { sorted.push_back(*it); it = lst.erase(it); } else it++; } result.merge(sorted); } return result; }
Write the same algorithm in C++ as shown in this Python implementation.
def is_prime(n: int) -> bool: if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def digit_sum(n: int) -> int: sum = 0 while n > 0: sum += n % 10 n //= 10 return sum def main() -> None: additive_primes = 0 for i in range(2, 500): if is_prime(i) and is_prime(digit_sum(i)): additive_primes += 1 print(i, end=" ") print(f"\nFound {additive_primes} additive primes less than 500") if __name__ == "__main__": main()
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } unsigned int digit_sum(unsigned int n) { unsigned int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { const unsigned int limit = 500; std::cout << "Additive primes less than " << limit << ":\n"; unsigned int count = 0; for (unsigned int n = 1; n < limit; ++n) { if (is_prime(digit_sum(n)) && is_prime(n)) { std::cout << std::setw(3) << n; if (++count % 10 == 0) std::cout << '\n'; else std::cout << ' '; } } std::cout << '\n' << count << " additive primes found.\n"; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
x = truevalue if condition else falsevalue
class invertedAssign { int data; public: invertedAssign(int data):data(data){} int getData(){return data;} void operator=(invertedAssign& other) const { other.data = this->data; } }; #include <iostream> int main(){ invertedAssign a = 0; invertedAssign b = 42; std::cout << a.getData() << ' ' << b.getData() << '\n'; b = a; std::cout << a.getData() << ' ' << b.getData() << '\n'; }
Port the following code from Python to C++ with equivalent syntax and logic.
x = truevalue if condition else falsevalue
class invertedAssign { int data; public: invertedAssign(int data):data(data){} int getData(){return data;} void operator=(invertedAssign& other) const { other.data = this->data; } }; #include <iostream> int main(){ invertedAssign a = 0; invertedAssign b = 42; std::cout << a.getData() << ' ' << b.getData() << '\n'; b = a; std::cout << a.getData() << ' ' << b.getData() << '\n'; }
Translate the given Python code snippet into C++ without altering its behavior.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; bool perfect_totient_number(const totient_calculator& tc, int n) { int sum = 0; for (int m = n; m > 1; ) { int t = tc.totient(m); sum += t; m = t; } return sum == n; } int main() { totient_calculator tc(10000); int count = 0, n = 1; std::cout << "First 20 perfect totient numbers:\n"; for (; count < 20; ++n) { if (perfect_totient_number(tc, n)) { if (count > 0) std::cout << ' '; ++count; std::cout << n; } } std::cout << '\n'; return 0; }
Write the same code in C++ as shown below in Python.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; bool perfect_totient_number(const totient_calculator& tc, int n) { int sum = 0; for (int m = n; m > 1; ) { int t = tc.totient(m); sum += t; m = t; } return sum == n; } int main() { totient_calculator tc(10000); int count = 0, n = 1; std::cout << "First 20 perfect totient numbers:\n"; for (; count < 20; ++n) { if (perfect_totient_number(tc, n)) { if (count > 0) std::cout << ' '; ++count; std::cout << n; } } std::cout << '\n'; return 0; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; bool perfect_totient_number(const totient_calculator& tc, int n) { int sum = 0; for (int m = n; m > 1; ) { int t = tc.totient(m); sum += t; m = t; } return sum == n; } int main() { totient_calculator tc(10000); int count = 0, n = 1; std::cout << "First 20 perfect totient numbers:\n"; for (; count < 20; ++n) { if (perfect_totient_number(tc, n)) { if (count > 0) std::cout << ' '; ++count; std::cout << n; } } std::cout << '\n'; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation' class Delegate: def thing(self): return 'delegate implementation' if __name__ == '__main__': a = Delegator() assert a.operation() == 'default implementation' a.delegate = 'A delegate may be any object' assert a.operation() == 'default implementation' a.delegate = Delegate() assert a.operation() == 'delegate implementation'
#include <tr1/memory> #include <string> #include <iostream> #include <tr1/functional> using namespace std; using namespace std::tr1; using std::tr1::function; class IDelegate { public: virtual ~IDelegate() {} }; class IThing { public: virtual ~IThing() {} virtual std::string Thing() = 0; }; class DelegateA : virtual public IDelegate { }; class DelegateB : public IThing, public IDelegate { std::string Thing() { return "delegate implementation"; } }; class Delegator { public: std::string Operation() { if(Delegate) if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get())) return pThing->Thing(); return "default implementation"; } shared_ptr<IDelegate> Delegate; }; int main() { shared_ptr<DelegateA> delegateA(new DelegateA()); shared_ptr<DelegateB> delegateB(new DelegateB()); Delegator delegator; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateA; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateB; std::cout << delegator.Operation() << std::endl; }
Translate this program into C++ but keep the logic exactly as in Python.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def sum_of_divisors(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= (pow(p,k+1) - 1)//(p-1) return ans if __name__ == "__main__": print([sum_of_divisors(n) for n in range(1,101)])
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } int main() { const unsigned int limit = 100; std::cout << "Sum of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(4) << divisor_sum(n); if (n % 10 == 0) std::cout << '\n'; } }
Write the same code in C++ as shown below in Python.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def sum_of_divisors(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= (pow(p,k+1) - 1)//(p-1) return ans if __name__ == "__main__": print([sum_of_divisors(n) for n in range(1,101)])
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } int main() { const unsigned int limit = 100; std::cout << "Sum of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(4) << divisor_sum(n); if (n % 10 == 0) std::cout << '\n'; } }
Generate a C++ translation of this Python snippet without changing its computational steps.
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Translate the given Python code snippet into C++ without altering its behavior.
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Translate this program into C++ but keep the logic exactly as in Python.
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Translate the given Python code snippet into C++ without altering its behavior.
>>> s = "Hello" >>> s[0] = "h" Traceback (most recent call last): File "<pyshell s[0] = "h" TypeError: 'str' object does not support item assignment
#include <iostream> class MyOtherClass { public: const int m_x; MyOtherClass(const int initX = 0) : m_x(initX) { } }; int main() { MyOtherClass mocA, mocB(7); std::cout << mocA.m_x << std::endl; std::cout << mocB.m_x << std::endl; return 0; }
Write the same code in C++ as shown below in Python.
def clip(subjectPolygon, clipPolygon): def inside(p): return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]) def computeIntersection(): dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ] dp = [ s[0] - e[0], s[1] - e[1] ] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList outputList = [] s = inputList[-1] for subjectVertex in inputList: e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 return(outputList)
#include <iostream> #include <span> #include <vector> struct vec2 { float x = 0.0f, y = 0.0f; constexpr vec2 operator+(vec2 other) const { return vec2{x + other.x, y + other.y}; } constexpr vec2 operator-(vec2 other) const { return vec2{x - other.x, y - other.y}; } }; constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; } constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; } constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; } constexpr bool is_inside(vec2 point, vec2 a, vec2 b) { return (cross(a - b, point) + cross(b, a)) < 0.0f; } constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) { return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) * (1.0f / cross(a1 - a2, b1 - b2)); } std::vector<vec2> suther_land_hodgman( std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) { if (clip_polygon.empty() || subject_polygon.empty()) { return {}; } std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()}; vec2 p1 = clip_polygon[clip_polygon.size() - 1]; std::vector<vec2> input; for (vec2 p2 : clip_polygon) { input.clear(); input.insert(input.end(), ring.begin(), ring.end()); vec2 s = input[input.size() - 1]; ring.clear(); for (vec2 e : input) { if (is_inside(e, p1, p2)) { if (!is_inside(s, p1, p2)) { ring.push_back(intersection(p1, p2, s, e)); } ring.push_back(e); } else if (is_inside(s, p1, p2)) { ring.push_back(intersection(p1, p2, s, e)); } s = e; } p1 = p2; } return ring; } int main(int argc, char **argv) { vec2 subject_polygon[] = {{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}; vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}; std::vector<vec2> clipped_polygon = suther_land_hodgman(subject_polygon, clip_polygon); std::cout << "Clipped polygon points:" << std::endl; for (vec2 p : clipped_polygon) { std::cout << "(" << p.x << ", " << p.y << ")" << std::endl; } return EXIT_SUCCESS; }
Write a version of this Python function in C++ with identical behavior.
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Transform the following Python implementation into C++, maintaining the same output and logic.
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Generate an equivalent C++ version of this Python code.
def spiral(n): dx,dy = 1,0 x,y = 0,0 myarray = [[None]* n for j in range(n)] for i in xrange(n**2): myarray[x][y] = i nx,ny = x+dx, y+dy if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None: x,y = nx,ny else: dx,dy = -dy,dx x,y = x+dx, y+dy return myarray def printspiral(myarray): n = range(len(myarray)) for y in n: for x in n: print "%2i" % myarray[x][y], print printspiral(spiral(5))
#include <vector> #include <memory> #include <cmath> #include <iostream> #include <iomanip> using namespace std; typedef vector< int > IntRow; typedef vector< IntRow > IntTable; auto_ptr< IntTable > getSpiralArray( int dimension ) { auto_ptr< IntTable > spiralArrayPtr( new IntTable( dimension, IntRow( dimension ) ) ); int numConcentricSquares = static_cast< int >( ceil( static_cast< double >( dimension ) / 2.0 ) ); int j; int sideLen = dimension; int currNum = 0; for ( int i = 0; i < numConcentricSquares; i++ ) { for ( j = 0; j < sideLen; j++ ) ( *spiralArrayPtr )[ i ][ i + j ] = currNum++; for ( j = 1; j < sideLen; j++ ) ( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++; for ( j = sideLen - 2; j > -1; j-- ) ( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++; for ( j = sideLen - 2; j > 0; j-- ) ( *spiralArrayPtr )[ i + j ][ i ] = currNum++; sideLen -= 2; } return spiralArrayPtr; } void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr ) { size_t dimension = spiralArrayPtr->size(); int fieldWidth = static_cast< int >( floor( log10( static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; size_t col; for ( size_t row = 0; row < dimension; row++ ) { for ( col = 0; col < dimension; col++ ) cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ]; cout << endl; } } int main() { printSpiralArray( getSpiralArray( 5 ) ); }
Maintain the same structure and functionality when rewriting this code in C++.
>>> def printtable(data): for row in data: print ' '.join('%-5s' % ('"%s"' % cell) for cell in row) >>> import operator >>> def sorttable(table, ordering=None, column=0, reverse=False): return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse) >>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]] >>> printtable(data) "a" "b" "c" "" "q" "z" "zap" "zip" "Zot" >>> printtable( sorttable(data) ) "" "q" "z" "a" "b" "c" "zap" "zip" "Zot" >>> printtable( sorttable(data, column=2) ) "zap" "zip" "Zot" "a" "b" "c" "" "q" "z" >>> printtable( sorttable(data, column=1) ) "a" "b" "c" "" "q" "z" "zap" "zip" "Zot" >>> printtable( sorttable(data, column=1, reverse=True) ) "zap" "zip" "Zot" "" "q" "z" "a" "b" "c" >>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) ) "zap" "zip" "Zot" "a" "b" "c" "" "q" "z" >>>
#include <vector> #include <algorithm> #include <string> template <class T> struct sort_table_functor { typedef bool (*CompFun)(const T &, const T &); const CompFun ordering; const int column; const bool reverse; sort_table_functor(CompFun o, int c, bool r) : ordering(o), column(c), reverse(r) { } bool operator()(const std::vector<T> &x, const std::vector<T> &y) const { const T &a = x[column], &b = y[column]; return reverse ? ordering(b, a) : ordering(a, b); } }; template <class T> bool myLess(const T &x, const T &y) { return x < y; } template <class T> void sort_table(std::vector<std::vector<T> > &table, int column = 0, bool reverse = false, bool (*ordering)(const T &, const T &) = myLess) { std::sort(table.begin(), table.end(), sort_table_functor<T>(ordering, column, reverse)); } #include <iostream> template <class T> void print_matrix(std::vector<std::vector<T> > &data) { for () { for (int j = 0; j < 3; j++) std::cout << data[i][j] << "\t"; std::cout << std::endl; } } bool desc_len_comparator(const std::string &x, const std::string &y) { return x.length() > y.length(); } int main() { std::string data_array[3][3] = { {"a", "b", "c"}, {"", "q", "z"}, {"zap", "zip", "Zot"} }; std::vector<std::vector<std::string> > data_orig; for (int i = 0; i < 3; i++) { std::vector<std::string> row; for (int j = 0; j < 3; j++) row.push_back(data_array[i][j]); data_orig.push_back(row); } print_matrix(data_orig); std::vector<std::vector<std::string> > data = data_orig; sort_table(data); print_matrix(data); data = data_orig; sort_table(data, 2); print_matrix(data); data = data_orig; sort_table(data, 1); print_matrix(data); data = data_orig; sort_table(data, 1, true); print_matrix(data); data = data_orig; sort_table(data, 0, false, desc_len_comparator); print_matrix(data); return 0; }
Produce a language-to-language conversion: from Python to C++, same semantics.
def setup(): size(500, 500) generate_voronoi_diagram(width, height, 25) saveFrame("VoronoiDiagram.png") def generate_voronoi_diagram(w, h, num_cells): nx, ny, nr, ng, nb = [], [], [], [], [] for i in range(num_cells): nx.append(int(random(w))) ny.append(int(random(h))) nr.append(int(random(256))) ng.append(int(random(256))) nb.append(int(random(256))) for y in range(h): for x in range(w): dmin = dist(0, 0, w - 1, h - 1) j = -1 for i in range(num_cells): d = dist(0, 0, nx[i] - x, ny[i] - y) if d < dmin: dmin = d j = i set(x, y, color(nr[j], ng[j], nb[j]))
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMemory(&bi, sizeof(bi)); bi.bmiHeader.biSize = sizeof(bi.bmiHeader); bi.bmiHeader.biBitCount = sizeof(DWORD) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; void *bits_ptr = nullptr; HDC dc = GetDC(GetConsoleWindow()); bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0); if (!bmp_) return false; hdc_ = CreateCompatibleDC(dc); SelectObject(hdc_, bmp_); ReleaseDC(GetConsoleWindow(), dc); width_ = w; height_ = h; return true; } void SetPenColor(DWORD clr) { if (pen_) DeleteObject(pen_); pen_ = CreatePen(PS_SOLID, 1, clr); SelectObject(hdc_, pen_); } bool SaveBitmap(const char* path) { HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return false; } BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; GetObject(bmp_, sizeof(bitmap), &bitmap); DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD)); ZeroMemory(&infoheader, sizeof(BITMAPINFO)); ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER)); infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS); DWORD wb; WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr); WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr); WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr); CloseHandle(file); delete[] dwp_bits; return true; } HDC hdc() { return hdc_; } int width() { return width_; } int height() { return height_; } private: HBITMAP bmp_; HDC hdc_; HPEN pen_; int width_, height_; }; static int DistanceSqrd(const Point& point, int x, int y) { int xd = x - point.x; int yd = y - point.y; return (xd * xd) + (yd * yd); } class Voronoi { public: void Make(MyBitmap* bmp, int count) { bmp_ = bmp; CreatePoints(count); CreateColors(); CreateSites(); SetSitesPoints(); } private: void CreateSites() { int w = bmp_->width(), h = bmp_->height(), d; for (int hh = 0; hh < h; hh++) { for (int ww = 0; ww < w; ww++) { int ind = -1, dist = INT_MAX; for (size_t it = 0; it < points_.size(); it++) { const Point& p = points_[it]; d = DistanceSqrd(p, ww, hh); if (d < dist) { dist = d; ind = it; } } if (ind > -1) SetPixel(bmp_->hdc(), ww, hh, colors_[ind]); else __asm nop } } } void SetSitesPoints() { for (const auto& point : points_) { int x = point.x, y = point.y; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) SetPixel(bmp_->hdc(), x + i, y + j, 0); } } void CreatePoints(int count) { const int w = bmp_->width() - 20, h = bmp_->height() - 20; for (int i = 0; i < count; i++) { points_.push_back({ rand() % w + 10, rand() % h + 10 }); } } void CreateColors() { for (size_t i = 0; i < points_.size(); i++) { DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50); colors_.push_back(c); } } vector<Point> points_; vector<DWORD> colors_; MyBitmap* bmp_; }; int main(int argc, char* argv[]) { ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); srand(GetTickCount()); MyBitmap bmp; bmp.Create(512, 512); bmp.SetPenColor(0); Voronoi v; v.Make(&bmp, 50); BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY); bmp.SaveBitmap("v.bmp"); system("pause"); return 0; }
Transform the following Python implementation into C++, maintaining the same output and logic.
def setup(): size(500, 500) generate_voronoi_diagram(width, height, 25) saveFrame("VoronoiDiagram.png") def generate_voronoi_diagram(w, h, num_cells): nx, ny, nr, ng, nb = [], [], [], [], [] for i in range(num_cells): nx.append(int(random(w))) ny.append(int(random(h))) nr.append(int(random(256))) ng.append(int(random(256))) nb.append(int(random(256))) for y in range(h): for x in range(w): dmin = dist(0, 0, w - 1, h - 1) j = -1 for i in range(num_cells): d = dist(0, 0, nx[i] - x, ny[i] - y) if d < dmin: dmin = d j = i set(x, y, color(nr[j], ng[j], nb[j]))
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMemory(&bi, sizeof(bi)); bi.bmiHeader.biSize = sizeof(bi.bmiHeader); bi.bmiHeader.biBitCount = sizeof(DWORD) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; void *bits_ptr = nullptr; HDC dc = GetDC(GetConsoleWindow()); bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0); if (!bmp_) return false; hdc_ = CreateCompatibleDC(dc); SelectObject(hdc_, bmp_); ReleaseDC(GetConsoleWindow(), dc); width_ = w; height_ = h; return true; } void SetPenColor(DWORD clr) { if (pen_) DeleteObject(pen_); pen_ = CreatePen(PS_SOLID, 1, clr); SelectObject(hdc_, pen_); } bool SaveBitmap(const char* path) { HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return false; } BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; GetObject(bmp_, sizeof(bitmap), &bitmap); DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD)); ZeroMemory(&infoheader, sizeof(BITMAPINFO)); ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER)); infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS); DWORD wb; WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr); WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr); WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr); CloseHandle(file); delete[] dwp_bits; return true; } HDC hdc() { return hdc_; } int width() { return width_; } int height() { return height_; } private: HBITMAP bmp_; HDC hdc_; HPEN pen_; int width_, height_; }; static int DistanceSqrd(const Point& point, int x, int y) { int xd = x - point.x; int yd = y - point.y; return (xd * xd) + (yd * yd); } class Voronoi { public: void Make(MyBitmap* bmp, int count) { bmp_ = bmp; CreatePoints(count); CreateColors(); CreateSites(); SetSitesPoints(); } private: void CreateSites() { int w = bmp_->width(), h = bmp_->height(), d; for (int hh = 0; hh < h; hh++) { for (int ww = 0; ww < w; ww++) { int ind = -1, dist = INT_MAX; for (size_t it = 0; it < points_.size(); it++) { const Point& p = points_[it]; d = DistanceSqrd(p, ww, hh); if (d < dist) { dist = d; ind = it; } } if (ind > -1) SetPixel(bmp_->hdc(), ww, hh, colors_[ind]); else __asm nop } } } void SetSitesPoints() { for (const auto& point : points_) { int x = point.x, y = point.y; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) SetPixel(bmp_->hdc(), x + i, y + j, 0); } } void CreatePoints(int count) { const int w = bmp_->width() - 20, h = bmp_->height() - 20; for (int i = 0; i < count; i++) { points_.push_back({ rand() % w + 10, rand() % h + 10 }); } } void CreateColors() { for (size_t i = 0; i < points_.size(); i++) { DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50); colors_.push_back(c); } } vector<Point> points_; vector<DWORD> colors_; MyBitmap* bmp_; }; int main(int argc, char* argv[]) { ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); srand(GetTickCount()); MyBitmap bmp; bmp.Create(512, 512); bmp.SetPenColor(0); Voronoi v; v.Make(&bmp, 50); BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY); bmp.SaveBitmap("v.bmp"); system("pause"); return 0; }
Produce a language-to-language conversion: from Python to C++, same semantics.
import ctypes libc = ctypes.CDLL("/lib/libc.so.6") libc.strcmp("abc", "def") libc.strcmp("hello", "hello")
FUNCTION MULTIPLY(X, Y) DOUBLE PRECISION MULTIPLY, X, Y
Transform the following Python implementation into C++, maintaining the same output and logic.
from random import randrange def s_of_n_creator(n): sample, i = [], 0 def s_of_n(item): nonlocal i i += 1 if i <= n: sample.append(item) elif randrange(i) < n: sample[randrange(n)] = item return sample return s_of_n if __name__ == '__main__': bin = [0]* 10 items = range(10) print("Single run samples for n = 3:") s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) print(" Item: %i -> sample: %s" % (item, sample)) for trial in range(100000): s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) for s in sample: bin[s] += 1 print("\nTest item frequencies for 100000 runs:\n ", '\n '.join("%i:%i" % x for x in enumerate(bin)))
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime> template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (std::rand() % i < n) { sample[std::rand() % n] = item; } return sample; }; } int main() { std::srand(std::time(NULL)); int bin[10] = {0}; for (int trial = 0; trial < 100000; trial++) { auto s_of_n = s_of_n_creator<int>(3); std::vector<int> sample; for (int i = 0; i < 10; i++) sample = s_of_n(i); for (int s : sample) bin[s]++; } for (int x : bin) std::cout << x << std::endl; return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from random import randrange def s_of_n_creator(n): sample, i = [], 0 def s_of_n(item): nonlocal i i += 1 if i <= n: sample.append(item) elif randrange(i) < n: sample[randrange(n)] = item return sample return s_of_n if __name__ == '__main__': bin = [0]* 10 items = range(10) print("Single run samples for n = 3:") s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) print(" Item: %i -> sample: %s" % (item, sample)) for trial in range(100000): s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) for s in sample: bin[s] += 1 print("\nTest item frequencies for 100000 runs:\n ", '\n '.join("%i:%i" % x for x in enumerate(bin)))
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime> template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (std::rand() % i < n) { sample[std::rand() % n] = item; } return sample; }; } int main() { std::srand(std::time(NULL)); int bin[10] = {0}; for (int trial = 0; trial < 100000; trial++) { auto s_of_n = s_of_n_creator<int>(3); std::vector<int> sample; for (int i = 0; i < 10; i++) sample = s_of_n(i); for (int s : sample) bin[s]++; } for (int x : bin) std::cout << x << std::endl; return 0; }
Translate this program into C++ but keep the logic exactly as in Python.
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:] def faulhaberSum(p, n): def go(x, y): return y * (n ** x) return sum( map(go, count(1), faulhaberTriangle(p)[-1]) ) def main(): fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) ) def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox def compose(g): return lambda f: lambda x: g(f(x)) def concat(xs): def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] def fmap(f): def go(xs): return list(map(f, xs)) return go def index(xs): return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) def showRatio(m): def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go if __name__ == '__main__': main()
#include <exception> #include <iomanip> #include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac() : num(0), denom(1) {} Frac(int n, int d) { if (d == 0) { throw std::runtime_error("d must not be zero"); } int sign_of_d = d < 0 ? -1 : 1; int g = std::gcd(n, d); num = sign_of_d * n / g; denom = sign_of_d * d / g; } Frac operator-() const { return Frac(-num, denom); } Frac operator+(const Frac& rhs) const { return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom); } Frac operator-(const Frac& rhs) const { return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom); } Frac operator*(const Frac& rhs) const { return Frac(num*rhs.num, denom*rhs.denom); } Frac operator*(int rhs) const { return Frac(num * rhs, denom); } friend std::ostream& operator<<(std::ostream&, const Frac&); private: int num; int denom; }; std::ostream & operator<<(std::ostream & os, const Frac &f) { if (f.num == 0 || f.denom == 1) { return os << f.num; } std::stringstream ss; ss << f.num << "/" << f.denom; return os << ss.str(); } Frac bernoulli(int n) { if (n < 0) { throw std::runtime_error("n may not be negative or zero"); } std::vector<Frac> a; for (int m = 0; m <= n; m++) { a.push_back(Frac(1, m + 1)); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * j; } } if (n != 1) return a[0]; return -a[0]; } int binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw std::runtime_error("parameters are invalid"); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num *= i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom *= i; } return num / denom; } std::vector<Frac> faulhaberTraingle(int p) { std::vector<Frac> coeffs(p + 1); Frac q{ 1, p + 1 }; int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j); } return coeffs; } int main() { for (int i = 0; i < 10; i++) { std::vector<Frac> coeffs = faulhaberTraingle(i); for (auto frac : coeffs) { std::cout << std::right << std::setw(5) << frac << " "; } std::cout << std::endl; } return 0; }
Write a version of this Python function in C++ with identical behavior.
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
Generate an equivalent C++ version of this Python code.
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
import urllib.request from collections import Counter GRID = def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'): "Return lowercased words of 3 to 9 characters" words = urllib.request.urlopen(url).read().decode().strip().lower().split() return (w for w in words if 2 < len(w) < 10) def solve(grid, dictionary): gridcount = Counter(grid) mid = grid[4] return [word for word in dictionary if mid in word and not (Counter(word) - gridcount)] if __name__ == '__main__': chars = ''.join(GRID.strip().lower().split()) found = solve(chars, dictionary=getwords()) print('\n'.join(found))
#include <array> #include <iostream> #include <fstream> #include <map> #include <string> #include <vector> #include <boost/program_options.hpp> class letterset { public: letterset() { count_.fill(0); } explicit letterset(const std::string& str) { count_.fill(0); for (char c : str) add(c); } bool contains(const letterset& set) const { for (size_t i = 0; i < count_.size(); ++i) { if (set.count_[i] > count_[i]) return false; } return true; } unsigned int count(char c) const { return count_[index(c)]; } bool is_valid() const { return count_[0] == 0; } void add(char c) { ++count_[index(c)]; } private: static bool is_letter(char c) { return c >= 'a' && c <= 'z'; } static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; } std::array<unsigned int, 27> count_; }; template <typename iterator, typename separator> std::string join(iterator begin, iterator end, separator sep) { std::string result; if (begin != end) { result += *begin++; for (; begin != end; ++begin) { result += sep; result += *begin; } } return result; } using dictionary = std::vector<std::pair<std::string, letterset>>; dictionary load_dictionary(const std::string& filename, int min_length, int max_length) { std::ifstream in(filename); if (!in) throw std::runtime_error("Cannot open file " + filename); std::string word; dictionary result; while (getline(in, word)) { if (word.size() < min_length) continue; if (word.size() > max_length) continue; letterset set(word); if (set.is_valid()) result.emplace_back(word, set); } return result; } void word_wheel(const dictionary& dict, const std::string& letters, char central_letter) { letterset set(letters); if (central_letter == 0 && !letters.empty()) central_letter = letters.at(letters.size()/2); std::map<size_t, std::vector<std::string>> words; for (const auto& pair : dict) { const auto& word = pair.first; const auto& subset = pair.second; if (subset.count(central_letter) > 0 && set.contains(subset)) words[word.size()].push_back(word); } size_t total = 0; for (const auto& p : words) { const auto& v = p.second; auto n = v.size(); total += n; std::cout << "Found " << n << " " << (n == 1 ? "word" : "words") << " of length " << p.first << ": " << join(v.begin(), v.end(), ", ") << '\n'; } std::cout << "Number of words found: " << total << '\n'; } void find_max_word_count(const dictionary& dict, int word_length) { size_t max_count = 0; std::vector<std::pair<std::string, char>> max_words; for (const auto& pair : dict) { const auto& word = pair.first; if (word.size() != word_length) continue; const auto& set = pair.second; dictionary subsets; for (const auto& p : dict) { if (set.contains(p.second)) subsets.push_back(p); } letterset done; for (size_t index = 0; index < word_length; ++index) { char central_letter = word[index]; if (done.count(central_letter) > 0) continue; done.add(central_letter); size_t count = 0; for (const auto& p : subsets) { const auto& subset = p.second; if (subset.count(central_letter) > 0) ++count; } if (count > max_count) { max_words.clear(); max_count = count; } if (count == max_count) max_words.emplace_back(word, central_letter); } } std::cout << "Maximum word count: " << max_count << '\n'; std::cout << "Words of " << word_length << " letters producing this count:\n"; for (const auto& pair : max_words) std::cout << pair.first << " with central letter " << pair.second << '\n'; } constexpr const char* option_filename = "filename"; constexpr const char* option_wheel = "wheel"; constexpr const char* option_central = "central"; constexpr const char* option_min_length = "min-length"; constexpr const char* option_part2 = "part2"; int main(int argc, char** argv) { const int word_length = 9; int min_length = 3; std::string letters = "ndeokgelw"; std::string filename = "unixdict.txt"; char central_letter = 0; bool do_part2 = false; namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() (option_filename, po::value<std::string>(), "name of dictionary file") (option_wheel, po::value<std::string>(), "word wheel letters") (option_central, po::value<char>(), "central letter (defaults to middle letter of word)") (option_min_length, po::value<int>(), "minimum word length") (option_part2, "include part 2"); try { po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count(option_filename)) filename = vm[option_filename].as<std::string>(); if (vm.count(option_wheel)) letters = vm[option_wheel].as<std::string>(); if (vm.count(option_central)) central_letter = vm[option_central].as<char>(); if (vm.count(option_min_length)) min_length = vm[option_min_length].as<int>(); if (vm.count(option_part2)) do_part2 = true; auto dict = load_dictionary(filename, min_length, word_length); word_wheel(dict, letters, central_letter); if (do_part2) { std::cout << '\n'; find_max_word_count(dict, word_length); } } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Write the same algorithm in C++ as shown in this Python implementation.
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
#include <vector> #include <iostream> int main() { std::vector<int> a(3), b(4); a[0] = 11; a[1] = 12; a[2] = 13; b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24; a.insert(a.end(), b.begin(), b.end()); for (int i = 0; i < a.size(); ++i) std::cout << "a[" << i << "] = " << a[i] << "\n"; }
Maintain the same structure and functionality when rewriting this code in C++.
string = raw_input("Input a string: ")
#include <iostream> #include <string> using namespace std; int main() { long int integer_input; string string_input; cout << "Enter an integer: "; cin >> integer_input; cout << "Enter a string: "; cin >> string_input; return 0; }
Port the provided Python code into C++ while preserving the original functionality.
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
Convert this Python snippet to C++ and keep its semantics consistent.
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
Transform the following Python implementation into C++, maintaining the same output and logic.
from itertools import combinations def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) ) def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), ) bagged = max( anycomb(items), key=totalvalue) print("Bagged the following items\n " + '\n '.join(sorted(item for item,_,_ in bagged))) val, wt = totalvalue(bagged) print("for a total value of %i and a total weight of %i" % (val, -wt))
#include <vector> #include <string> #include <iostream> #include <boost/tuple/tuple.hpp> #include <set> int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , std::set<int> & , const int ) ; int main( ) { std::vector<boost::tuple<std::string , int , int> > items ; items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ; items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ; items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ; items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ; items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ; items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ; items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ; items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ; items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ; items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ; items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ; items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ; items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ; items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ; items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ; items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ; items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ; items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ; items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ; items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ; items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ; items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ; items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ; const int maximumWeight = 400 ; std::set<int> bestItems ; int bestValue = findBestPack( items , bestItems , maximumWeight ) ; std::cout << "The best value that can be packed in the given knapsack is " << bestValue << " !\n" ; int totalweight = 0 ; std::cout << "The following items should be packed in the knapsack:\n" ; for ( std::set<int>::const_iterator si = bestItems.begin( ) ; si != bestItems.end( ) ; si++ ) { std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ; totalweight += (items.begin( ) + *si)->get<1>( ) ; } std::cout << "The total weight of all items is " << totalweight << " !\n" ; return 0 ; } int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) { const int n = items.size( ) ; int bestValues [ n ][ weightlimit ] ; std::set<int> solutionSets[ n ][ weightlimit ] ; std::set<int> emptyset ; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < weightlimit ; j++ ) { bestValues[ i ][ j ] = 0 ; solutionSets[ i ][ j ] = emptyset ; } } for ( int i = 0 ; i < n ; i++ ) { for ( int weight = 0 ; weight < weightlimit ; weight++ ) { if ( i == 0 ) bestValues[ i ][ weight ] = 0 ; else { int itemweight = (items.begin( ) + i)->get<1>( ) ; if ( weight < itemweight ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } else { if ( bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) > bestValues[ i - 1 ][ weight ] ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight - itemweight ] ; solutionSets[ i ][ weight ].insert( i ) ; } else { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } } } } } bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ; return bestValues[ n - 1 ][ weightlimit - 1 ] ; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
from __future__ import print_function from itertools import takewhile maxsum = 99 def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x % p == 0: break else: lprimes.append(x) return lprimes descendants = [[] for _ in range(maxsum + 1)] ancestors = [[] for _ in range(maxsum + 1)] primes = get_primes(maxsum) for p in primes: descendants[p].append(p) for s in range(1, len(descendants) - p): descendants[s + p] += [p * pr for pr in descendants[s]] for p in primes + [4]: descendants[p].pop() total = 0 for s in range(1, maxsum + 1): descendants[s].sort() for d in takewhile(lambda x: x <= maxsum, descendants[s]): ancestors[d] = ancestors[s] + [s] print([s], "Level:", len(ancestors[s])) print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None") print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None") if len(descendants[s]): print(descendants[s]) print() total += len(descendants[s]) print("Total descendants", total)
#include <algorithm> #include <iostream> #include <vector> typedef unsigned long long integer; std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && a != n; ) { n = a; a = ancestor[n]; result.push_back(n); } return result; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()) { std::cout << "none\n"; return; } auto i = vec.begin(); std::cout << *i++; for (; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (integer p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } int main(int argc, char** argv) { const size_t limit = 100; std::vector<integer> ancestor(limit, 0); std::vector<std::vector<integer>> descendants(limit); for (size_t prime = 0; prime < limit; ++prime) { if (!is_prime(prime)) continue; descendants[prime].push_back(prime); for (size_t i = 0; i + prime < limit; ++i) { integer s = i + prime; for (integer n : descendants[i]) { integer prod = n * prime; descendants[s].push_back(prod); if (prod < limit) ancestor[prod] = s; } } } size_t total_descendants = 0; for (integer i = 1; i < limit; ++i) { std::vector<integer> ancestors(get_ancestors(ancestor, i)); std::cout << "[" << i << "] Level: " << ancestors.size() << '\n'; std::cout << "Ancestors: "; std::sort(ancestors.begin(), ancestors.end()); print_vector(ancestors); std::cout << "Descendants: "; std::vector<integer>& desc = descendants[i]; if (!desc.empty()) { std::sort(desc.begin(), desc.end()); if (desc[0] == i) desc.erase(desc.begin()); } std::cout << desc.size() << '\n'; total_descendants += desc.size(); if (!desc.empty()) print_vector(desc); std::cout << '\n'; } std::cout << "Total descendants: " << total_descendants << '\n'; return 0; }
Port the provided Python code into C++ while preserving the original functionality.
from __future__ import print_function from itertools import takewhile maxsum = 99 def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x % p == 0: break else: lprimes.append(x) return lprimes descendants = [[] for _ in range(maxsum + 1)] ancestors = [[] for _ in range(maxsum + 1)] primes = get_primes(maxsum) for p in primes: descendants[p].append(p) for s in range(1, len(descendants) - p): descendants[s + p] += [p * pr for pr in descendants[s]] for p in primes + [4]: descendants[p].pop() total = 0 for s in range(1, maxsum + 1): descendants[s].sort() for d in takewhile(lambda x: x <= maxsum, descendants[s]): ancestors[d] = ancestors[s] + [s] print([s], "Level:", len(ancestors[s])) print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None") print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None") if len(descendants[s]): print(descendants[s]) print() total += len(descendants[s]) print("Total descendants", total)
#include <algorithm> #include <iostream> #include <vector> typedef unsigned long long integer; std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && a != n; ) { n = a; a = ancestor[n]; result.push_back(n); } return result; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()) { std::cout << "none\n"; return; } auto i = vec.begin(); std::cout << *i++; for (; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (integer p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } int main(int argc, char** argv) { const size_t limit = 100; std::vector<integer> ancestor(limit, 0); std::vector<std::vector<integer>> descendants(limit); for (size_t prime = 0; prime < limit; ++prime) { if (!is_prime(prime)) continue; descendants[prime].push_back(prime); for (size_t i = 0; i + prime < limit; ++i) { integer s = i + prime; for (integer n : descendants[i]) { integer prod = n * prime; descendants[s].push_back(prod); if (prod < limit) ancestor[prod] = s; } } } size_t total_descendants = 0; for (integer i = 1; i < limit; ++i) { std::vector<integer> ancestors(get_ancestors(ancestor, i)); std::cout << "[" << i << "] Level: " << ancestors.size() << '\n'; std::cout << "Ancestors: "; std::sort(ancestors.begin(), ancestors.end()); print_vector(ancestors); std::cout << "Descendants: "; std::vector<integer>& desc = descendants[i]; if (!desc.empty()) { std::sort(desc.begin(), desc.end()); if (desc[0] == i) desc.erase(desc.begin()); } std::cout << desc.size() << '\n'; total_descendants += desc.size(); if (!desc.empty()) print_vector(desc); std::cout << '\n'; } std::cout << "Total descendants: " << total_descendants << '\n'; return 0; }
Please provide an equivalent version of this Python code in C++.
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }
Convert the following code from Python to C++, ensuring the logic remains intact.
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
#include <functional> #include <algorithm> #include <iostream> #include <vector> #include <cmath> using std::cout; using std::endl; using std::vector; using std::function; using std::transform; using std::back_inserter; typedef function<double(double)> FunType; vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } }; vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } }; template <typename A, typename B, typename C> function<C(A)> compose(function<C(B)> f, function<B(A)> g) { return [f,g](A x) { return f(g(x)); }; } int main() { vector<FunType> composedFuns; auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0}; transform(B.begin(), B.end(), A.begin(), back_inserter(composedFuns), compose<double, double, double>); for (auto num: exNums) for (auto fun: composedFuns) cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl; return 0; }
Port the following code from Python to C++ with equivalent syntax and logic.
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
#include <vector> #include <iostream> #include <algorithm> std::vector<int> properDivisors ( int number ) { std::vector<int> divisors ; for ( int i = 1 ; i < number / 2 + 1 ; i++ ) if ( number % i == 0 ) divisors.push_back( i ) ; return divisors ; } int main( ) { std::vector<int> divisors ; unsigned int maxdivisors = 0 ; int corresponding_number = 0 ; for ( int i = 1 ; i < 11 ; i++ ) { divisors = properDivisors ( i ) ; std::cout << "Proper divisors of " << i << ":\n" ; for ( int number : divisors ) { std::cout << number << " " ; } std::cout << std::endl ; divisors.clear( ) ; } for ( int i = 11 ; i < 20001 ; i++ ) { divisors = properDivisors ( i ) ; if ( divisors.size( ) > maxdivisors ) { maxdivisors = divisors.size( ) ; corresponding_number = i ; } divisors.clear( ) ; } std::cout << "Most divisors has " << corresponding_number << " , it has " << maxdivisors << " divisors!\n" ; return 0 ; }
Please provide an equivalent version of this Python code in C++.
>>> from xml.etree import ElementTree as ET >>> from itertools import izip >>> def characterstoxml(names, remarks): root = ET.Element("CharacterRemarks") for name, remark in izip(names, remarks): c = ET.SubElement(root, "Character", {'name': name}) c.text = remark return ET.tostring(root) >>> print characterstoxml( names = ["April", "Tam O'Shanter", "Emily"], remarks = [ "Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', 'Short & shrift' ] ).replace('><','>\n<')
#include <vector> #include <utility> #include <iostream> #include <boost/algorithm/string.hpp> std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ; int main( ) { std::vector<std::string> names , remarks ; names.push_back( "April" ) ; names.push_back( "Tam O'Shantor" ) ; names.push_back ( "Emily" ) ; remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ; remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ; remarks.push_back( "Short & shrift" ) ; std::cout << "This is in XML:\n" ; std::cout << create_xml( names , remarks ) << std::endl ; return 0 ; } std::string create_xml( std::vector<std::string> & names , std::vector<std::string> & remarks ) { std::vector<std::pair<std::string , std::string> > entities ; entities.push_back( std::make_pair( "&" , "&amp;" ) ) ; entities.push_back( std::make_pair( "<" , "&lt;" ) ) ; entities.push_back( std::make_pair( ">" , "&gt;" ) ) ; std::string xmlstring ( "<CharacterRemarks>\n" ) ; std::vector<std::string>::iterator vsi = names.begin( ) ; typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ; for ( ; vsi != names.end( ) ; vsi++ ) { for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { boost::replace_all ( *vsi , vs->first , vs->second ) ; } } for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) { for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { boost::replace_all ( *vsi , vs->first , vs->second ) ; } } for ( int i = 0 ; i < names.size( ) ; i++ ) { xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">") .append( remarks[ i ] ).append( "</Character>\n" ) ; } xmlstring.append( "</CharacterRemarks>" ) ; return xmlstring ; }
Maintain the same structure and functionality when rewriting this code in C++.
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
#include <windows.h> #include <string> #include <vector> using namespace std; const int HSTEP = 46, MWID = 40, MHEI = 471; const float VSTEP = 2.3f; class vector2 { public: vector2() { x = y = 0; } vector2( float a, float b ) { x = a; y = b; } void set( float a, float b ) { x = a; y = b; } float x, y; }; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class plot { public: plot() { bmp.create( 512, 512 ); } void draw( vector<vector2>* pairs ) { bmp.clear( 0xff ); drawGraph( pairs ); plotIt( pairs ); HDC dc = GetDC( GetConsoleWindow() ); BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( GetConsoleWindow(), dc ); } private: void drawGraph( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); bmp.setPenColor( RGB( 240, 240, 240 ) ); DWORD b = 11, c = 40, x; RECT rc; char txt[8]; for( x = 0; x < pairs->size(); x++ ) { MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 ); wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); wsprintf( txt, "%d", x ); SetRect( &rc, c - 8, 472, c + 8, 492 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); c += 46; b += 46; } SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); } void plotIt( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); HBRUSH br = CreateSolidBrush( 255 ); RECT rc; bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); vector<vector2>::iterator it = pairs->begin(); int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); MoveToEx( dc, a, b, NULL ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); it++; for( ; it < pairs->end(); it++ ) { a = MWID + HSTEP * static_cast<int>( ( *it ).x ); b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); LineTo( dc, a, b ); } DeleteObject( br ); } myBitmap bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); plot pt; vector<vector2> pairs; pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) ); pt.draw( &pairs ); system( "pause" ); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
#include <windows.h> #include <string> #include <vector> using namespace std; const int HSTEP = 46, MWID = 40, MHEI = 471; const float VSTEP = 2.3f; class vector2 { public: vector2() { x = y = 0; } vector2( float a, float b ) { x = a; y = b; } void set( float a, float b ) { x = a; y = b; } float x, y; }; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class plot { public: plot() { bmp.create( 512, 512 ); } void draw( vector<vector2>* pairs ) { bmp.clear( 0xff ); drawGraph( pairs ); plotIt( pairs ); HDC dc = GetDC( GetConsoleWindow() ); BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( GetConsoleWindow(), dc ); } private: void drawGraph( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); bmp.setPenColor( RGB( 240, 240, 240 ) ); DWORD b = 11, c = 40, x; RECT rc; char txt[8]; for( x = 0; x < pairs->size(); x++ ) { MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 ); wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); wsprintf( txt, "%d", x ); SetRect( &rc, c - 8, 472, c + 8, 492 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); c += 46; b += 46; } SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); } void plotIt( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); HBRUSH br = CreateSolidBrush( 255 ); RECT rc; bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); vector<vector2>::iterator it = pairs->begin(); int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); MoveToEx( dc, a, b, NULL ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); it++; for( ; it < pairs->end(); it++ ) { a = MWID + HSTEP * static_cast<int>( ( *it ).x ); b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); LineTo( dc, a, b ); } DeleteObject( br ); } myBitmap bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); plot pt; vector<vector2> pairs; pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) ); pt.draw( &pairs ); system( "pause" ); return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
#include <windows.h> #include <string> #include <vector> using namespace std; const int HSTEP = 46, MWID = 40, MHEI = 471; const float VSTEP = 2.3f; class vector2 { public: vector2() { x = y = 0; } vector2( float a, float b ) { x = a; y = b; } void set( float a, float b ) { x = a; y = b; } float x, y; }; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class plot { public: plot() { bmp.create( 512, 512 ); } void draw( vector<vector2>* pairs ) { bmp.clear( 0xff ); drawGraph( pairs ); plotIt( pairs ); HDC dc = GetDC( GetConsoleWindow() ); BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( GetConsoleWindow(), dc ); } private: void drawGraph( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); bmp.setPenColor( RGB( 240, 240, 240 ) ); DWORD b = 11, c = 40, x; RECT rc; char txt[8]; for( x = 0; x < pairs->size(); x++ ) { MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 ); wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); wsprintf( txt, "%d", x ); SetRect( &rc, c - 8, 472, c + 8, 492 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); c += 46; b += 46; } SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); } void plotIt( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); HBRUSH br = CreateSolidBrush( 255 ); RECT rc; bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); vector<vector2>::iterator it = pairs->begin(); int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); MoveToEx( dc, a, b, NULL ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); it++; for( ; it < pairs->end(); it++ ) { a = MWID + HSTEP * static_cast<int>( ( *it ).x ); b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); LineTo( dc, a, b ); } DeleteObject( br ); } myBitmap bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); plot pt; vector<vector2> pairs; pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) ); pt.draw( &pairs ); system( "pause" ); return 0; }
Generate a C++ translation of this Python snippet without changing its computational steps.
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
#include <iostream> #include <string> #include <iterator> #include <regex> int main() { std::regex re(".* string$"); std::string s = "Hi, I am a string"; if (std::regex_match(s, re)) std::cout << "The string matches.\n"; else std::cout << "Oops - not found?\n"; std::regex re2(" a.*a"); std::smatch match; if (std::regex_search(s, match, re2)) { std::cout << "Matched " << match.length() << " characters starting at " << match.position() << ".\n"; std::cout << "Matched character sequence: \"" << match.str() << "\"\n"; } else { std::cout << "Oops - not found?\n"; } std::string dest_string; std::regex_replace(std::back_inserter(dest_string), s.begin(), s.end(), re2, "'m now a changed"); std::cout << dest_string << std::endl; }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
inclusive_range = mn, mx = (1, 10) print( % inclusive_range) i = 0 while True: i += 1 guess = (mn+mx)//2 txt = input("Guess %2i is: %2i. The score for which is (h,l,=): " % (i, guess)).strip().lower()[0] if txt not in 'hl=': print(" I don't understand your input of '%s' ?" % txt) continue if txt == 'h': mx = guess-1 if txt == 'l': mn = guess+1 if txt == '=': print(" Ye-Haw!!") break if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]): print("Please check your scoring as I cannot find the value") break print("\nThanks for keeping score.")
#include <iostream> #include <algorithm> #include <string> #include <iterator> struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> { int i; GuessNumberIterator() { } GuessNumberIterator(int _i) : i(_i) { } GuessNumberIterator& operator++() { ++i; return *this; } GuessNumberIterator operator++(int) { GuessNumberIterator tmp = *this; ++(*this); return tmp; } bool operator==(const GuessNumberIterator& y) { return i == y.i; } bool operator!=(const GuessNumberIterator& y) { return i != y.i; } int operator*() { std::cout << "Is your number less than or equal to " << i << "? "; std::string s; std::cin >> s; return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1; } GuessNumberIterator& operator--() { --i; return *this; } GuessNumberIterator operator--(int) { GuessNumberIterator tmp = *this; --(*this); return tmp; } GuessNumberIterator& operator+=(int n) { i += n; return *this; } GuessNumberIterator& operator-=(int n) { i -= n; return *this; } GuessNumberIterator operator+(int n) { GuessNumberIterator tmp = *this; return tmp += n; } GuessNumberIterator operator-(int n) { GuessNumberIterator tmp = *this; return tmp -= n; } int operator-(const GuessNumberIterator &y) { return i - y.i; } int operator[](int n) { return *(*this + n); } bool operator<(const GuessNumberIterator &y) { return i < y.i; } bool operator>(const GuessNumberIterator &y) { return i > y.i; } bool operator<=(const GuessNumberIterator &y) { return i <= y.i; } bool operator>=(const GuessNumberIterator &y) { return i >= y.i; } }; inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; } const int lower = 0; const int upper = 100; int main() { std::cout << "Instructions:\n" << "Think of integer number from " << lower << " (inclusive) to " << upper << " (exclusive) and\n" << "I will guess it. After each guess, I will ask you if it is less than\n" << "or equal to some number, and you will respond with \"yes\" or \"no\".\n"; int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i; std::cout << "Your number is " << answer << ".\n"; return 0; }
Port the following code from Python to C++ with equivalent syntax and logic.
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
#include <unordered_map> #include <string> int main() { std::string keys[] = { "1", "2", "3" }; std::string vals[] = { "a", "b", "c" }; std::unordered_map<std::string, std::string> hash; for( int i = 0 ; i < 3 ; i++ ) hash[ keys[i] ] = vals[i] ; }
Write the same code in C++ as shown below in Python.
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> std::vector<int> bins(const std::vector<int>& limits, const std::vector<int>& data) { std::vector<int> result(limits.size() + 1, 0); for (int n : data) { auto i = std::upper_bound(limits.begin(), limits.end(), n); ++result[i - limits.begin()]; } return result; } void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) { size_t n = limits.size(); if (n == 0) return; assert(n + 1 == bins.size()); std::cout << " < " << std::setw(3) << limits[0] << ": " << std::setw(2) << bins[0] << '\n'; for (size_t i = 1; i < n; ++i) std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < " << std::setw(3) << limits[i] << ": " << std::setw(2) << bins[i] << '\n'; std::cout << ">= " << std::setw(3) << limits[n - 1] << "  : " << std::setw(2) << bins[n] << '\n'; } int main() { const std::vector<int> limits1{23, 37, 43, 53, 67, 83}; const std::vector<int> data1{ 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; std::cout << "Example 1:\n"; print_bins(limits1, bins(limits1, data1)); const std::vector<int> limits2{14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const std::vector<int> data2{ 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; std::cout << "\nExample 2:\n"; print_bins(limits2, bins(limits2, data2)); }
Port the following code from Python to C++ with equivalent syntax and logic.
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> std::vector<int> bins(const std::vector<int>& limits, const std::vector<int>& data) { std::vector<int> result(limits.size() + 1, 0); for (int n : data) { auto i = std::upper_bound(limits.begin(), limits.end(), n); ++result[i - limits.begin()]; } return result; } void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) { size_t n = limits.size(); if (n == 0) return; assert(n + 1 == bins.size()); std::cout << " < " << std::setw(3) << limits[0] << ": " << std::setw(2) << bins[0] << '\n'; for (size_t i = 1; i < n; ++i) std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < " << std::setw(3) << limits[i] << ": " << std::setw(2) << bins[i] << '\n'; std::cout << ">= " << std::setw(3) << limits[n - 1] << "  : " << std::setw(2) << bins[n] << '\n'; } int main() { const std::vector<int> limits1{23, 37, 43, 53, 67, 83}; const std::vector<int> data1{ 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; std::cout << "Example 1:\n"; print_bins(limits1, bins(limits1, data1)); const std::vector<int> limits2{14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const std::vector<int> data2{ 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; std::cout << "\nExample 2:\n"; print_bins(limits2, bins(limits2, data2)); }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
def setup(): size(600, 600) background(0) stroke(255) drawTree(300, 550, 9) def drawTree(x, y, depth): fork_ang = radians(20) base_len = 10 if depth > 0: pushMatrix() translate(x, y - baseLen * depth) line(0, baseLen * depth, 0, 0) rotate(fork_ang) drawTree(0, 0, depth - 1) rotate(2 * -fork_ang) drawTree(0, 0, depth - 1) popMatrix()
#include <windows.h> #include <string> #include <math.h> using namespace std; const float PI = 3.1415926536f; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; void *pBits; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file; GetObject( bmp, sizeof( bitmap ), &bitmap ); dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() { return hdc; } int getWidth() { return width; } int getHeight() { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; int width, height; }; class vector2 { public: vector2() { x = y = 0; } vector2( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { float _x = static_cast<float>( x ), _y = static_cast<float>( y ), s = sinf( angle_r ), c = cosf( angle_r ), a = _x * c - _y * s, b = _x * s + _y * c; x = static_cast<int>( a ); y = static_cast<int>( b ); } int x, y; }; class fractalTree { public: fractalTree() { _ang = DegToRadian( 24.0f ); } float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } void create( myBitmap* bmp ) { _bmp = bmp; float line_len = 130.0f; vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 ); MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL ); sp.y -= static_cast<int>( line_len ); LineTo( _bmp->getDC(), sp.x, sp.y); drawRL( &sp, line_len, 0, true ); drawRL( &sp, line_len, 0, false ); } private: void drawRL( vector2* sp, float line_len, float a, bool rg ) { line_len *= .75f; if( line_len < 2.0f ) return; MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL ); vector2 r( 0, static_cast<int>( line_len ) ); if( rg ) a -= _ang; else a += _ang; r.rotate( a ); r.x += sp->x; r.y = sp->y - r.y; LineTo( _bmp->getDC(), r.x, r.y ); drawRL( &r, line_len, a, true ); drawRL( &r, line_len, a, false ); } myBitmap* _bmp; float _ang; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); myBitmap bmp; bmp.create( 640, 512 ); bmp.setPenColor( RGB( 255, 255, 0 ) ); fractalTree tree; tree.create( &bmp ); BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY ); bmp.saveBitmap( "f: system( "pause" ); return 0; }
Keep all operations the same but rewrite the snippet in C++.
from turtle import * colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"] screen = getscreen() left_edge = -screen.window_width()//2 right_edge = screen.window_width()//2 quarter_height = screen.window_height()//4 half_height = quarter_height * 2 speed("fastest") for quarter in range(4): pensize(quarter+1) colornum = 0 min_y = half_height - ((quarter + 1) * quarter_height) max_y = half_height - ((quarter) * quarter_height) for x in range(left_edge,right_edge,quarter+1): penup() pencolor(colors[colornum]) colornum = (colornum + 1) % len(colors) setposition(x,min_y) pendown() setposition(x,max_y) notused = input("Hit enter to continue: ")
#include <windows.h> class pinstripe { public: pinstripe() { createColors(); } void setDimensions( int x, int y ) { _mw = x; _mh = y; } void createColors() { colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 ); colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); colors[7] = RGB( 255, 255, 255 ); } void draw( HDC dc ) { HPEN pen; int lh = _mh / 4, row, cp; for( int lw = 1; lw < 5; lw++ ) { cp = 0; row = ( lw - 1 ) * lh; for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw ) { pen = CreatePen( PS_SOLID, lw, colors[cp] ); ++cp %= 8; SelectObject( dc, pen ); MoveToEx( dc, x, row, NULL ); LineTo( dc, x, row + lh ); DeleteObject( pen ); } } } private: int _mw, _mh; DWORD colors[8]; }; pinstripe pin; void PaintWnd( HWND hWnd ) { PAINTSTRUCT ps; HDC hdc = BeginPaint( hWnd, &ps ); pin.draw( hdc ); EndPaint( hWnd, &ps ); } LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_PAINT: PaintWnd( hWnd ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll( HINSTANCE hInstance ) { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_CLR_PS_"; RegisterClassEx( &wcex ); return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL ); } int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); HWND hwnd = InitAll( hInstance ); if( !hwnd ) return -1; int mw = GetSystemMetrics( SM_CXSCREEN ), mh = GetSystemMetrics( SM_CYSCREEN ); pin.setDimensions( mw, mh ); RECT rc = { 0, 0, mw, mh }; AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 ); int w = rc.right - rc.left, h = rc.bottom - rc.top; int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ), posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 ); SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER ); ShowWindow( hwnd, nCmdShow ); UpdateWindow( hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_CLR_PS_", hInstance ); }
Preserve the algorithm and functionality while converting the code from Python to C++.
from datetime import date from calendar import isleap def weekday(d): days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dooms = [ [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] ] c = d.year // 100 r = d.year % 100 s = r // 12 t = r % 12 c_anchor = (5 * (c % 4) + 2) % 7 doomsday = (s + t + (t // 4) + c_anchor) % 7 anchorday = dooms[isleap(d.year)][d.month - 1] weekday = (doomsday + d.day - anchorday + 7) % 7 return days[weekday] dates = [date(*x) for x in [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)] ] for d in dates: tense = "was" if d < date.today() else "is" if d == date.today() else "will be" print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const std::string days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned const c = date.year/100, r = date.year%100; unsigned const s = r/12, t = r%12; unsigned const c_anchor = (5 * (c%4) + 2) % 7; unsigned const doom = (s + t + t/4 + c_anchor) % 7; unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const std::string months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; for (const Date& d : dates) { std::cout << months[d.month] << " " << (int)d.day << ", " << d.year; std::cout << (d.year > 2021 ? " will be " : " was "); std::cout << "on a " << weekday(d) << std::endl; } return 0; }
Write a version of this Python function in C++ with identical behavior.
from datetime import date from calendar import isleap def weekday(d): days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dooms = [ [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] ] c = d.year // 100 r = d.year % 100 s = r // 12 t = r % 12 c_anchor = (5 * (c % 4) + 2) % 7 doomsday = (s + t + (t // 4) + c_anchor) % 7 anchorday = dooms[isleap(d.year)][d.month - 1] weekday = (doomsday + d.day - anchorday + 7) % 7 return days[weekday] dates = [date(*x) for x in [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)] ] for d in dates: tense = "was" if d < date.today() else "is" if d == date.today() else "will be" print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const std::string days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned const c = date.year/100, r = date.year%100; unsigned const s = r/12, t = r%12; unsigned const c_anchor = (5 * (c%4) + 2) % 7; unsigned const doom = (s + t + t/4 + c_anchor) % 7; unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const std::string months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; for (const Date& d : dates) { std::cout << months[d.month] << " " << (int)d.day << ", " << d.year; std::cout << (d.year > 2021 ? " will be " : " was "); std::cout << "on a " << weekday(d) << std::endl; } return 0; }
Generate an equivalent C++ version of this Python code.
def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1 while beginIdx <= endIdx: newBeginIdx = endIdx newEndIdx = beginIdx for ii in range(beginIdx,endIdx): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newEndIdx = ii endIdx = newEndIdx for ii in range(endIdx,beginIdx-1,-1): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newBeginIdx = ii beginIdx = newBeginIdx + 1 test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] cocktailshiftingbounds(test1) print(test1) test2=list('big fjords vex quick waltz nymph') cocktailshiftingbounds(test2) print(''.join(test2))
#include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <vector> template <typename iterator> void cocktail_shaker_sort(iterator begin, iterator end) { if (begin == end) return; for (--end; begin < end; ) { iterator new_begin = end; iterator new_end = begin; for (iterator i = begin; i < end; ++i) { iterator j = i + 1; if (*j < *i) { std::iter_swap(i, j); new_end = i; } } end = new_end; for (iterator i = end; i > begin; --i) { iterator j = i - 1; if (*i < *j) { std::iter_swap(i, j); new_begin = i; } } begin = new_begin; } } template <typename iterator> void print(iterator begin, iterator end) { if (begin == end) return; std::cout << *begin++; while (begin != end) std::cout << ' ' << *begin++; std::cout << '\n'; } int main() { std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15}; std::cout << "before: "; print(v.begin(), v.end()); cocktail_shaker_sort(v.begin(), v.end()); assert(std::is_sorted(v.begin(), v.end())); std::cout << "after: "; print(v.begin(), v.end()); return 0; }
Write the same algorithm in C++ as shown in this Python implementation.
import pygame, sys from pygame.locals import * from math import sin, cos, radians pygame.init() WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15 window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum") screen = pygame.display.get_surface() screen.fill((255,255,255)) PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4 class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw() def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2) firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0 midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2 midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1) def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw() bob = BobMass() TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK) def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update() while True: input(pygame.event.get()) pygame.display.flip()
#ifndef __wxPendulumDlg_h__ #define __wxPendulumDlg_h__ #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include <wx/wx.h> #include <wx/dialog.h> #else #include <wx/wxprec.h> #endif #include <wx/timer.h> #include <wx/dcbuffer.h> #include <cmath> class wxPendulumDlgApp : public wxApp { public: bool OnInit(); int OnExit(); }; class wxPendulumDlg : public wxDialog { public: wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX); virtual ~wxPendulumDlg(); void wxPendulumDlgPaint(wxPaintEvent& event); void wxPendulumDlgSize(wxSizeEvent& event); void OnTimer(wxTimerEvent& event); private: wxTimer *m_timer; unsigned int m_uiLength; double m_Angle; double m_AngleVelocity; enum wxIDs { ID_WXTIMER1 = 1001, ID_DUMMY_VALUE_ }; void OnClose(wxCloseEvent& event); void CreateGUIControls(); DECLARE_EVENT_TABLE() }; #endif
Rewrite the snippet below in C++ so it works the same as the original Python code.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
Translate this program into C++ but keep the logic exactly as in Python.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
Rewrite the snippet below in C++ so it works the same as the original Python code.
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
#include <iostream> #include <fstream> #if defined(_WIN32) || defined(WIN32) constexpr auto FILENAME = "tape.file"; #else constexpr auto FILENAME = "/dev/tape"; #endif int main() { std::filebuf fb; fb.open(FILENAME,std::ios::out); std::ostream os(&fb); os << "Hello World\n"; fb.close(); return 0; }
Write a version of this Python function in C++ with identical behavior.
def heapsort(lst): for start in range((len(lst)-2)/2, -1, -1): siftdown(lst, start, len(lst)-1) for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] siftdown(lst, 0, end - 1) return lst def siftdown(lst, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] root = child else: break
#include <algorithm> #include <iterator> #include <iostream> template<typename RandomAccessIterator> void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) { std::make_heap(begin, end); std::sort_heap(begin, end); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; heap_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Convert this Python block to C++, preserving its control flow and logic.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
Produce a language-to-language conversion: from Python to C++, same semantics.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
array = [] array.append(1) array.append(3) array[0] = 2 print array[0]
#include <array> #include <vector> #include <algorithm> #include <iostream> #include <iterator> #include <string> template <typename Array> void demonstrate(Array& array) { array[2] = "Three"; array.at(1) = "Two"; std::reverse(begin(array), end(array)); std::for_each(begin(array), end(array), [](typename Array::value_type const& element) { std::cout << element << ' '; }); std::cout << '\n'; } int main() { auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" }; auto dynamic_array = std::vector<std::string>{ "One", "Four" }; dynamic_array.push_back("Eight"); demonstrate(fixed_size_array); demonstrate(dynamic_array); }
Produce a language-to-language conversion: from Python to C++, same semantics.
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
#include <cstdint> #include <cstdlib> #include <cstdio> static constexpr int32_t bct_low_bits = 0x55555555; static int32_t bct_decrement(int32_t v) { --v; return v ^ (v & (v>>1) & bct_low_bits); } int main (int argc, char *argv[]) { const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3; if (n < 0 || 9 < n) { std::printf("N out of range (use 0..9): %ld\n", long(n)); return 1; } const int32_t size_bct = 1<<(n*2); int32_t y = size_bct; do { y = bct_decrement(y); int32_t x = size_bct; do { x = bct_decrement(x); std::putchar((x & y & bct_low_bits) ? ' ' : '#'); } while (0 < x); std::putchar('\n'); } while (0 < y); return 0; }
Change the programming language of this snippet from Python to C++ without modifying what it does.
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
#include <algorithm> #include <iostream> #include <iterator> #include <random> template <typename RandomAccessIterator, typename Predicate> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end, Predicate p) { std::random_device rd; std::mt19937 generator(rd()); while (!std::is_sorted(begin, end, p)) { std::shuffle(begin, end, generator); } } template <typename RandomAccessIterator> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) { bogo_sort( begin, end, std::less< typename std::iterator_traits<RandomAccessIterator>::value_type>()); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bogo_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Generate an equivalent C++ version of this Python code.
import pandas as pd df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".") df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".") df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE']) df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left') df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False) df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']}) print(df_result)
#include <iostream> #include <optional> #include <ranges> #include <string> #include <vector> using namespace std; struct Patient { string ID; string LastName; }; struct Visit { string PatientID; string Date; optional<float> Score; }; int main(void) { auto patients = vector<Patient> { {"1001", "Hopper"}, {"4004", "Wirth"}, {"3003", "Kemeny"}, {"2002", "Gosling"}, {"5005", "Kurtz"}}; auto visits = vector<Visit> { {"2002", "2020-09-10", 6.8}, {"1001", "2020-09-17", 5.5}, {"4004", "2020-09-24", 8.4}, {"2002", "2020-10-08", }, {"1001", "" , 6.6}, {"3003", "2020-11-12", }, {"4004", "2020-11-05", 7.0}, {"1001", "2020-11-19", 5.3}}; sort(patients.begin(), patients.end(), [](const auto& a, const auto&b){ return a.ID < b.ID;}); cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n"; for(const auto& patient : patients) { string lastVisit; float sum = 0; int numScores = 0; auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;}; for(const auto& visit : visits | views::filter( patientFilter )) { if(visit.Score) { sum += *visit.Score; numScores++; } lastVisit = max(lastVisit, visit.Date); } cout << "| " << patient.ID << " | "; cout.width(8); cout << patient.LastName << " | "; cout.width(10); cout << lastVisit << " | "; if(numScores > 0) { cout.width(9); cout << sum << " | "; cout.width(9); cout << (sum / float(numScores)); } else cout << " | "; cout << " |\n"; } }
Convert this Python block to C++, preserving its control flow and logic.
def euler(f,y0,a,b,h): t,y = a,y0 while t <= b: print "%6.3f %6.3f" % (t,y) t += h y += h * f(t,y) def newtoncooling(time, temp): return -0.07 * (temp - 20) euler(newtoncooling,100,0,100,10)
#include <iomanip> #include <iostream> typedef double F(double,double); void euler(F f, double y0, double a, double b, double h) { double y = y0; for (double t = a; t < b; t += h) { std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n"; y += h * f(t, y); } std::cout << "done\n"; } double newtonCoolingLaw(double, double t) { return -0.07 * (t - 20); } int main() { euler(newtonCoolingLaw, 100, 0, 100, 2); euler(newtonCoolingLaw, 100, 0, 100, 5); euler(newtonCoolingLaw, 100, 0, 100, 10); }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <boost/bind.hpp> #include <iterator> double nextNumber( double number ) { return number + floor( 0.5 + sqrt( number ) ) ; } int main( ) { std::vector<double> non_squares ; typedef std::vector<double>::iterator SVI ; non_squares.reserve( 1000000 ) ; for ( double i = 1.0 ; i < 100001.0 ; i += 1 ) non_squares.push_back( nextNumber( i ) ) ; std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 , std::ostream_iterator<double>(std::cout, " " ) ) ; std::cout << '\n' ; SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) , boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ; if ( found != non_squares.end( ) ) { std::cout << "Found a square number in the sequence!\n" ; std::cout << "It is " << *found << " !\n" ; } else { std::cout << "Up to 1000000, found no square number in the sequence!\n" ; } return 0 ; }
Produce a language-to-language conversion: from Python to C++, same semantics.
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
#include <iostream> #include <string> int main() { std::string s = "0123456789"; int const n = 3; int const m = 4; char const c = '2'; std::string const sub = "456"; std::cout << s.substr(n, m)<< "\n"; std::cout << s.substr(n) << "\n"; std::cout << s.substr(0, s.size()-1) << "\n"; std::cout << s.substr(s.find(c), m) << "\n"; std::cout << s.substr(s.find(sub), m) << "\n"; }
Port the provided Python code into C++ while preserving the original functionality.
>>> def jortsort(sequence): return list(sequence) == sorted(sequence) >>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']: print(f'jortsort({repr(data)}) is {jortsort(data)}') jortsort((1, 2, 4, 3)) is False jortsort((14, 6, 8)) is False jortsort(['a', 'c']) is True jortsort(['s', 'u', 'x']) is True jortsort('CVGH') is False jortsort('PQRST') is True >>>
#include <algorithm> #include <string> #include <iostream> #include <iterator> class jortSort { public: template<class T> bool jort_sort( T* o, size_t s ) { T* n = copy_array( o, s ); sort_array( n, s ); bool r = false; if( n ) { r = check( o, n, s ); delete [] n; } return r; } private: template<class T> T* copy_array( T* o, size_t s ) { T* z = new T[s]; memcpy( z, o, s * sizeof( T ) ); return z; } template<class T> void sort_array( T* n, size_t s ) { std::sort( n, n + s ); } template<class T> bool check( T* n, T* o, size_t s ) { for( size_t x = 0; x < s; x++ ) if( n[x] != o[x] ) return false; return true; } }; jortSort js; template<class T> void displayTest( T* o, size_t s ) { std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) ); std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n"; } int main( int argc, char* argv[] ) { const size_t s = 5; std::string oStr[] = { "5", "A", "D", "R", "S" }; displayTest( oStr, s ); std::swap( oStr[0], oStr[1] ); displayTest( oStr, s ); int oInt[] = { 1, 2, 3, 4, 5 }; displayTest( oInt, s ); std::swap( oInt[0], oInt[1] ); displayTest( oInt, s ); return 0; }
Convert this Python snippet to C++ and keep its semantics consistent.
import calendar calendar.isleap(year)
#include <iostream> bool is_leap_year(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } int main() { for (auto year : {1900, 1994, 1996, 1997, 2000}) { std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n"; } }
Keep all operations the same but rewrite the snippet in C++.
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n') print('\n\nSample Combs 10..60') for N in range(10, 61, 10): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n') exact=False print('\n\nSample Perms 5..1500 Using FP approximations') for N in [5, 15, 150, 1500, 15000]: k = N-2 print('%iP%i =' % (N, k), perm(N, k, exact)) print('\nSample Combs 100..1000 Using FP approximations') for N in range(100, 1001, 100): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact))
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return r; } int main() { for (uint i = 1u; i < 12u; i++) std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl; for (uint i = 10u; i < 60u; i += 10u) std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl; return 0; }
Port the provided Python code into C++ while preserving the original functionality.
n=13 print(sorted(range(1,n+1), key=str))
#include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> void lexicographical_sort(std::vector<int>& numbers) { std::vector<std::string> strings(numbers.size()); std::transform(numbers.begin(), numbers.end(), strings.begin(), [](int i) { return std::to_string(i); }); std::sort(strings.begin(), strings.end()); std::transform(strings.begin(), strings.end(), numbers.begin(), [](const std::string& s) { return std::stoi(s); }); } std::vector<int> lexicographically_sorted_vector(int n) { std::vector<int> numbers(n >= 1 ? n : 2 - n); std::iota(numbers.begin(), numbers.end(), std::min(1, n)); lexicographical_sort(numbers); return numbers; } template <typename T> void print_vector(std::ostream& out, const std::vector<T>& v) { out << '['; if (!v.empty()) { auto i = v.begin(); out << *i++; for (; i != v.end(); ++i) out << ',' << *i; } out << "]\n"; } int main(int argc, char** argv) { for (int i : { 0, 5, 13, 21, -22 }) { std::cout << i << ": "; print_vector(std::cout, lexicographically_sorted_vector(i)); } return 0; }
Please provide an equivalent version of this Python code in C++.
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) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
#include <string> #include <iostream> using std::string; const char* smallNumbers[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string spellHundreds(unsigned n) { string res; if (n > 99) { res = smallNumbers[n/100]; res += " hundred"; n %= 100; if (n) res += " and "; } if (n >= 20) { static const char* Decades[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; res += Decades[n/10]; n %= 10; if (n) res += "-"; } if (n < 20 && n > 0) res += smallNumbers[n]; return res; } const char* thousandPowers[] = { " billion", " million", " thousand", "" }; typedef unsigned long Spellable; string spell(Spellable n) { if (n < 20) return smallNumbers[n]; string res; const char** pScaleName = thousandPowers; Spellable scaleFactor = 1000000000; while (scaleFactor > 0) { if (n >= scaleFactor) { Spellable h = n / scaleFactor; res += spellHundreds(h) + *pScaleName; n %= scaleFactor; if (n) res += ", "; } scaleFactor /= 1000; ++pScaleName; } return res; } int main() { #define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl; SPELL_IT( 99); SPELL_IT( 300); SPELL_IT( 310); SPELL_IT( 1501); SPELL_IT( 12609); SPELL_IT( 512609); SPELL_IT(43112609); SPELL_IT(1234567890); return 0; }
Convert this Python snippet to C++ and keep its semantics consistent.
A = 'I am string' B = 'I am string too' if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
#include <iostream> #include <algorithm> #include <string> #include <list> using namespace std; bool cmp(const string& a, const string& b) { return b.length() < a.length(); } void compareAndReportStringsLength(list<string> listOfStrings) { if (!listOfStrings.empty()) { char Q = '"'; string has_length(" has length "); string predicate_max(" and is the longest string"); string predicate_min(" and is the shortest string"); string predicate_ave(" and is neither the longest nor the shortest string"); list<string> ls(listOfStrings); ls.sort(cmp); int max = ls.front().length(); int min = ls.back().length(); for (list<string>::iterator s = ls.begin(); s != ls.end(); s++) { int length = s->length(); string* predicate; if (length == max) predicate = &predicate_max; else if (length == min) predicate = &predicate_min; else predicate = &predicate_ave; cout << Q << *s << Q << has_length << length << *predicate << endl; } } } int main(int argc, char* argv[]) { list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(listOfStrings); return EXIT_SUCCESS; }
Rewrite the snippet below in C++ so it works the same as the original Python code.
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
#include <time.h> #include <iostream> using namespace std; const int MAX = 126; class shell { public: shell() { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; } void sort( int* a, int count ) { _cnt = count; for( int x = 0; x < 9; x++ ) if( count > _gap[x] ) { _idx = x; break; } sortIt( a ); } private: void sortIt( int* arr ) { bool sorted = false; while( true ) { sorted = true; int st = 0; for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] ) { if( arr[st] > arr[x] ) { swap( arr[st], arr[x] ); sorted = false; } st = x; } if( ++_idx >= 8 ) _idx = 8; if( sorted && _idx == 8 ) break; } } void swap( int& a, int& b ) { int t = a; a = b; b = t; } int _gap[9], _idx, _cnt; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX]; for( int x = 0; x < MAX; x++ ) arr[x] = rand() % MAX - rand() % MAX; cout << " Before: \n=========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl; shell s; s.sort( arr, MAX ); cout << " After: \n========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl << endl; return system( "pause" ); }
Preserve the algorithm and functionality while converting the code from Python to C++.
from collections import deque some_list = deque(["a", "b", "c"]) print(some_list) some_list.appendleft("Z") print(some_list) for value in reversed(some_list): print(value)
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); numbers.insert(numbers.end(), 4); auto it = std::next(numbers.begin(), numbers.size() / 2); numbers.insert(it, 6); for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Convert this Python snippet to C++ and keep its semantics consistent.
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
#include <fstream> #include <iostream> int main() { std::ifstream input("filename.txt", std::ios_base::binary); if (!input) { std::cerr << "error: can't open file\n"; return -1; } size_t count[256]; std::fill_n(count, 256, 0); for (char c; input.get(c); ++count[uint8_t(c)]) ; for (size_t i = 0; i < 256; ++i) { if (count[i] && isgraph(i)) { std::cout << char(i) << " = " << count[i] << '\n'; } } }
Ensure the translated C++ code behaves exactly like the original Python snippet.
from itertools import combinations as comb def statistic(ab, a): sumab, suma = sum(ab), sum(a) return ( suma / len(a) - (sumab -suma) / (len(ab) - len(a)) ) def permutationTest(a, b): ab = a + b Tobs = statistic(ab, a) under = 0 for count, perm in enumerate(comb(ab, len(a)), 1): if statistic(ab, perm) <= Tobs: under += 1 return under * 100. / count treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] under = permutationTest(treatmentGroup, controlGroup) print("under=%.2f%%, over=%.2f%%" % (under, 100. - under))
#include<iostream> #include<vector> #include<numeric> #include<functional> class { public: int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);} private: int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); } int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);} }combinations; int main() { static constexpr int treatment = 9; const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 }; int treated = std::accumulate(data.begin(), data.begin() + treatment, 0); std::function<int (int, int, int)> pick; pick = [&](int n, int from, int accumulated) { if(n == 0) return accumulated > treated ? 1 : 0; else return pick(n - 1, from - 1, accumulated + data[from - 1]) + (from > n ? pick(n, from - 1, accumulated) : 0); }; int total = combinations(data.size(), treatment); int greater = pick(treatment, data.size(), 0); int lesser = total - greater; std::cout << "<= : " << 100.0 * lesser / total << "% " << lesser << std::endl << " > : " << 100.0 * greater / total << "% " << greater << std::endl; }
Change the programming language of this snippet from Python to C++ without modifying what it does.
def isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (i * i <= n and n % i == 0) : return False return True def mobius(N) : if (N == 1) : return 1 p = 0 for i in range(1, N + 1) : if (N % i == 0 and isPrime(i)) : if (N % (i * i) == 0) : return 0 else : p = p + 1 if(p % 2 != 0) : return -1 else : return 1 print("Mobius numbers from 1..99:") for i in range(1, 100): print(f"{mobius(i):>4}", end = '') if i % 20 == 0: print()
#include <iomanip> #include <iostream> #include <vector> constexpr int MU_MAX = 1'000'000; std::vector<int> MU; int mobiusFunction(int n) { if (!MU.empty()) { return MU[n]; } MU.resize(MU_MAX + 1, 1); int root = sqrt(MU_MAX); for (int i = 2; i <= root; i++) { if (MU[i] == 1) { for (int j = i; j <= MU_MAX; j += i) { MU[j] *= -i; } for (int j = i * i; j <= MU_MAX; j += i * i) { MU[j] = 0; } } } for (int i = 2; i <= MU_MAX; i++) { if (MU[i] == i) { MU[i] = 1; } else if (MU[i] == -i) { MU[i] = -1; } else if (MU[i] < 0) { MU[i] = 1; } else if (MU[i] > 0) { MU[i] = -1; } } return MU[n]; } int main() { std::cout << "First 199 terms of the möbius function are as follows:\n "; for (int n = 1; n < 200; n++) { std::cout << std::setw(2) << mobiusFunction(n) << " "; if ((n + 1) % 20 == 0) { std::cout << '\n'; } } return 0; }
Port the following code from Python to C++ with equivalent syntax and logic.
next = str(int('123') + 1)
#include <cstdlib> #include <string> #include <sstream> std::string s = "12345"; int i; std::istringstream(s) >> i; i++; std::ostringstream oss; if (oss << i) s = oss.str();
Translate this program into C++ but keep the logic exactly as in Python.
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
#include <algorithm> #include <iostream> #include <string> std::string stripchars(std::string str, const std::string &chars) { str.erase( std::remove_if(str.begin(), str.end(), [&](char c){ return chars.find(c) != std::string::npos; }), str.end() ); return str; } int main() { std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; return 0; }
Produce a functionally identical C++ code for the snippet given in Python.
from itertools import permutations in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
#include <algorithm> template<typename ForwardIterator> void permutation_sort(ForwardIterator begin, ForwardIterator end) { while (std::next_permutation(begin, end)) { } }
Translate this program into C++ but keep the logic exactly as in Python.
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
#include <vector> double mean(const std::vector<double>& numbers) { if (numbers.size() == 0) return 0; double sum = 0; for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++) sum += *i; return sum / numbers.size(); }
Translate the given Python code snippet into C++ without altering its behavior.
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Produce a functionally identical C++ code for the snippet given in Python.
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Write the same code in C++ as shown below in Python.
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> double log2( double number ) { return log( number ) / log( 2 ) ; } int main( int argc , char *argv[ ] ) { std::string teststring( argv[ 1 ] ) ; std::map<char , int> frequencies ; for ( char c : teststring ) frequencies[ c ] ++ ; int numlen = teststring.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent -= freq * log2( freq ) ; } std::cout << "The information content of " << teststring << " is " << infocontent << std::endl ; return 0 ; }
Maintain the same structure and functionality when rewriting this code in C++.
def token_with_escape(a, escape = '^', separator = '|'): result = [] token = '' state = 0 for c in a: if state == 0: if c == escape: state = 1 elif c == separator: result.append(token) token = '' else: token += c elif state == 1: token += c state = 0 result.append(token) return result
#include <iostream> #include <stdexcept> #include <string> #include <vector> using namespace std; vector<string> tokenize(const string& input, char seperator, char escape) { vector<string> output; string token; bool inEsc = false; for (char ch : input) { if (inEsc) { inEsc = false; } else if (ch == escape) { inEsc = true; continue; } else if (ch == seperator) { output.push_back(token); token = ""; continue; } token += ch; } if (inEsc) throw new invalid_argument("Invalid terminal escape"); output.push_back(token); return output; } int main() { string sample = "one^|uno||three^^^^|four^^^|^cuatro|"; cout << sample << endl; cout << '['; for (auto t : tokenize(sample, '|', '^')) { cout << '"' << t << "\", "; } cout << ']' << endl; return 0; }
Convert the following code from Python to C++, ensuring the logic remains intact.
print "Hello world!"
#include <iostream> int main () { std::cout << "Hello world!" << std::endl; }
Convert this Python block to C++, preserving its control flow and logic.
LIMIT = 1_000_035 def primes2(limit=LIMIT): if limit < 2: return [] if limit < 3: return [2] lmtbf = (limit - 3) // 2 buf = [True] * (lmtbf + 1) for i in range((int(limit ** 0.5) - 3) // 2 + 1): if buf[i]: p = i + i + 3 s = p * (i + 1) + i buf[s::p] = [False] * ((lmtbf - s) // p + 1) return [2] + [i + i + 3 for i, v in enumerate(buf) if v] primes = primes2(LIMIT +6) primeset = set(primes) primearray = [n in primeset for n in range(LIMIT)] s = [[] for x in range(4)] unsexy = [] for p in primes: if p > LIMIT: break if p + 6 in primeset and p + 6 < LIMIT: s[0].append((p, p+6)) elif p + 6 in primeset: break else: if p - 6 not in primeset: unsexy.append(p) continue if p + 12 in primeset and p + 12 < LIMIT: s[1].append((p, p+6, p+12)) else: continue if p + 18 in primeset and p + 18 < LIMIT: s[2].append((p, p+6, p+12, p+18)) else: continue if p + 24 in primeset and p + 24 < LIMIT: s[3].append((p, p+6, p+12, p+18, p+24)) print('"SEXY" PRIME GROUPINGS:') for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()): print(f' {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn "" let ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...') for sx in sexy[-5:]: print(' ',sx) print(f'\nThere are {len(unsexy)} unsexy primes ending with ...') for usx in unsexy[-10:]: print(' ',usx)
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_size = 5; const int diff = 6; const int array_size = max + diff; const int max_groups = 5; const int max_unsexy = 10; prime_sieve sieve(array_size); std::array<int, max_group_size> group_count{0}; vector<group_buffer> groups(max_group_size, group_buffer(max_groups)); int unsexy_count = 0; circular_buffer<int> unsexy_primes(max_unsexy); vector<int> group; for (int p = 2; p < max; ++p) { if (!sieve.is_prime(p)) continue; if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) { ++unsexy_count; unsexy_primes.push_back(p); } else { group.clear(); group.push_back(p); for (int group_size = 1; group_size < max_group_size; group_size++) { int next_p = p + group_size * diff; if (next_p >= max || !sieve.is_prime(next_p)) break; group.push_back(next_p); ++group_count[group_size]; groups[group_size].push_back(group); } } } for (int size = 1; size < max_group_size; ++size) { cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n'; cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":"; for (const vector<int>& group : groups[size]) { cout << " ("; for (size_t i = 0; i < group.size(); ++i) { if (i > 0) cout << ' '; cout << group[i]; } cout << ")"; } cout << "\n\n"; } cout << "number of unsexy primes is " << unsexy_count << '\n'; cout << "last " << unsexy_primes.size() << " unsexy primes:"; for (int prime : unsexy_primes) cout << ' ' << prime; cout << '\n'; return 0; }
Write the same algorithm in C++ as shown in this Python implementation.
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
Translate the given Python code snippet into C++ without altering its behavior.
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }