Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"fmt"
"math"
"rcu"
"time"
)
var count []int
func primeCounter(limit int) {
count = make([]int, limit)
for i := 0; i < limit; i++ {
count[i] = 1
}
if limit > 0 {
count[0] = 0
}
if limit > 1 {
count[1] = 0
}
for i := 4; i < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
| #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_counter(int limit) : count_(limit, 1) {
if (limit > 0)
count_[0] = 0;
if (limit > 1)
count_[1] = 0;
for (int i = 4; i < limit; i += 2)
count_[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count_[p]) {
for (int q = sq; q < limit; q += p << 1)
count_[q] = 0;
}
sq += (p + 1) << 2;
}
std::partial_sum(count_.begin(), count_.end(), count_.begin());
}
int ramanujan_max(int n) {
return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}
int ramanujan_prime(const prime_counter& pc, int n) {
int max = ramanujan_max(n);
for (int i = max; i >= 0; --i) {
if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
return i + 1;
}
return 0;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
prime_counter pc(1 + ramanujan_max(100000));
for (int i = 1; i <= 100; ++i) {
std::cout << std::setw(5) << ramanujan_prime(pc, i)
<< (i % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (int n = 1000; n <= 100000; n *= 10) {
std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
<< ".\n";
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\nElapsed time: "
<< std::chrono::duration<double>(end - start).count() * 1000
<< " milliseconds\n";
}
|
Write a version of this Go function in C++ with identical behavior. | package main
import (
"fmt"
"math"
"rcu"
"time"
)
var count []int
func primeCounter(limit int) {
count = make([]int, limit)
for i := 0; i < limit; i++ {
count[i] = 1
}
if limit > 0 {
count[0] = 0
}
if limit > 1 {
count[1] = 0
}
for i := 4; i < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
| #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_counter(int limit) : count_(limit, 1) {
if (limit > 0)
count_[0] = 0;
if (limit > 1)
count_[1] = 0;
for (int i = 4; i < limit; i += 2)
count_[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count_[p]) {
for (int q = sq; q < limit; q += p << 1)
count_[q] = 0;
}
sq += (p + 1) << 2;
}
std::partial_sum(count_.begin(), count_.end(), count_.begin());
}
int ramanujan_max(int n) {
return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}
int ramanujan_prime(const prime_counter& pc, int n) {
int max = ramanujan_max(n);
for (int i = max; i >= 0; --i) {
if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
return i + 1;
}
return 0;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
prime_counter pc(1 + ramanujan_max(100000));
for (int i = 1; i <= 100; ++i) {
std::cout << std::setw(5) << ramanujan_prime(pc, i)
<< (i % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (int n = 1000; n <= 100000; n *= 10) {
std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
<< ".\n";
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\nElapsed time: "
<< std::chrono::duration<double>(end - start).count() * 1000
<< " milliseconds\n";
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"math"
"rcu"
"time"
)
var count []int
func primeCounter(limit int) {
count = make([]int, limit)
for i := 0; i < limit; i++ {
count[i] = 1
}
if limit > 0 {
count[0] = 0
}
if limit > 1 {
count[1] = 0
}
for i := 4; i < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
| #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_counter(int limit) : count_(limit, 1) {
if (limit > 0)
count_[0] = 0;
if (limit > 1)
count_[1] = 0;
for (int i = 4; i < limit; i += 2)
count_[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count_[p]) {
for (int q = sq; q < limit; q += p << 1)
count_[q] = 0;
}
sq += (p + 1) << 2;
}
std::partial_sum(count_.begin(), count_.end(), count_.begin());
}
int ramanujan_max(int n) {
return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}
int ramanujan_prime(const prime_counter& pc, int n) {
int max = ramanujan_max(n);
for (int i = max; i >= 0; --i) {
if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
return i + 1;
}
return 0;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
prime_counter pc(1 + ramanujan_max(100000));
for (int i = 1; i <= 100; ++i) {
std::cout << std::setw(5) << ramanujan_prime(pc, i)
<< (i % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (int n = 1000; n <= 100000; n *= 10) {
std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
<< ".\n";
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\nElapsed time: "
<< std::chrono::duration<double>(end - start).count() * 1000
<< " milliseconds\n";
}
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
| #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
}
auto perfect_powers(uint128_t n) {
std::vector<uint128_t> result;
for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)
for (uint128_t p = i * i; p < n; p *= i)
result.push_back(p);
unique_sort(result);
return result;
}
auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {
std::vector<uint128_t> result;
auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));
auto s = sqrt(to / 8);
for (uint128_t b = 2; b <= c; ++b) {
uint128_t b3 = b * b * b;
for (uint128_t a = 2; a <= s; ++a) {
uint128_t p = b3 * a * a;
if (p >= to)
break;
if (p >= from && !binary_search(pps.begin(), pps.end(), p))
result.push_back(p);
}
}
unique_sort(result);
return result;
}
uint128_t totient(uint128_t n) {
uint128_t tot = n;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
tot -= tot >> 1;
}
for (uint128_t p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
tot -= tot / p;
}
}
if (n > 1)
tot -= tot / n;
return tot;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
const uint128_t limit = 1000000000000000;
auto pps = perfect_powers(limit);
auto ach = achilles(1, 1000000, pps);
std::cout << "First 50 Achilles numbers:\n";
for (size_t i = 0; i < 50 && i < ach.size(); ++i)
std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' ');
std::cout << "\nFirst 50 strong Achilles numbers:\n";
for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)
if (binary_search(ach.begin(), ach.end(), totient(ach[i])))
std::cout << std::setw(6) << ach[i]
<< (++count % 10 == 0 ? '\n' : ' ');
int digits = 2;
std::cout << "\nNumber of Achilles numbers with:\n";
for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {
size_t count = achilles(from, to, pps).size();
std::cout << std::setw(2) << digits << " digits: " << count << '\n';
from = to;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
| #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
}
auto perfect_powers(uint128_t n) {
std::vector<uint128_t> result;
for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)
for (uint128_t p = i * i; p < n; p *= i)
result.push_back(p);
unique_sort(result);
return result;
}
auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {
std::vector<uint128_t> result;
auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));
auto s = sqrt(to / 8);
for (uint128_t b = 2; b <= c; ++b) {
uint128_t b3 = b * b * b;
for (uint128_t a = 2; a <= s; ++a) {
uint128_t p = b3 * a * a;
if (p >= to)
break;
if (p >= from && !binary_search(pps.begin(), pps.end(), p))
result.push_back(p);
}
}
unique_sort(result);
return result;
}
uint128_t totient(uint128_t n) {
uint128_t tot = n;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
tot -= tot >> 1;
}
for (uint128_t p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
tot -= tot / p;
}
}
if (n > 1)
tot -= tot / n;
return tot;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
const uint128_t limit = 1000000000000000;
auto pps = perfect_powers(limit);
auto ach = achilles(1, 1000000, pps);
std::cout << "First 50 Achilles numbers:\n";
for (size_t i = 0; i < 50 && i < ach.size(); ++i)
std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' ');
std::cout << "\nFirst 50 strong Achilles numbers:\n";
for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)
if (binary_search(ach.begin(), ach.end(), totient(ach[i])))
std::cout << std::setw(6) << ach[i]
<< (++count % 10 == 0 ? '\n' : ' ');
int digits = 2;
std::cout << "\nNumber of Achilles numbers with:\n";
for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {
size_t count = achilles(from, to, pps).size();
std::cout << std::setw(2) << digits << " digits: " << count << '\n';
from = to;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
primes := rcu.Primes(333)
var oss []int
for i := 1; i < len(primes)-1; i++ {
for j := i + 1; j < len(primes); j++ {
n := primes[i] * primes[j]
if n >= 1000 {
break
}
oss = append(oss, n)
}
}
sort.Ints(oss)
fmt.Println("Odd squarefree semiprimes under 1,000:")
for i, n := range oss {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found.\n", len(oss))
}
| #include <iomanip>
#include <iostream>
bool odd_square_free_semiprime(int n) {
if ((n & 1) == 0)
return false;
int count = 0;
for (int i = 3; i * i <= n; i += 2) {
for (; n % i == 0; n /= i) {
if (++count > 1)
return false;
}
}
return count == 1;
}
int main() {
const int n = 1000;
std::cout << "Odd square-free semiprimes < " << n << ":\n";
int count = 0;
for (int i = 1; i < n; i += 2) {
if (odd_square_free_semiprime(i)) {
++count;
std::cout << std::setw(4) << i;
if (count % 20 == 0)
std::cout << '\n';
}
}
std::cout << "\nCount: " << count << '\n';
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
primes := rcu.Primes(333)
var oss []int
for i := 1; i < len(primes)-1; i++ {
for j := i + 1; j < len(primes); j++ {
n := primes[i] * primes[j]
if n >= 1000 {
break
}
oss = append(oss, n)
}
}
sort.Ints(oss)
fmt.Println("Odd squarefree semiprimes under 1,000:")
for i, n := range oss {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found.\n", len(oss))
}
| #include <iomanip>
#include <iostream>
bool odd_square_free_semiprime(int n) {
if ((n & 1) == 0)
return false;
int count = 0;
for (int i = 3; i * i <= n; i += 2) {
for (; n % i == 0; n /= i) {
if (++count > 1)
return false;
}
}
return count == 1;
}
int main() {
const int n = 1000;
std::cout << "Odd square-free semiprimes < " << n << ":\n";
int count = 0;
for (int i = 1; i < n; i += 2) {
if (odd_square_free_semiprime(i)) {
++count;
std::cout << std::setw(4) << i;
if (count % 20 == 0)
std::cout << '\n';
}
}
std::cout << "\nCount: " << count << '\n';
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"github.com/fogleman/gg"
"math"
)
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h float64
func lineTo(newX, newY float64) {
dc.LineTo(newX-width/2+h, height-newY+2*h)
cx, cy = newX, newY
}
func lineN() { lineTo(cx, cy-2*h) }
func lineS() { lineTo(cx, cy+2*h) }
func lineE() { lineTo(cx+2*h, cy) }
func lineW() { lineTo(cx-2*h, cy) }
func lineNW() { lineTo(cx-h, cy-h) }
func lineNE() { lineTo(cx+h, cy-h) }
func lineSE() { lineTo(cx+h, cy+h) }
func lineSW() { lineTo(cx-h, cy+h) }
func sierN(level int) {
if level == 1 {
lineNE()
lineN()
lineNW()
} else {
sierN(level - 1)
lineNE()
sierE(level - 1)
lineN()
sierW(level - 1)
lineNW()
sierN(level - 1)
}
}
func sierE(level int) {
if level == 1 {
lineSE()
lineE()
lineNE()
} else {
sierE(level - 1)
lineSE()
sierS(level - 1)
lineE()
sierN(level - 1)
lineNE()
sierE(level - 1)
}
}
func sierS(level int) {
if level == 1 {
lineSW()
lineS()
lineSE()
} else {
sierS(level - 1)
lineSW()
sierW(level - 1)
lineS()
sierE(level - 1)
lineSE()
sierS(level - 1)
}
}
func sierW(level int) {
if level == 1 {
lineNW()
lineW()
lineSW()
} else {
sierW(level - 1)
lineNW()
sierN(level - 1)
lineW()
sierS(level - 1)
lineSW()
sierW(level - 1)
}
}
func squareCurve(level int) {
sierN(level)
lineNE()
sierE(level)
lineSE()
sierS(level)
lineSW()
sierW(level)
lineNW()
lineNE()
}
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
level := 5
cx, cy = width/2, height
h = cx / math.Pow(2, float64(level+1))
squareCurve(level)
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_curve.png")
}
|
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length/std::sqrt(2.0);
y_ = 2 * x_;
angle_ = 45;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F--XF--F--XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF+G+XF--F--XF+G+X";
else
t += c;
}
return t;
}
void sierpinski_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ -= length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
case 'G':
line(out);
break;
case '+':
angle_ = (angle_ + 45) % 360;
break;
case '-':
angle_ = (angle_ - 45) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_curve s;
s.write(out, 545, 7, 5);
return 0;
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import (
"github.com/fogleman/gg"
"math"
)
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h float64
func lineTo(newX, newY float64) {
dc.LineTo(newX-width/2+h, height-newY+2*h)
cx, cy = newX, newY
}
func lineN() { lineTo(cx, cy-2*h) }
func lineS() { lineTo(cx, cy+2*h) }
func lineE() { lineTo(cx+2*h, cy) }
func lineW() { lineTo(cx-2*h, cy) }
func lineNW() { lineTo(cx-h, cy-h) }
func lineNE() { lineTo(cx+h, cy-h) }
func lineSE() { lineTo(cx+h, cy+h) }
func lineSW() { lineTo(cx-h, cy+h) }
func sierN(level int) {
if level == 1 {
lineNE()
lineN()
lineNW()
} else {
sierN(level - 1)
lineNE()
sierE(level - 1)
lineN()
sierW(level - 1)
lineNW()
sierN(level - 1)
}
}
func sierE(level int) {
if level == 1 {
lineSE()
lineE()
lineNE()
} else {
sierE(level - 1)
lineSE()
sierS(level - 1)
lineE()
sierN(level - 1)
lineNE()
sierE(level - 1)
}
}
func sierS(level int) {
if level == 1 {
lineSW()
lineS()
lineSE()
} else {
sierS(level - 1)
lineSW()
sierW(level - 1)
lineS()
sierE(level - 1)
lineSE()
sierS(level - 1)
}
}
func sierW(level int) {
if level == 1 {
lineNW()
lineW()
lineSW()
} else {
sierW(level - 1)
lineNW()
sierN(level - 1)
lineW()
sierS(level - 1)
lineSW()
sierW(level - 1)
}
}
func squareCurve(level int) {
sierN(level)
lineNE()
sierE(level)
lineSE()
sierS(level)
lineSW()
sierW(level)
lineNW()
lineNE()
}
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
level := 5
cx, cy = width/2, height
h = cx / math.Pow(2, float64(level+1))
squareCurve(level)
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_curve.png")
}
|
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length/std::sqrt(2.0);
y_ = 2 * x_;
angle_ = 45;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F--XF--F--XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF+G+XF--F--XF+G+X";
else
t += c;
}
return t;
}
void sierpinski_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ -= length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
case 'G':
line(out);
break;
case '+':
angle_ = (angle_ + 45) % 360;
break;
case '-':
angle_ = (angle_ - 45) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_curve s;
s.write(out, 545, 7, 5);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import (
"fmt"
"sort"
)
type cf struct {
c rune
f int
}
func reverseStr(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func indexOfCf(cfs []cf, r rune) int {
for i, cf := range cfs {
if cf.c == r {
return i
}
}
return -1
}
func minOf(i, j int) int {
if i < j {
return i
}
return j
}
func mostFreqKHashing(input string, k int) string {
var cfs []cf
for _, r := range input {
ix := indexOfCf(cfs, r)
if ix >= 0 {
cfs[ix].f++
} else {
cfs = append(cfs, cf{r, 1})
}
}
sort.SliceStable(cfs, func(i, j int) bool {
return cfs[i].f > cfs[j].f
})
acc := ""
min := minOf(len(cfs), k)
for _, cf := range cfs[:min] {
acc += fmt.Sprintf("%c%c", cf.c, cf.f)
}
return acc
}
func mostFreqKSimilarity(input1, input2 string) int {
similarity := 0
runes1, runes2 := []rune(input1), []rune(input2)
for i := 0; i < len(runes1); i += 2 {
for j := 0; j < len(runes2); j += 2 {
if runes1[i] == runes2[j] {
freq1, freq2 := runes1[i+1], runes2[j+1]
if freq1 != freq2 {
continue
}
similarity += int(freq1)
}
}
}
return similarity
}
func mostFreqKSDF(input1, input2 string, k, maxDistance int) {
fmt.Println("input1 :", input1)
fmt.Println("input2 :", input2)
s1 := mostFreqKHashing(input1, k)
s2 := mostFreqKHashing(input2, k)
fmt.Printf("mfkh(input1, %d) = ", k)
for i, c := range s1 {
if i%2 == 0 {
fmt.Printf("%c", c)
} else {
fmt.Printf("%d", c)
}
}
fmt.Printf("\nmfkh(input2, %d) = ", k)
for i, c := range s2 {
if i%2 == 0 {
fmt.Printf("%c", c)
} else {
fmt.Printf("%d", c)
}
}
result := maxDistance - mostFreqKSimilarity(s1, s2)
fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result)
}
func main() {
pairs := [][2]string{
{"research", "seeking"},
{"night", "nacht"},
{"my", "a"},
{"research", "research"},
{"aaaaabbbb", "ababababa"},
{"significant", "capabilities"},
}
for _, pair := range pairs {
mostFreqKSDF(pair[0], pair[1], 2, 10)
}
s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"
s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"
mostFreqKSDF(s1, s2, 2, 100)
s1 = "abracadabra12121212121abracadabra12121212121"
s2 = reverseStr(s1)
mostFreqKSDF(s1, s2, 2, 100)
}
| #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include <utility>
#include <sstream>
std::string mostFreqKHashing ( const std::string & input , int k ) {
std::ostringstream oss ;
std::map<char, int> frequencies ;
for ( char c : input ) {
frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;
}
std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;
std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,
std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ;
int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }
else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;
for ( int i = 0 ; i < letters.size( ) ; i++ ) {
oss << std::get<0>( letters[ i ] ) ;
oss << std::get<1>( letters[ i ] ) ;
}
std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;
if ( letters.size( ) >= k ) {
return output ;
}
else {
return output.append( "NULL0" ) ;
}
}
int mostFreqKSimilarity ( const std::string & first , const std::string & second ) {
int i = 0 ;
while ( i < first.length( ) - 1 ) {
auto found = second.find_first_of( first.substr( i , 2 ) ) ;
if ( found != std::string::npos )
return std::stoi ( first.substr( i , 2 )) ;
else
i += 2 ;
}
return 0 ;
}
int mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {
return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;
}
int main( ) {
std::string s1("LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" ) ;
std::string s2( "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" ) ;
std::cout << "MostFreqKHashing( s1 , 2 ) = " << mostFreqKHashing( s1 , 2 ) << '\n' ;
std::cout << "MostFreqKHashing( s2 , 2 ) = " << mostFreqKHashing( s2 , 2 ) << '\n' ;
return 0 ;
}
|
Generate an equivalent C++ version of this Go code. | package main
import (
"fmt"
"rcu"
)
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n /= 10
}
return rev
}
func main() {
primes := rcu.Primes(99999)
var pals []int
for _, p := range primes {
if p == reversed(p) {
pals = append(pals, p)
}
}
fmt.Println("Palindromic primes under 1,000:")
var smallPals, bigPals []int
for _, p := range pals {
if p < 1000 {
smallPals = append(smallPals, p)
} else {
bigPals = append(bigPals, p)
}
}
rcu.PrintTable(smallPals, 10, 3, false)
fmt.Println()
fmt.Println(len(smallPals), "such primes found.")
fmt.Println("\nAdditional palindromic primes under 100,000:")
rcu.PrintTable(bigPals, 10, 6, true)
fmt.Println()
fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.")
}
| #include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
unsigned int reverse(unsigned int base, unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= base)
rev = rev * base + (n % base);
return rev;
}
class palindrome_generator {
public:
explicit palindrome_generator(unsigned int base)
: base_(base), upper_(base) {}
unsigned int next_palindrome();
private:
unsigned int base_;
unsigned int lower_ = 1;
unsigned int upper_;
unsigned int next_ = 0;
bool even_ = false;
};
unsigned int palindrome_generator::next_palindrome() {
++next_;
if (next_ == upper_) {
if (even_) {
lower_ = upper_;
upper_ *= base_;
}
next_ = lower_;
even_ = !even_;
}
return even_ ? next_ * upper_ + reverse(base_, next_)
: next_ * lower_ + reverse(base_, next_ / base_);
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
std::string to_string(unsigned int base, unsigned int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
void print_palindromic_primes(unsigned int base, unsigned int limit) {
auto width =
static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));
unsigned int count = 0;
auto columns = 80 / (width + 1);
std::cout << "Base " << base << " palindromic primes less than " << limit
<< ":\n";
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit) {
if (is_prime(palindrome)) {
++count;
std::cout << std::setw(width) << to_string(base, palindrome)
<< (count % columns == 0 ? '\n' : ' ');
}
}
if (count % columns != 0)
std::cout << '\n';
std::cout << "Count: " << count << '\n';
}
void count_palindromic_primes(unsigned int base, unsigned int limit) {
unsigned int count = 0;
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit)
if (is_prime(palindrome))
++count;
std::cout << "Number of base " << base << " palindromic primes less than "
<< limit << ": " << count << '\n';
}
int main() {
print_palindromic_primes(10, 1000);
std::cout << '\n';
print_palindromic_primes(10, 100000);
std::cout << '\n';
count_palindromic_primes(10, 1000000000);
std::cout << '\n';
print_palindromic_primes(16, 500);
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"fmt"
"rcu"
)
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n /= 10
}
return rev
}
func main() {
primes := rcu.Primes(99999)
var pals []int
for _, p := range primes {
if p == reversed(p) {
pals = append(pals, p)
}
}
fmt.Println("Palindromic primes under 1,000:")
var smallPals, bigPals []int
for _, p := range pals {
if p < 1000 {
smallPals = append(smallPals, p)
} else {
bigPals = append(bigPals, p)
}
}
rcu.PrintTable(smallPals, 10, 3, false)
fmt.Println()
fmt.Println(len(smallPals), "such primes found.")
fmt.Println("\nAdditional palindromic primes under 100,000:")
rcu.PrintTable(bigPals, 10, 6, true)
fmt.Println()
fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.")
}
| #include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
unsigned int reverse(unsigned int base, unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= base)
rev = rev * base + (n % base);
return rev;
}
class palindrome_generator {
public:
explicit palindrome_generator(unsigned int base)
: base_(base), upper_(base) {}
unsigned int next_palindrome();
private:
unsigned int base_;
unsigned int lower_ = 1;
unsigned int upper_;
unsigned int next_ = 0;
bool even_ = false;
};
unsigned int palindrome_generator::next_palindrome() {
++next_;
if (next_ == upper_) {
if (even_) {
lower_ = upper_;
upper_ *= base_;
}
next_ = lower_;
even_ = !even_;
}
return even_ ? next_ * upper_ + reverse(base_, next_)
: next_ * lower_ + reverse(base_, next_ / base_);
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
std::string to_string(unsigned int base, unsigned int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
void print_palindromic_primes(unsigned int base, unsigned int limit) {
auto width =
static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));
unsigned int count = 0;
auto columns = 80 / (width + 1);
std::cout << "Base " << base << " palindromic primes less than " << limit
<< ":\n";
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit) {
if (is_prime(palindrome)) {
++count;
std::cout << std::setw(width) << to_string(base, palindrome)
<< (count % columns == 0 ? '\n' : ' ');
}
}
if (count % columns != 0)
std::cout << '\n';
std::cout << "Count: " << count << '\n';
}
void count_palindromic_primes(unsigned int base, unsigned int limit) {
unsigned int count = 0;
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit)
if (is_prime(palindrome))
++count;
std::cout << "Number of base " << base << " palindromic primes less than "
<< limit << ": " << count << '\n';
}
int main() {
print_palindromic_primes(10, 1000);
std::cout << '\n';
print_palindromic_primes(10, 100000);
std::cout << '\n';
count_palindromic_primes(10, 1000000000);
std::cout << '\n';
print_palindromic_primes(16, 500);
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 10 {
words = append(words, s)
}
}
count := 0
fmt.Println("Words which contain all 5 vowels once in", wordList, "\b:\n")
for _, word := range words {
ca, ce, ci, co, cu := 0, 0, 0, 0, 0
for _, r := range word {
switch r {
case 'a':
ca++
case 'e':
ce++
case 'i':
ci++
case 'o':
co++
case 'u':
cu++
}
}
if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 {
count++
fmt.Printf("%2d: %s\n", count, word)
}
}
}
| #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
bool contains_all_vowels_once(const std::string& word) {
std::bitset<5> vowels;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
size_t bit = 0;
switch (ch) {
case 'a': bit = 0; break;
case 'e': bit = 1; break;
case 'i': bit = 2; break;
case 'o': bit = 3; break;
case 'u': bit = 4; break;
default: continue;
}
if (vowels.test(bit))
return false;
vowels.set(bit);
}
return vowels.all();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
if (word.size() > 10 && contains_all_vowels_once(word))
std::cout << std::setw(2) << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
)
func levenshtein(s, t string) int {
d := make([][]int, len(s)+1)
for i := range d {
d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i
}
for j := range d[0] {
d[0][j] = j
}
for j := 1; j <= len(t); j++ {
for i := 1; i <= len(s); i++ {
if s[i-1] == t[j-1] {
d[i][j] = d[i-1][j-1]
} else {
min := d[i-1][j]
if d[i][j-1] < min {
min = d[i][j-1]
}
if d[i-1][j-1] < min {
min = d[i-1][j-1]
}
d[i][j] = min + 1
}
}
}
return d[len(s)][len(t)]
}
func main() {
search := "complition"
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
words := bytes.Fields(b)
var lev [4][]string
for _, word := range words {
s := string(word)
ld := levenshtein(search, s)
if ld < 4 {
lev[ld] = append(lev[ld], s)
}
}
fmt.Printf("Input word: %s\n\n", search)
for i := 1; i < 4; i++ {
length := float64(len(search))
similarity := (length - float64(i)) * 100 / length
fmt.Printf("Words which are %4.1f%% similar:\n", similarity)
fmt.Println(lev[i])
fmt.Println()
}
}
| #include <algorithm>
#include <fstream>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int levenshtein_distance(const std::string& str1, const std::string& str2) {
size_t m = str1.size(), n = str2.size();
std::vector<int> cost(n + 1);
std::iota(cost.begin(), cost.end(), 0);
for (size_t i = 0; i < m; ++i) {
cost[0] = i + 1;
int prev = i;
for (size_t j = 0; j < n; ++j) {
int c = (str1[i] == str2[j]) ? prev
: 1 + std::min(std::min(cost[j + 1], cost[j]), prev);
prev = cost[j + 1];
cost[j + 1] = c;
}
}
return cost[n];
}
template <typename T>
void print_vector(const std::vector<T>& vec) {
auto i = vec.begin();
if (i == vec.end())
return;
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
}
int main(int argc, char** argv) {
if (argc != 3) {
std::cerr << "usage: " << argv[0] << " dictionary word\n";
return EXIT_FAILURE;
}
std::ifstream in(argv[1]);
if (!in) {
std::cerr << "Cannot open file " << argv[1] << '\n';
return EXIT_FAILURE;
}
std::string word(argv[2]);
if (word.empty()) {
std::cerr << "Word must not be empty\n";
return EXIT_FAILURE;
}
constexpr size_t max_dist = 4;
std::vector<std::string> matches[max_dist + 1];
std::string match;
while (getline(in, match)) {
int distance = levenshtein_distance(word, match);
if (distance <= max_dist)
matches[distance].push_back(match);
}
for (size_t dist = 0; dist <= max_dist; ++dist) {
if (matches[dist].empty())
continue;
std::cout << "Words at Levenshtein distance of " << dist
<< " (" << 100 - (100 * dist)/word.size()
<< "% similarity) from '" << word << "':\n";
print_vector(matches[dist]);
std::cout << "\n\n";
}
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
const limit = int(1e10)
const maxIndex = 9
primes := rcu.Primes(limit)
anaprimes := make(map[int][]int)
for _, p := range primes {
digs := rcu.Digits(p, 10)
key := 1
for _, dig := range digs {
key *= primes[dig]
}
if _, ok := anaprimes[key]; ok {
anaprimes[key] = append(anaprimes[key], p)
} else {
anaprimes[key] = []int{p}
}
}
largest := make([]int, maxIndex+1)
groups := make([][][]int, maxIndex+1)
for key := range anaprimes {
v := anaprimes[key]
nd := len(rcu.Digits(v[0], 10))
c := len(v)
if c > largest[nd-1] {
largest[nd-1] = c
groups[nd-1] = [][]int{v}
} else if c == largest[nd-1] {
groups[nd-1] = append(groups[nd-1], v)
}
}
j := 1000
for i := 2; i <= maxIndex; i++ {
js := rcu.Commatize(j)
ls := rcu.Commatize(largest[i])
fmt.Printf("Largest group(s) of anaprimes before %s: %s members:\n", js, ls)
sort.Slice(groups[i], func(k, l int) bool {
return groups[i][k][0] < groups[i][l][0]
})
for _, g := range groups[i] {
fmt.Printf(" First: %s Last: %s\n", rcu.Commatize(g[0]), rcu.Commatize(g[len(g)-1]))
}
j *= 10
fmt.Println()
}
}
| #include <array>
#include <iostream>
#include <map>
#include <vector>
#include <primesieve.hpp>
using digit_set = std::array<int, 10>;
digit_set get_digits(uint64_t n) {
digit_set result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
int main() {
std::cout.imbue(std::locale(""));
primesieve::iterator pi;
using map_type =
std::map<digit_set, std::vector<uint64_t>, std::greater<digit_set>>;
map_type anaprimes;
for (uint64_t limit = 1000; limit <= 10000000000;) {
uint64_t prime = pi.next_prime();
if (prime > limit) {
size_t max_length = 0;
std::vector<map_type::iterator> groups;
for (auto i = anaprimes.begin(); i != anaprimes.end(); ++i) {
if (i->second.size() > max_length) {
groups.clear();
max_length = i->second.size();
}
if (max_length == i->second.size())
groups.push_back(i);
}
std::cout << "Largest group(s) of anaprimes before " << limit
<< ": " << max_length << " members:\n";
for (auto i : groups) {
std::cout << " First: " << i->second.front()
<< " Last: " << i->second.back() << '\n';
}
std::cout << '\n';
anaprimes.clear();
limit *= 10;
}
anaprimes[get_digits(prime)].push_back(prime);
}
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"log"
"math"
)
var MinusInf = math.Inf(-1)
type MaxTropical struct{ r float64 }
func newMaxTropical(r float64) MaxTropical {
if math.IsInf(r, 1) || math.IsNaN(r) {
log.Fatal("Argument must be a real number or negative infinity.")
}
return MaxTropical{r}
}
func (t MaxTropical) eq(other MaxTropical) bool {
return t.r == other.r
}
func (t MaxTropical) add(other MaxTropical) MaxTropical {
if t.r == MinusInf {
return other
}
if other.r == MinusInf {
return t
}
return newMaxTropical(math.Max(t.r, other.r))
}
func (t MaxTropical) mul(other MaxTropical) MaxTropical {
if t.r == 0 {
return other
}
if other.r == 0 {
return t
}
return newMaxTropical(t.r + other.r)
}
func (t MaxTropical) pow(e int) MaxTropical {
if e < 1 {
log.Fatal("Exponent must be a positive integer.")
}
if e == 1 {
return t
}
p := t
for i := 2; i <= e; i++ {
p = p.mul(t)
}
return p
}
func (t MaxTropical) String() string {
return fmt.Sprintf("%g", t.r)
}
func main() {
data := [][]float64{
{2, -2, 1},
{-0.001, MinusInf, 0},
{0, MinusInf, 1},
{1.5, -1, 0},
{-0.5, 0, 1},
}
for _, d := range data {
a := newMaxTropical(d[0])
b := newMaxTropical(d[1])
if d[2] == 0 {
fmt.Printf("%s ⊕ %s = %s\n", a, b, a.add(b))
} else {
fmt.Printf("%s ⊗ %s = %s\n", a, b, a.mul(b))
}
}
c := newMaxTropical(5)
fmt.Printf("%s ^ 7 = %s\n", c, c.pow(7))
d := newMaxTropical(8)
e := newMaxTropical(7)
f := c.mul(d.add(e))
g := c.mul(d).add(c.mul(e))
fmt.Printf("%s ⊗ (%s ⊕ %s) = %s\n", c, d, e, f)
fmt.Printf("%s ⊗ %s ⊕ %s ⊗ %s = %s\n", c, d, c, e, g)
fmt.Printf("%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\n", c, d, e, c, d, c, e, f.eq(g))
}
| #include <iostream>
#include <optional>
using namespace std;
class TropicalAlgebra
{
optional<double> m_value;
public:
friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);
friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;
TropicalAlgebra() = default;
explicit TropicalAlgebra(double value) noexcept
: m_value{value} {}
TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
*this = rhs;
}
else if (!rhs.m_value)
{
}
else
{
*m_value = max(*rhs.m_value, *m_value);
}
return *this;
}
TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
}
else if (!rhs.m_value)
{
*this = rhs;
}
else
{
*m_value += *rhs.m_value;
}
return *this;
}
};
inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs += rhs;
return lhs;
}
inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs *= rhs;
return lhs;
}
inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept
{
auto result = base;
for(unsigned int i = 1; i < exponent; i++)
{
result *= base;
}
return result;
}
ostream& operator<<(ostream& os, const TropicalAlgebra& pt)
{
if(!pt.m_value) cout << "-Inf\n";
else cout << *pt.m_value << "\n";
return os;
}
int main(void) {
const TropicalAlgebra a(-2);
const TropicalAlgebra b(-1);
const TropicalAlgebra c(-0.5);
const TropicalAlgebra d(-0.001);
const TropicalAlgebra e(0);
const TropicalAlgebra h(1.5);
const TropicalAlgebra i(2);
const TropicalAlgebra j(5);
const TropicalAlgebra k(7);
const TropicalAlgebra l(8);
const TropicalAlgebra m;
cout << "2 * -2 == " << i * a;
cout << "-0.001 + -Inf == " << d + m;
cout << "0 * -Inf == " << e * m;
cout << "1.5 + -1 == " << h + b;
cout << "-0.5 * 0 == " << c * e;
cout << "pow(5, 7) == " << pow(j, 7);
cout << "5 * (8 + 7)) == " << j * (l + k);
cout << "5 * 8 + 5 * 7 == " << j * l + j * k;
}
|
Port the provided Go code into C++ while preserving the original functionality. | package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const (
gameOver = iota
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
| #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const (
gameOver = iota
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
| #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
|
Write a version of this Go function in C++ with identical behavior. | package cf
import "math"
type NG8 struct {
A12, A1, A2, A int64
B12, B1, B2, B int64
}
var (
NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}
NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}
NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}
NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}
)
func (ng *NG8) needsIngest() bool {
if ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {
return true
}
x := ng.A / ng.B
return ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x
}
func (ng *NG8) isDone() bool {
return ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0
}
func (ng *NG8) ingestWhich() bool {
if ng.B == 0 && ng.B2 == 0 {
return true
}
if ng.B == 0 || ng.B2 == 0 {
return false
}
x1 := float64(ng.A1) / float64(ng.B1)
x2 := float64(ng.A2) / float64(ng.B2)
x := float64(ng.A) / float64(ng.B)
return math.Abs(x1-x) > math.Abs(x2-x)
}
func (ng *NG8) ingest(isN1 bool, t int64) {
if isN1 {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,
ng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1
} else {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,
ng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2
}
}
func (ng *NG8) ingestInfinite(isN1 bool) {
if isN1 {
ng.A2, ng.A, ng.B2, ng.B =
ng.A12, ng.A1,
ng.B12, ng.B1
} else {
ng.A1, ng.A, ng.B1, ng.B =
ng.A12, ng.A2,
ng.B12, ng.B2
}
}
func (ng *NG8) egest(t int64) {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.B12, ng.B1, ng.B2, ng.B,
ng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t
}
func (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {
return func() NextFn {
next1, next2 := N1(), N2()
done := false
sinceEgest := 0
return func() (int64, bool) {
if done {
return 0, false
}
for ng.needsIngest() {
sinceEgest++
if sinceEgest > limit {
done = true
return 0, false
}
isN1 := ng.ingestWhich()
next := next2
if isN1 {
next = next1
}
if t, ok := next(); ok {
ng.ingest(isN1, t)
} else {
ng.ingestInfinite(isN1)
}
}
sinceEgest = 0
t := ng.A / ng.B
ng.egest(t)
done = ng.isDone()
return t, true
}
}
}
|
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;
if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;
if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;
if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;
thisTerm = (int)ab;
if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){
t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;
haveTerm = true; return false;
}
cfn = chooseCFN();
return true;
}
void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}
void consumeTerm(int n){
if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}
else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}
}
public:
NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){
}};
|
Convert this Go block to C++, preserving its control flow and logic. | package cf
import "math"
type NG8 struct {
A12, A1, A2, A int64
B12, B1, B2, B int64
}
var (
NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}
NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}
NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}
NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}
)
func (ng *NG8) needsIngest() bool {
if ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {
return true
}
x := ng.A / ng.B
return ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x
}
func (ng *NG8) isDone() bool {
return ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0
}
func (ng *NG8) ingestWhich() bool {
if ng.B == 0 && ng.B2 == 0 {
return true
}
if ng.B == 0 || ng.B2 == 0 {
return false
}
x1 := float64(ng.A1) / float64(ng.B1)
x2 := float64(ng.A2) / float64(ng.B2)
x := float64(ng.A) / float64(ng.B)
return math.Abs(x1-x) > math.Abs(x2-x)
}
func (ng *NG8) ingest(isN1 bool, t int64) {
if isN1 {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,
ng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1
} else {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,
ng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2
}
}
func (ng *NG8) ingestInfinite(isN1 bool) {
if isN1 {
ng.A2, ng.A, ng.B2, ng.B =
ng.A12, ng.A1,
ng.B12, ng.B1
} else {
ng.A1, ng.A, ng.B1, ng.B =
ng.A12, ng.A2,
ng.B12, ng.B2
}
}
func (ng *NG8) egest(t int64) {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.B12, ng.B1, ng.B2, ng.B,
ng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t
}
func (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {
return func() NextFn {
next1, next2 := N1(), N2()
done := false
sinceEgest := 0
return func() (int64, bool) {
if done {
return 0, false
}
for ng.needsIngest() {
sinceEgest++
if sinceEgest > limit {
done = true
return 0, false
}
isN1 := ng.ingestWhich()
next := next2
if isN1 {
next = next1
}
if t, ok := next(); ok {
ng.ingest(isN1, t)
} else {
ng.ingestInfinite(isN1)
}
}
sinceEgest = 0
t := ng.A / ng.B
ng.egest(t)
done = ng.isDone()
return t, true
}
}
}
|
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;
if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;
if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;
if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;
thisTerm = (int)ab;
if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){
t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;
haveTerm = true; return false;
}
cfn = chooseCFN();
return true;
}
void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}
void consumeTerm(int n){
if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}
else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}
}
public:
NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){
}};
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"flag"
"fmt"
"math"
"math/big"
"os"
)
var maxRev = big.NewInt(math.MaxUint64 / 10)
var ten = big.NewInt(10)
func reverseInt(v *big.Int, result *big.Int) *big.Int {
if v.Cmp(maxRev) <= 0 {
result.SetUint64(reverseUint64(v.Uint64()))
} else {
if true {
s := reverseString(v.String())
result.SetString(s, 10)
} else {
v := new(big.Int).Set(v)
digit := new(big.Int)
result.SetUint64(0)
for v.BitLen() > 0 {
v.QuoRem(v, ten, digit)
result.Mul(result, ten)
result.Add(result, digit)
}
}
}
return result
}
func reverseUint64(v uint64) uint64 {
var r uint64
for v > 0 {
r *= 10
r += v % 10
v /= 10
}
return r
}
func reverseString(s string) string {
b := make([]byte, len(s))
for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {
b[i] = s[j]
}
return string(b)
}
var known = make(map[string]bool)
func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {
v, r := new(big.Int).SetUint64(n), new(big.Int)
reverseInt(v, r)
seen := make(map[string]bool)
isLychrel = true
isSeed = true
for i := iter; i > 0; i-- {
str := v.String()
if seen[str] {
isLychrel = true
break
}
if ans, ok := known[str]; ok {
isLychrel = ans
isSeed = false
break
}
seen[str] = true
v = v.Add(v, r)
reverseInt(v, r)
if v.Cmp(r) == 0 {
isLychrel = false
isSeed = false
break
}
}
for k := range seen {
known[k] = isLychrel
}
return isLychrel, isSeed
}
func main() {
max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive")
iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter)
var seeds []uint64
var related int
var pals []uint64
for i := uint64(1); i <= *max; i++ {
if l, s := Lychrel(i, *iter); l {
if s {
seeds = append(seeds, i)
} else {
related++
}
if i == reverseUint64(i) {
pals = append(pals, i)
}
}
}
fmt.Println(" Number of Lychrel seeds:", len(seeds))
fmt.Println(" Lychrel seeds:", seeds)
fmt.Println(" Number of related:", related)
fmt.Println("Number of Lychrel palindromes:", len(pals))
fmt.Println(" Lychrel palindromes:", pals)
}
| #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"flag"
"fmt"
"math"
"math/big"
"os"
)
var maxRev = big.NewInt(math.MaxUint64 / 10)
var ten = big.NewInt(10)
func reverseInt(v *big.Int, result *big.Int) *big.Int {
if v.Cmp(maxRev) <= 0 {
result.SetUint64(reverseUint64(v.Uint64()))
} else {
if true {
s := reverseString(v.String())
result.SetString(s, 10)
} else {
v := new(big.Int).Set(v)
digit := new(big.Int)
result.SetUint64(0)
for v.BitLen() > 0 {
v.QuoRem(v, ten, digit)
result.Mul(result, ten)
result.Add(result, digit)
}
}
}
return result
}
func reverseUint64(v uint64) uint64 {
var r uint64
for v > 0 {
r *= 10
r += v % 10
v /= 10
}
return r
}
func reverseString(s string) string {
b := make([]byte, len(s))
for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {
b[i] = s[j]
}
return string(b)
}
var known = make(map[string]bool)
func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {
v, r := new(big.Int).SetUint64(n), new(big.Int)
reverseInt(v, r)
seen := make(map[string]bool)
isLychrel = true
isSeed = true
for i := iter; i > 0; i-- {
str := v.String()
if seen[str] {
isLychrel = true
break
}
if ans, ok := known[str]; ok {
isLychrel = ans
isSeed = false
break
}
seen[str] = true
v = v.Add(v, r)
reverseInt(v, r)
if v.Cmp(r) == 0 {
isLychrel = false
isSeed = false
break
}
}
for k := range seen {
known[k] = isLychrel
}
return isLychrel, isSeed
}
func main() {
max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive")
iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter)
var seeds []uint64
var related int
var pals []uint64
for i := uint64(1); i <= *max; i++ {
if l, s := Lychrel(i, *iter); l {
if s {
seeds = append(seeds, i)
} else {
related++
}
if i == reverseUint64(i) {
pals = append(pals, i)
}
}
}
fmt.Println(" Number of Lychrel seeds:", len(seeds))
fmt.Println(" Lychrel seeds:", seeds)
fmt.Println(" Number of related:", related)
fmt.Println("Number of Lychrel palindromes:", len(pals))
fmt.Println(" Lychrel palindromes:", pals)
}
| #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
const nondecimal = "abcdef"
c := 0
for i := int64(0); i <= 500; i++ {
hex := strconv.FormatInt(i, 16)
if strings.ContainsAny(nondecimal, hex) {
fmt.Printf("%3d ", i)
c++
if c%15 == 0 {
fmt.Println()
}
}
}
fmt.Printf("\n\n%d such numbers found.\n", c)
}
| #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
}
}
std::cout << "\n\n" << count << " such numbers found.\n";
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
const nondecimal = "abcdef"
c := 0
for i := int64(0); i <= 500; i++ {
hex := strconv.FormatInt(i, 16)
if strings.ContainsAny(nondecimal, hex) {
fmt.Printf("%3d ", i)
c++
if c%15 == 0 {
fmt.Println()
}
}
}
fmt.Printf("\n\n%d such numbers found.\n", c)
}
| #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
}
}
std::cout << "\n\n" << count << " such numbers found.\n";
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"fmt"
"math"
"rcu"
)
var limit = int(math.Log(1e6) * 1e6 * 1.2)
var primes = rcu.Primes(limit)
var prevCats = make(map[int]int)
func cat(p int) int {
if v, ok := prevCats[p]; ok {
return v
}
pf := rcu.PrimeFactors(p + 1)
all := true
for _, f := range pf {
if f != 2 && f != 3 {
all = false
break
}
}
if all {
return 1
}
if p > 2 {
len := len(pf)
for i := len - 1; i >= 1; i-- {
if pf[i-1] == pf[i] {
pf = append(pf[:i], pf[i+1:]...)
}
}
}
for c := 2; c <= 11; c++ {
all := true
for _, f := range pf {
if cat(f) >= c {
all = false
break
}
}
if all {
prevCats[p] = c
return c
}
}
return 12
}
func main() {
es := make([][]int, 12)
fmt.Println("First 200 primes:\n")
for _, p := range primes[0:200] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 6; c++ {
if len(es[c-1]) > 0 {
fmt.Println("Category", c, "\b:")
fmt.Println(es[c-1])
fmt.Println()
}
}
fmt.Println("First million primes:\n")
for _, p := range primes[200:1e6] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 12; c++ {
e := es[c-1]
if len(e) > 0 {
format := "Category %-2d: First = %7d Last = %8d Count = %6d\n"
fmt.Printf(format, c, e[0], e[len(e)-1], len(e))
}
}
}
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <map>
#include <vector>
#include <primesieve.hpp>
class erdos_selfridge {
public:
explicit erdos_selfridge(int limit);
uint64_t get_prime(int index) const { return primes_[index].first; }
int get_category(int index);
private:
std::vector<std::pair<uint64_t, int>> primes_;
size_t get_index(uint64_t prime) const;
};
erdos_selfridge::erdos_selfridge(int limit) {
primesieve::iterator iter;
for (int i = 0; i < limit; ++i)
primes_.emplace_back(iter.next_prime(), 0);
}
int erdos_selfridge::get_category(int index) {
auto& pair = primes_[index];
if (pair.second != 0)
return pair.second;
int max_category = 0;
uint64_t n = pair.first + 1;
for (int i = 0; n > 1; ++i) {
uint64_t p = primes_[i].first;
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + get_category(i);
max_category = std::max(max_category, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));
max_category = std::max(max_category, category);
}
pair.second = max_category;
return max_category;
}
size_t erdos_selfridge::get_index(uint64_t prime) const {
auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,
[](const std::pair<uint64_t, int>& p,
uint64_t n) { return p.first < n; });
assert(it != primes_.end());
assert(it->first == prime);
return std::distance(primes_.begin(), it);
}
auto get_primes_by_category(erdos_selfridge& es, int limit) {
std::map<int, std::vector<uint64_t>> primes_by_category;
for (int i = 0; i < limit; ++i) {
uint64_t prime = es.get_prime(i);
int category = es.get_category(i);
primes_by_category[category].push_back(prime);
}
return primes_by_category;
}
int main() {
const int limit1 = 200, limit2 = 1000000;
erdos_selfridge es(limit2);
std::cout << "First 200 primes:\n";
for (const auto& p : get_primes_by_category(es, limit1)) {
std::cout << "Category " << p.first << ":\n";
for (size_t i = 0, n = p.second.size(); i != n; ++i) {
std::cout << std::setw(4) << p.second[i]
<< ((i + 1) % 15 == 0 ? '\n' : ' ');
}
std::cout << "\n\n";
}
std::cout << "First 1,000,000 primes:\n";
for (const auto& p : get_primes_by_category(es, limit2)) {
const auto& v = p.second;
std::cout << "Category " << std::setw(2) << p.first << ": "
<< "first = " << std::setw(7) << v.front()
<< " last = " << std::setw(8) << v.back()
<< " count = " << v.size() << '\n';
}
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import (
"fmt"
"strings"
)
type rng struct{ from, to int }
type fn func(rngs *[]rng, n int)
func (r rng) String() string { return fmt.Sprintf("%d-%d", r.from, r.to) }
func rangesAdd(rngs []rng, n int) []rng {
if len(rngs) == 0 {
rngs = append(rngs, rng{n, n})
return rngs
}
for i, r := range rngs {
if n < r.from-1 {
rngs = append(rngs, rng{})
copy(rngs[i+1:], rngs[i:])
rngs[i] = rng{n, n}
return rngs
} else if n == r.from-1 {
rngs[i] = rng{n, r.to}
return rngs
} else if n <= r.to {
return rngs
} else if n == r.to+1 {
rngs[i] = rng{r.from, n}
if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) {
rngs[i] = rng{r.from, rngs[i+1].to}
copy(rngs[i+1:], rngs[i+2:])
rngs[len(rngs)-1] = rng{}
rngs = rngs[:len(rngs)-1]
}
return rngs
} else if i == len(rngs)-1 {
rngs = append(rngs, rng{n, n})
return rngs
}
}
return rngs
}
func rangesRemove(rngs []rng, n int) []rng {
if len(rngs) == 0 {
return rngs
}
for i, r := range rngs {
if n <= r.from-1 {
return rngs
} else if n == r.from && n == r.to {
copy(rngs[i:], rngs[i+1:])
rngs[len(rngs)-1] = rng{}
rngs = rngs[:len(rngs)-1]
return rngs
} else if n == r.from {
rngs[i] = rng{n + 1, r.to}
return rngs
} else if n < r.to {
rngs[i] = rng{r.from, n - 1}
rngs = append(rngs, rng{})
copy(rngs[i+2:], rngs[i+1:])
rngs[i+1] = rng{n + 1, r.to}
return rngs
} else if n == r.to {
rngs[i] = rng{r.from, n - 1}
return rngs
}
}
return rngs
}
func standard(rngs []rng) string {
if len(rngs) == 0 {
return ""
}
var sb strings.Builder
for _, r := range rngs {
sb.WriteString(fmt.Sprintf("%s,", r))
}
s := sb.String()
return s[:len(s)-1]
}
func main() {
const add = 0
const remove = 1
fns := []fn{
func(prngs *[]rng, n int) {
*prngs = rangesAdd(*prngs, n)
fmt.Printf(" add %2d => %s\n", n, standard(*prngs))
},
func(prngs *[]rng, n int) {
*prngs = rangesRemove(*prngs, n)
fmt.Printf(" remove %2d => %s\n", n, standard(*prngs))
},
}
var rngs []rng
ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}}
fmt.Printf("Start: %q\n", standard(rngs))
for _, op := range ops {
fns[op[0]](&rngs, op[1])
}
rngs = []rng{{1, 3}, {5, 5}}
ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}}
fmt.Printf("\nStart: %q\n", standard(rngs))
for _, op := range ops {
fns[op[0]](&rngs, op[1])
}
rngs = []rng{{1, 5}, {10, 25}, {27, 30}}
ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}}
fmt.Printf("\nStart: %q\n", standard(rngs))
for _, op := range ops {
fns[op[0]](&rngs, op[1])
}
}
| #include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
struct range {
range(int lo, int hi) : low(lo), high(hi) {}
int low;
int high;
};
std::ostream& operator<<(std::ostream& out, const range& r) {
return out << r.low << '-' << r.high;
}
class ranges {
public:
ranges() {}
explicit ranges(std::initializer_list<range> init) : ranges_(init) {}
void add(int n);
void remove(int n);
bool empty() const { return ranges_.empty(); }
private:
friend std::ostream& operator<<(std::ostream& out, const ranges& r);
std::list<range> ranges_;
};
void ranges::add(int n) {
for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {
if (n + 1 < i->low) {
ranges_.emplace(i, n, n);
return;
}
if (n > i->high + 1)
continue;
if (n + 1 == i->low)
i->low = n;
else if (n == i->high + 1)
i->high = n;
else
return;
if (i != ranges_.begin()) {
auto prev = std::prev(i);
if (prev->high + 1 == i->low) {
i->low = prev->low;
ranges_.erase(prev);
}
}
auto next = std::next(i);
if (next != ranges_.end() && next->low - 1 == i->high) {
i->high = next->high;
ranges_.erase(next);
}
return;
}
ranges_.emplace_back(n, n);
}
void ranges::remove(int n) {
for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {
if (n < i->low)
return;
if (n == i->low) {
if (++i->low > i->high)
ranges_.erase(i);
return;
}
if (n == i->high) {
if (--i->high < i->low)
ranges_.erase(i);
return;
}
if (n > i->low & n < i->high) {
int low = i->low;
i->low = n + 1;
ranges_.emplace(i, low, n - 1);
return;
}
}
}
std::ostream& operator<<(std::ostream& out, const ranges& r) {
if (!r.empty()) {
auto i = r.ranges_.begin();
out << *i++;
for (; i != r.ranges_.end(); ++i)
out << ',' << *i;
}
return out;
}
void test_add(ranges& r, int n) {
r.add(n);
std::cout << " add " << std::setw(2) << n << " => " << r << '\n';
}
void test_remove(ranges& r, int n) {
r.remove(n);
std::cout << " remove " << std::setw(2) << n << " => " << r << '\n';
}
void test1() {
ranges r;
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 77);
test_add(r, 79);
test_add(r, 78);
test_remove(r, 77);
test_remove(r, 78);
test_remove(r, 79);
}
void test2() {
ranges r{{1,3}, {5,5}};
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 1);
test_remove(r, 4);
test_add(r, 7);
test_add(r, 8);
test_add(r, 6);
test_remove(r, 7);
}
void test3() {
ranges r{{1,5}, {10,25}, {27,30}};
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 26);
test_add(r, 9);
test_add(r, 7);
test_remove(r, 26);
test_remove(r, 9);
test_remove(r, 7);
}
int main() {
test1();
std::cout << '\n';
test2();
std::cout << '\n';
test3();
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"log"
big "github.com/ncw/gmp"
"rcu"
)
var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)
func juggler(n int64) (int, int, *big.Int, int) {
if n < 1 {
log.Fatal("Starting value must be a positive integer.")
}
count := 0
maxCount := 0
a := big.NewInt(n)
max := big.NewInt(n)
tmp := new(big.Int)
for a.Cmp(one) != 0 {
if tmp.Rem(a, two).Cmp(zero) == 0 {
a.Sqrt(a)
} else {
tmp.Mul(a, a)
tmp.Mul(tmp, a)
a.Sqrt(tmp)
}
count++
if a.Cmp(max) > 0 {
max.Set(a)
maxCount = count
}
}
return count, maxCount, max, len(max.String())
}
func main() {
fmt.Println("n l[n] i[n] h[n]")
fmt.Println("-----------------------------------")
for n := int64(20); n < 40; n++ {
count, maxCount, max, _ := juggler(n)
cmax := rcu.Commatize(int(max.Int64()))
fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax)
}
fmt.Println()
nums := []int64{
113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,
2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,
}
fmt.Println(" n l[n] i[n] d[n]")
fmt.Println("-------------------------------------")
for _, n := range nums {
count, maxCount, _, digits := juggler(n)
cn := rcu.Commatize(int(n))
fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits))
}
}
| #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
a = sqrt(big_int(a * a * a));
++count;
if (a > max) {
max = a;
max_count = count;
}
}
return std::make_tuple(count, max_count, max, max.get_str().size());
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "n l[n] i[n] h[n]\n";
std::cout << "--------------------------------\n";
for (int n = 20; n < 40; ++n) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(2) << n << " " << std::setw(2) << count
<< " " << std::setw(2) << max_count << " " << max
<< '\n';
}
std::cout << '\n';
std::cout << " n l[n] i[n] d[n]\n";
std::cout << "----------------------------------------\n";
for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,
275485, 1267909, 2264915, 5812827, 7110201, 56261531,
92502777, 172376627, 604398963}) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(11) << n << " " << std::setw(3) << count
<< " " << std::setw(3) << max_count << " " << digits
<< '\n';
}
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"log"
big "github.com/ncw/gmp"
"rcu"
)
var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)
func juggler(n int64) (int, int, *big.Int, int) {
if n < 1 {
log.Fatal("Starting value must be a positive integer.")
}
count := 0
maxCount := 0
a := big.NewInt(n)
max := big.NewInt(n)
tmp := new(big.Int)
for a.Cmp(one) != 0 {
if tmp.Rem(a, two).Cmp(zero) == 0 {
a.Sqrt(a)
} else {
tmp.Mul(a, a)
tmp.Mul(tmp, a)
a.Sqrt(tmp)
}
count++
if a.Cmp(max) > 0 {
max.Set(a)
maxCount = count
}
}
return count, maxCount, max, len(max.String())
}
func main() {
fmt.Println("n l[n] i[n] h[n]")
fmt.Println("-----------------------------------")
for n := int64(20); n < 40; n++ {
count, maxCount, max, _ := juggler(n)
cmax := rcu.Commatize(int(max.Int64()))
fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax)
}
fmt.Println()
nums := []int64{
113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,
2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,
}
fmt.Println(" n l[n] i[n] d[n]")
fmt.Println("-------------------------------------")
for _, n := range nums {
count, maxCount, _, digits := juggler(n)
cn := rcu.Commatize(int(n))
fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits))
}
}
| #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
a = sqrt(big_int(a * a * a));
++count;
if (a > max) {
max = a;
max_count = count;
}
}
return std::make_tuple(count, max_count, max, max.get_str().size());
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "n l[n] i[n] h[n]\n";
std::cout << "--------------------------------\n";
for (int n = 20; n < 40; ++n) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(2) << n << " " << std::setw(2) << count
<< " " << std::setw(2) << max_count << " " << max
<< '\n';
}
std::cout << '\n';
std::cout << " n l[n] i[n] d[n]\n";
std::cout << "----------------------------------------\n";
for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,
275485, 1267909, 2264915, 5812827, 7110201, 56261531,
92502777, 172376627, 604398963}) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(11) << n << " " << std::setw(3) << count
<< " " << std::setw(3) << max_count << " " << digits
<< '\n';
}
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"github.com/fogleman/gg"
"github.com/trubitsyn/go-lindenmayer"
"log"
"math"
)
const twoPi = 2 * math.Pi
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h, theta float64
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2,
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
operations['+']()
operations['F']()
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
}
|
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_square {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = (size - length)/2;
y_ = length;
angle_ = 0;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F+XF+F+XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_square::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF-F+F-XF+F+XF-F+F-X";
else
t += c;
}
return t;
}
void sierpinski_square::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ += length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_square::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
line(out);
break;
case '+':
angle_ = (angle_ + 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_square.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_square s;
s.write(out, 635, 5, 5);
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
"sort"
)
const adj = 0.0001
var primes = []uint64{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
}
func gcd(x, y uint64) uint64 {
for y != 0 {
x, y = y, x%y
}
return x
}
func isSquareFree(x uint64) bool {
for _, p := range primes {
p2 := p * p
if p2 > x {
break
}
if x%p2 == 0 {
return false
}
}
return true
}
func iroot(x, p uint64) uint64 {
return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)
}
func ipow(x, p uint64) uint64 {
prod := uint64(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func powerful(n, k uint64) []uint64 {
set := make(map[uint64]bool)
var f func(m, r uint64)
f = func(m, r uint64) {
if r < k {
set[m] = true
return
}
for v := uint64(1); v <= iroot(n/m, r); v++ {
if r > k {
if !isSquareFree(v) || gcd(m, v) != 1 {
continue
}
}
f(m*ipow(v, r), r-1)
}
}
f(1, (1<<k)-1)
list := make([]uint64, 0, len(set))
for key := range set {
list = append(list, key)
}
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list
}
func main() {
power := uint64(10)
for k := uint64(2); k <= 10; k++ {
power *= 10
a := powerful(power, k)
le := len(a)
h, t := a[0:5], a[le-5:]
fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t)
}
fmt.Println()
for k := uint64(2); k <= 10; k++ {
power := uint64(1)
var counts []int
for j := uint64(0); j < k+10; j++ {
a := powerful(power, k)
counts = append(counts, len(a))
power *= 10
}
j := k + 10
fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts)
}
}
| #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"math"
"sort"
)
const adj = 0.0001
var primes = []uint64{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
}
func gcd(x, y uint64) uint64 {
for y != 0 {
x, y = y, x%y
}
return x
}
func isSquareFree(x uint64) bool {
for _, p := range primes {
p2 := p * p
if p2 > x {
break
}
if x%p2 == 0 {
return false
}
}
return true
}
func iroot(x, p uint64) uint64 {
return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)
}
func ipow(x, p uint64) uint64 {
prod := uint64(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func powerful(n, k uint64) []uint64 {
set := make(map[uint64]bool)
var f func(m, r uint64)
f = func(m, r uint64) {
if r < k {
set[m] = true
return
}
for v := uint64(1); v <= iroot(n/m, r); v++ {
if r > k {
if !isSquareFree(v) || gcd(m, v) != 1 {
continue
}
}
f(m*ipow(v, r), r-1)
}
}
f(1, (1<<k)-1)
list := make([]uint64, 0, len(set))
for key := range set {
list = append(list, key)
}
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list
}
func main() {
power := uint64(10)
for k := uint64(2); k <= 10; k++ {
power *= 10
a := powerful(power, k)
le := len(a)
h, t := a[0:5], a[le-5:]
fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t)
}
fmt.Println()
for k := uint64(2); k <= 10; k++ {
power := uint64(1)
var counts []int
for j := uint64(0); j < k+10; j++ {
a := powerful(power, k)
counts = append(counts, len(a))
power *= 10
}
j := k + 10
fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts)
}
}
| #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
|
Generate an equivalent C++ version of this Go code. | package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func reverseBytes(bytes []byte) {
for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
bytes[i], bytes[j] = bytes[j], bytes[i]
}
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
in, err := os.Open("infile.dat")
check(err)
defer in.Close()
out, err := os.Create("outfile.dat")
check(err)
record := make([]byte, 80)
empty := make([]byte, 80)
for {
n, err := in.Read(record)
if err != nil {
if n == 0 {
break
} else {
out.Close()
log.Fatal(err)
}
}
reverseBytes(record)
out.Write(record)
copy(record, empty)
}
out.Close()
cmd := exec.Command("dd", "if=outfile.dat", "cbs=80", "conv=unblock")
bytes, err := cmd.Output()
check(err)
fmt.Println(string(bytes))
}
| #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
void reverse(std::istream& in, std::ostream& out) {
constexpr size_t record_length = 80;
char record[record_length];
while (in.read(record, record_length)) {
std::reverse(std::begin(record), std::end(record));
out.write(record, record_length);
}
out.flush();
}
int main(int argc, char** argv) {
std::ifstream in("infile.dat", std::ios_base::binary);
if (!in) {
std::cerr << "Cannot open input file\n";
return EXIT_FAILURE;
}
std::ofstream out("outfile.dat", std::ios_base::binary);
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
try {
in.exceptions(std::ios_base::badbit);
out.exceptions(std::ios_base::badbit);
reverse(in, out);
} catch (const std::exception& ex) {
std::cerr << "I/O error: " << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
count := 0
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {
count++
fmt.Printf("%d: %s\n", count, s)
}
}
}
| #include <cstdlib>
#include <fstream>
#include <iostream>
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
const size_t len = word.size();
if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
std::cout << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import "fmt"
var factors []int
var inc = []int{4, 2, 4, 2, 4, 6, 2, 6}
func primeFactors(n int) {
factors = factors[:0]
factors = append(factors, 2)
last := 2
n /= 2
for n%3 == 0 {
if last == 3 {
factors = factors[:0]
return
}
last = 3
factors = append(factors, 3)
n /= 3
}
for n%5 == 0 {
if last == 5 {
factors = factors[:0]
return
}
last = 5
factors = append(factors, 5)
n /= 5
}
for k, i := 7, 0; k*k <= n; {
if n%k == 0 {
if last == k {
factors = factors[:0]
return
}
last = k
factors = append(factors, k)
n /= k
} else {
k += inc[i]
i = (i + 1) % 8
}
}
if n > 1 {
factors = append(factors, n)
}
}
func main() {
const limit = 5
var giuga []int
for n := 6; len(giuga) < limit; n += 4 {
primeFactors(n)
if len(factors) > 2 {
isGiuga := true
for _, f := range factors {
if (n/f-1)%f != 0 {
isGiuga = false
break
}
}
if isGiuga {
giuga = append(giuga, n)
}
}
}
fmt.Println("The first", limit, "Giuga numbers are:")
fmt.Println(giuga)
}
| #include <iostream>
bool is_giuga(unsigned int n) {
unsigned int m = n / 2;
auto test_factor = [&m, n](unsigned int p) -> bool {
if (m % p != 0)
return true;
m /= p;
return m % p != 0 && (n / p - 1) % p == 0;
};
if (!test_factor(3) || !test_factor(5))
return false;
static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};
for (unsigned int p = 7, i = 0; p * p <= m; ++i) {
if (!test_factor(p))
return false;
p += wheel[i & 7];
}
return m == 1 || (n / m - 1) % m == 0;
}
int main() {
std::cout << "First 5 Giuga numbers:\n";
for (unsigned int i = 0, n = 6; i < 5; n += 4) {
if (is_giuga(n)) {
std::cout << n << '\n';
++i;
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
|
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
|
Generate an equivalent C++ version of this Go code. | package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
|
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"rcu"
)
func countDivisors(n int) int {
count := 0
i := 1
k := 1
if n%2 == 1 {
k = 2
}
for ; i*i <= n; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
}
return count
}
func main() {
const limit = 1e5
var results []int
for i := 2; i * i < limit; i++ {
n := countDivisors(i * i)
if n > 2 && rcu.IsPrime(n) {
results = append(results, i * i)
}
}
climit := rcu.Commatize(limit)
fmt.Printf("Positive integers under %7s whose number of divisors is an odd prime:\n", climit)
under1000 := 0
for i, n := range results {
fmt.Printf("%7s", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
if n < 1000 {
under1000++
}
}
fmt.Printf("\n\nFound %d such integers (%d under 1,000).\n", len(results), under1000)
}
| #include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
int divisor_count(int n) {
int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (int p = 3; p * p <= n; p += 2) {
int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
int limit = 1000;
switch (argc) {
case 1:
break;
case 2:
limit = std::strtol(argv[1], nullptr, 10);
if (limit <= 0) {
std::cerr << "Invalid limit\n";
return EXIT_FAILURE;
}
break;
default:
std::cerr << "usage: " << argv[0] << " [limit]\n";
return EXIT_FAILURE;
}
int width = static_cast<int>(std::ceil(std::log10(limit)));
int count = 0;
for (int i = 1;; ++i) {
int n = i * i;
if (n >= limit)
break;
int divisors = divisor_count(n);
if (divisors != 2 && is_prime(divisors))
std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\n' : ' ');
}
std::cout << "\nCount: " << count << '\n';
return EXIT_SUCCESS;
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import (
"fmt"
"rcu"
)
func countDivisors(n int) int {
count := 0
i := 1
k := 1
if n%2 == 1 {
k = 2
}
for ; i*i <= n; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
}
return count
}
func main() {
const limit = 1e5
var results []int
for i := 2; i * i < limit; i++ {
n := countDivisors(i * i)
if n > 2 && rcu.IsPrime(n) {
results = append(results, i * i)
}
}
climit := rcu.Commatize(limit)
fmt.Printf("Positive integers under %7s whose number of divisors is an odd prime:\n", climit)
under1000 := 0
for i, n := range results {
fmt.Printf("%7s", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
if n < 1000 {
under1000++
}
}
fmt.Printf("\n\nFound %d such integers (%d under 1,000).\n", len(results), under1000)
}
| #include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
int divisor_count(int n) {
int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (int p = 3; p * p <= n; p += 2) {
int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
int limit = 1000;
switch (argc) {
case 1:
break;
case 2:
limit = std::strtol(argv[1], nullptr, 10);
if (limit <= 0) {
std::cerr << "Invalid limit\n";
return EXIT_FAILURE;
}
break;
default:
std::cerr << "usage: " << argv[0] << " [limit]\n";
return EXIT_FAILURE;
}
int width = static_cast<int>(std::ceil(std::log10(limit)));
int count = 0;
for (int i = 1;; ++i) {
int n = i * i;
if (n >= limit)
break;
int divisors = divisor_count(n);
if (divisors != 2 && is_prime(divisors))
std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\n' : ' ');
}
std::cout << "\nCount: " << count << '\n';
return EXIT_SUCCESS;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
count := 0
fmt.Println("The odd words with length > 4 in", wordList, "are:")
for _, word := range words {
rword := []rune(word)
if len(rword) > 8 {
var sb strings.Builder
for i := 0; i < len(rword); i += 2 {
sb.WriteRune(rword[i])
}
s := sb.String()
idx := sort.SearchStrings(words, s)
if idx < len(words) && words[idx] == s {
count = count + 1
fmt.Printf("%2d: %-12s -> %s\n", count, word, s)
}
}
}
}
| #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
using word_list = std::vector<std::pair<std::string, std::string>>;
void print_words(std::ostream& out, const word_list& words) {
int n = 1;
for (const auto& pair : words) {
out << std::right << std::setw(2) << n++ << ": "
<< std::left << std::setw(14) << pair.first
<< pair.second << '\n';
}
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
const int min_length = 5;
std::string line;
std::set<std::string> dictionary;
while (getline(in, line)) {
if (line.size() >= min_length)
dictionary.insert(line);
}
word_list odd_words, even_words;
for (const std::string& word : dictionary) {
if (word.size() < min_length + 2*(min_length/2))
continue;
std::string odd_word, even_word;
for (auto w = word.begin(); w != word.end(); ++w) {
odd_word += *w;
if (++w == word.end())
break;
even_word += *w;
}
if (dictionary.find(odd_word) != dictionary.end())
odd_words.emplace_back(word, odd_word);
if (dictionary.find(even_word) != dictionary.end())
even_words.emplace_back(word, even_word);
}
std::cout << "Odd words:\n";
print_words(std::cout, odd_words);
std::cout << "\nEven words:\n";
print_words(std::cout, even_words);
return EXIT_SUCCESS;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"fmt"
"io"
"os"
"strings"
)
type nNode struct {
name string
children []nNode
}
type iNode struct {
level int
name string
}
func printNest(n nNode, level int, w io.Writer) {
if level == 0 {
fmt.Fprintln(w, "\n==Nest form==\n")
}
fmt.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name)
for _, c := range n.children {
fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1))
printNest(c, level+1, w)
}
}
func toNest(iNodes []iNode, start, level int, n *nNode) {
if level == 0 {
n.name = iNodes[0].name
}
for i := start + 1; i < len(iNodes); i++ {
if iNodes[i].level == level+1 {
c := nNode{iNodes[i].name, nil}
toNest(iNodes, i, level+1, &c)
n.children = append(n.children, c)
} else if iNodes[i].level <= level {
return
}
}
}
func printIndent(iNodes []iNode, w io.Writer) {
fmt.Fprintln(w, "\n==Indent form==\n")
for _, n := range iNodes {
fmt.Fprintf(w, "%d %s\n", n.level, n.name)
}
}
func toIndent(n nNode, level int, iNodes *[]iNode) {
*iNodes = append(*iNodes, iNode{level, n.name})
for _, c := range n.children {
toIndent(c, level+1, iNodes)
}
}
func main() {
n1 := nNode{"RosettaCode", nil}
n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}}
n3 := nNode{"mocks", []nNode{{"trolling", nil}}}
n1.children = append(n1.children, n2, n3)
var sb strings.Builder
printNest(n1, 0, &sb)
s1 := sb.String()
fmt.Print(s1)
var iNodes []iNode
toIndent(n1, 0, &iNodes)
printIndent(iNodes, os.Stdout)
var n nNode
toNest(iNodes, 0, 0, &n)
sb.Reset()
printNest(n, 0, &sb)
s2 := sb.String()
fmt.Print(s2)
fmt.Println("\nRound trip test satisfied? ", s1 == s2)
}
| #include <iomanip>
#include <iostream>
#include <list>
#include <string>
#include <vector>
#include <utility>
#include <vector>
class nest_tree;
bool operator==(const nest_tree&, const nest_tree&);
class nest_tree {
public:
explicit nest_tree(const std::string& name) : name_(name) {}
nest_tree& add_child(const std::string& name) {
children_.emplace_back(name);
return children_.back();
}
void print(std::ostream& out) const {
print(out, 0);
}
const std::string& name() const {
return name_;
}
const std::list<nest_tree>& children() const {
return children_;
}
bool equals(const nest_tree& n) const {
return name_ == n.name_ && children_ == n.children_;
}
private:
void print(std::ostream& out, int level) const {
std::string indent(level * 4, ' ');
out << indent << name_ << '\n';
for (const nest_tree& child : children_)
child.print(out, level + 1);
}
std::string name_;
std::list<nest_tree> children_;
};
bool operator==(const nest_tree& a, const nest_tree& b) {
return a.equals(b);
}
class indent_tree {
public:
explicit indent_tree(const nest_tree& n) {
items_.emplace_back(0, n.name());
from_nest(n, 0);
}
void print(std::ostream& out) const {
for (const auto& item : items_)
std::cout << item.first << ' ' << item.second << '\n';
}
nest_tree to_nest() const {
nest_tree n(items_[0].second);
to_nest_(n, 1, 0);
return n;
}
private:
void from_nest(const nest_tree& n, int level) {
for (const nest_tree& child : n.children()) {
items_.emplace_back(level + 1, child.name());
from_nest(child, level + 1);
}
}
size_t to_nest_(nest_tree& n, size_t pos, int level) const {
while (pos < items_.size() && items_[pos].first == level + 1) {
nest_tree& child = n.add_child(items_[pos].second);
pos = to_nest_(child, pos + 1, level + 1);
}
return pos;
}
std::vector<std::pair<int, std::string>> items_;
};
int main() {
nest_tree n("RosettaCode");
auto& child1 = n.add_child("rocks");
auto& child2 = n.add_child("mocks");
child1.add_child("code");
child1.add_child("comparison");
child1.add_child("wiki");
child2.add_child("trolling");
std::cout << "Initial nest format:\n";
n.print(std::cout);
indent_tree i(n);
std::cout << "\nIndent format:\n";
i.print(std::cout);
nest_tree n2(i.to_nest());
std::cout << "\nFinal nest format:\n";
n2.print(std::cout);
std::cout << "\nAre initial and final nest formats equal? "
<< std::boolalpha << n.equals(n2) << '\n';
return 0;
}
|
Write a version of this Go function in C++ with identical behavior. | package main
import (
"fmt"
"strings"
)
func main() {
s := "abracadabra"
ss := []byte(s)
var ixs []int
for ix, c := range s {
if c == 'a' {
ixs = append(ixs, ix)
}
}
repl := "ABaCD"
for i := 0; i < 5; i++ {
ss[ixs[i]] = repl[i]
}
s = string(ss)
s = strings.Replace(s, "b", "E", 1)
s = strings.Replace(s, "r", "F", 2)
s = strings.Replace(s, "F", "r", 1)
fmt.Println(s)
}
| #include <map>
#include <iostream>
#include <string>
int main()
{
std::map<char, std::string> rep =
{{'a', "DCaBA"},
{'b', "E"},
{'r', "Fr"}};
std::string magic = "abracadabra";
for(auto it = magic.begin(); it != magic.end(); ++it)
{
if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())
{
*it = f->second.back();
f->second.pop_back();
}
}
std::cout << magic << "\n";
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"fmt"
"strings"
)
func main() {
s := "abracadabra"
ss := []byte(s)
var ixs []int
for ix, c := range s {
if c == 'a' {
ixs = append(ixs, ix)
}
}
repl := "ABaCD"
for i := 0; i < 5; i++ {
ss[ixs[i]] = repl[i]
}
s = string(ss)
s = strings.Replace(s, "b", "E", 1)
s = strings.Replace(s, "r", "F", 2)
s = strings.Replace(s, "F", "r", 1)
fmt.Println(s)
}
| #include <map>
#include <iostream>
#include <string>
int main()
{
std::map<char, std::string> rep =
{{'a', "DCaBA"},
{'b', "E"},
{'r', "Fr"}};
std::string magic = "abracadabra";
for(auto it = magic.begin(); it != magic.end(); ++it)
{
if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())
{
*it = f->second.back();
f->second.pop_back();
}
}
std::cout << magic << "\n";
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
if s.ProbablyPrime(15) {
rPrimes = append(rPrimes, p)
}
}
fmt.Printf("Base %2d: %v\n", b, rPrimes)
}
}
| #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
mpz_class repunit(std::string(prime, '1'), base);
if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
result.push_back(prime);
}
return result;
}
int main() {
std::vector<uint64_t> primes;
const uint64_t limit = 2700;
primesieve::generate_primes(limit, &primes);
std::vector<std::future<std::vector<uint64_t>>> futures;
for (uint32_t base = 2; base <= 36; ++base) {
futures.push_back(std::async(repunit_primes, base, primes));
}
std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
std::cout << "Base " << std::setw(2) << base << ':';
for (auto digits : futures[i].get())
std::cout << ' ' << digits;
std::cout << '\n';
}
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
if s.ProbablyPrime(15) {
rPrimes = append(rPrimes, p)
}
}
fmt.Printf("Base %2d: %v\n", b, rPrimes)
}
}
| #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
mpz_class repunit(std::string(prime, '1'), base);
if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
result.push_back(prime);
}
return result;
}
int main() {
std::vector<uint64_t> primes;
const uint64_t limit = 2700;
primesieve::generate_primes(limit, &primes);
std::vector<std::future<std::vector<uint64_t>>> futures;
for (uint32_t base = 2; base <= 36; ++base) {
futures.push_back(std::async(repunit_primes, base, primes));
}
std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
std::cout << "Base " << std::setw(2) << base << ':';
for (auto digits : futures[i].get())
std::cout << ' ' << digits;
std::cout << '\n';
}
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import (
"fmt"
"math/big"
)
func main() {
zero := big.NewInt(0)
one := big.NewInt(1)
for k := int64(2); k <= 10; k += 2 {
bk := big.NewInt(k)
fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
count := 0
n := int64(1)
pow := big.NewInt(k)
z := new(big.Int)
var curzon50 []int64
for {
z.Add(pow, one)
d := k*n + 1
bd := big.NewInt(d)
if z.Rem(z, bd).Cmp(zero) == 0 {
if count < 50 {
curzon50 = append(curzon50, n)
}
count++
if count == 50 {
for i := 0; i < len(curzon50); i++ {
fmt.Printf("%4d ", curzon50[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Print("\nOne thousandth: ")
}
if count == 1000 {
fmt.Println(n)
break
}
}
n++
pow.Mul(pow, bk)
}
fmt.Println()
}
}
| #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_curzon(uint64_t n, uint64_t k) {
const uint64_t r = k * n;
return modpow(k, n, r + 1) == r;
}
int main() {
for (uint64_t k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
uint64_t count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import (
"fmt"
"math/big"
)
func main() {
zero := big.NewInt(0)
one := big.NewInt(1)
for k := int64(2); k <= 10; k += 2 {
bk := big.NewInt(k)
fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
count := 0
n := int64(1)
pow := big.NewInt(k)
z := new(big.Int)
var curzon50 []int64
for {
z.Add(pow, one)
d := k*n + 1
bd := big.NewInt(d)
if z.Rem(z, bd).Cmp(zero) == 0 {
if count < 50 {
curzon50 = append(curzon50, n)
}
count++
if count == 50 {
for i := 0; i < len(curzon50); i++ {
fmt.Printf("%4d ", curzon50[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Print("\nOne thousandth: ")
}
if count == 1000 {
fmt.Println(n)
break
}
}
n++
pow.Mul(pow, bk)
}
fmt.Println()
}
}
| #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_curzon(uint64_t n, uint64_t k) {
const uint64_t r = k * n;
return modpow(k, n, r + 1) == r;
}
int main() {
for (uint64_t k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
uint64_t count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
}
|
Write a version of this Go function in C++ with identical behavior. | package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
| #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
| #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
| #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import (
"fmt"
"reflect"
)
type example struct{}
func (example) Foo() int {
return 42
}
func (e example) CallMethod(n string) int {
if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {
return int(m.Call(nil)[0].Int())
}
fmt.Println("Unknown method:", n)
return 0
}
func main() {
var e example
fmt.Println(e.CallMethod("Foo"))
fmt.Println(e.CallMethod("Bar"))
}
| class animal {
public:
virtual void bark()
{
throw "implement me: do not know how to bark";
}
};
class elephant : public animal
{
};
int main()
{
elephant e;
e.bark();
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import (
"fmt"
"strings"
)
type dict map[string]bool
func newDict(words ...string) dict {
d := dict{}
for _, w := range words {
d[w] = true
}
return d
}
func (d dict) wordBreak(s string) (broken []string, ok bool) {
if s == "" {
return nil, true
}
type prefix struct {
length int
broken []string
}
bp := []prefix{{0, nil}}
for end := 1; end <= len(s); end++ {
for i := len(bp) - 1; i >= 0; i-- {
w := s[bp[i].length:end]
if d[w] {
b := append(bp[i].broken, w)
if end == len(s) {
return b, true
}
bp = append(bp, prefix{end, b})
break
}
}
}
return nil, false
}
func main() {
d := newDict("a", "bc", "abc", "cd", "b")
for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} {
if b, ok := d.wordBreak(s); ok {
fmt.Printf("%s: %s\n", s, strings.Join(b, " "))
} else {
fmt.Println("can't break")
}
}
}
| #include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
struct string_comparator {
using is_transparent = void;
bool operator()(const std::string& lhs, const std::string& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string& lhs, const std::string_view& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string_view& lhs, const std::string& rhs) const {
return lhs < rhs;
}
};
using dictionary = std::set<std::string, string_comparator>;
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
auto create_string(const std::string_view& s,
const std::vector<std::optional<size_t>>& v) {
auto idx = s.size();
std::vector<std::string_view> sv;
while (v[idx].has_value()) {
size_t prev = v[idx].value();
sv.push_back(s.substr(prev, idx - prev));
idx = prev;
}
std::reverse(sv.begin(), sv.end());
return join(sv.begin(), sv.end(), ' ');
}
std::optional<std::string> word_break(const std::string_view& str,
const dictionary& dict) {
auto size = str.size() + 1;
std::vector<std::optional<size_t>> possible(size);
auto check_word = [&dict, &str](size_t i, size_t j)
-> std::optional<size_t> {
if (dict.find(str.substr(i, j - i)) != dict.end())
return i;
return std::nullopt;
};
for (size_t i = 1; i < size; ++i) {
if (!possible[i].has_value())
possible[i] = check_word(0, i);
if (possible[i].has_value()) {
for (size_t j = i + 1; j < size; ++j) {
if (!possible[j].has_value())
possible[j] = check_word(i, j);
}
if (possible[str.size()].has_value())
return create_string(str, possible);
}
}
return std::nullopt;
}
int main(int argc, char** argv) {
dictionary dict;
dict.insert("a");
dict.insert("bc");
dict.insert("abc");
dict.insert("cd");
dict.insert("b");
auto result = word_break("abcd", dict);
if (result.has_value())
std::cout << result.value() << '\n';
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
var primes = rcu.Primes(1e8 - 1)
type res struct {
bc interface{}
next int
}
func getBrilliant(digits, limit int, countOnly bool) res {
var brilliant []int
count := 0
pow := 1
next := math.MaxInt
for k := 1; k <= digits; k++ {
var s []int
for _, p := range primes {
if p >= pow*10 {
break
}
if p > pow {
s = append(s, p)
}
}
for i := 0; i < len(s); i++ {
for j := i; j < len(s); j++ {
prod := s[i] * s[j]
if prod < limit {
if countOnly {
count++
} else {
brilliant = append(brilliant, prod)
}
} else {
if next > prod {
next = prod
}
break
}
}
}
pow *= 10
}
if countOnly {
return res{count, next}
}
return res{brilliant, next}
}
func main() {
fmt.Println("First 100 brilliant numbers:")
brilliant := getBrilliant(2, 10000, false).bc.([]int)
sort.Ints(brilliant)
brilliant = brilliant[0:100]
for i := 0; i < len(brilliant); i++ {
fmt.Printf("%4d ", brilliant[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
for k := 1; k <= 13; k++ {
limit := int(math.Pow(10, float64(k)))
r := getBrilliant(k, limit, true)
total := r.bc.(int)
next := r.next
climit := rcu.Commatize(limit)
ctotal := rcu.Commatize(total + 1)
cnext := rcu.Commatize(next)
fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
}
}
| #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
|
Generate an equivalent C++ version of this Go code. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
var primes = rcu.Primes(1e8 - 1)
type res struct {
bc interface{}
next int
}
func getBrilliant(digits, limit int, countOnly bool) res {
var brilliant []int
count := 0
pow := 1
next := math.MaxInt
for k := 1; k <= digits; k++ {
var s []int
for _, p := range primes {
if p >= pow*10 {
break
}
if p > pow {
s = append(s, p)
}
}
for i := 0; i < len(s); i++ {
for j := i; j < len(s); j++ {
prod := s[i] * s[j]
if prod < limit {
if countOnly {
count++
} else {
brilliant = append(brilliant, prod)
}
} else {
if next > prod {
next = prod
}
break
}
}
}
pow *= 10
}
if countOnly {
return res{count, next}
}
return res{brilliant, next}
}
func main() {
fmt.Println("First 100 brilliant numbers:")
brilliant := getBrilliant(2, 10000, false).bc.([]int)
sort.Ints(brilliant)
brilliant = brilliant[0:100]
for i := 0; i < len(brilliant); i++ {
fmt.Printf("%4d ", brilliant[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
for k := 1; k <= 13; k++ {
limit := int(math.Pow(10, float64(k)))
r := getBrilliant(k, limit, true)
total := r.bc.(int)
next := r.next
climit := rcu.Commatize(limit)
ctotal := rcu.Commatize(total + 1)
cnext := rcu.Commatize(next)
fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
}
}
| #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func contains(a []string, s string) bool {
for _, e := range a {
if e == s {
return true
}
}
return false
}
func oneAway(a, b string) bool {
sum := 0
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
sum++
}
}
return sum == 1
}
func wordLadder(words []string, a, b string) {
l := len(a)
var poss []string
for _, word := range words {
if len(word) == l {
poss = append(poss, word)
}
}
todo := [][]string{{a}}
for len(todo) > 0 {
curr := todo[0]
todo = todo[1:]
var next []string
for _, word := range poss {
if oneAway(word, curr[len(curr)-1]) {
next = append(next, word)
}
}
if contains(next, b) {
curr = append(curr, b)
fmt.Println(strings.Join(curr, " -> "))
return
}
for i := len(poss) - 1; i >= 0; i-- {
if contains(next, poss[i]) {
copy(poss[i:], poss[i+1:])
poss[len(poss)-1] = ""
poss = poss[:len(poss)-1]
}
}
for _, s := range next {
temp := make([]string, len(curr))
copy(temp, curr)
temp = append(temp, s)
todo = append(todo, temp)
}
}
fmt.Println(a, "into", b, "cannot be done.")
}
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
pairs := [][]string{
{"boy", "man"},
{"girl", "lady"},
{"john", "jane"},
{"child", "adult"},
}
for _, pair := range pairs {
wordLadder(words, pair[0], pair[1])
}
}
| #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() != s2.size())
return false;
bool result = false;
for (size_t i = 0, n = s1.size(); i != n; ++i) {
if (s1[i] != s2[i]) {
if (result)
return false;
result = true;
}
}
return result;
}
template <typename iterator_type, typename separator_type>
std::string join(iterator_type begin, iterator_type end,
separator_type separator) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += separator;
result += *begin;
}
}
return result;
}
bool word_ladder(const word_map& words, const std::string& from,
const std::string& to) {
auto w = words.find(from.size());
if (w != words.end()) {
auto poss = w->second;
std::vector<std::vector<std::string>> queue{{from}};
while (!queue.empty()) {
auto curr = queue.front();
queue.erase(queue.begin());
for (auto i = poss.begin(); i != poss.end();) {
if (!one_away(*i, curr.back())) {
++i;
continue;
}
if (to == *i) {
curr.push_back(to);
std::cout << join(curr.begin(), curr.end(), " -> ") << '\n';
return true;
}
std::vector<std::string> temp(curr);
temp.push_back(*i);
queue.push_back(std::move(temp));
i = poss.erase(i);
}
}
}
std::cout << from << " into " << to << " cannot be done.\n";
return false;
}
int main() {
word_map words;
std::ifstream in("unixdict.txt");
if (!in) {
std::cerr << "Cannot open file unixdict.txt.\n";
return EXIT_FAILURE;
}
std::string word;
while (getline(in, word))
words[word.size()].push_back(word);
word_ladder(words, "boy", "man");
word_ladder(words, "girl", "lady");
word_ladder(words, "john", "jane");
word_ladder(words, "child", "adult");
word_ladder(words, "cat", "dog");
word_ladder(words, "lead", "gold");
word_ladder(words, "white", "black");
word_ladder(words, "bubble", "tickle");
return EXIT_SUCCESS;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"fmt"
"log"
"rcu"
"sort"
)
func ord(n int) string {
if n < 0 {
log.Fatal("Argument must be a non-negative integer.")
}
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%sth", rcu.Commatize(n))
}
m %= 10
suffix := "th"
if m == 1 {
suffix = "st"
} else if m == 2 {
suffix = "nd"
} else if m == 3 {
suffix = "rd"
}
return fmt.Sprintf("%s%s", rcu.Commatize(n), suffix)
}
func main() {
limit := int(4 * 1e8)
c := rcu.PrimeSieve(limit-1, true)
var compSums []int
var primeSums []int
csum := 0
psum := 0
for i := 2; i < limit; i++ {
if c[i] {
csum += i
compSums = append(compSums, csum)
} else {
psum += i
primeSums = append(primeSums, psum)
}
}
for i := 0; i < len(primeSums); i++ {
ix := sort.SearchInts(compSums, primeSums[i])
if ix < len(compSums) && compSums[ix] == primeSums[i] {
cps := rcu.Commatize(primeSums[i])
fmt.Printf("%21s - %12s prime sum, %12s composite sum\n", cps, ord(i+1), ord(ix+1))
}
}
}
| #include <primesieve.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
class composite_iterator {
public:
composite_iterator();
uint64_t next_composite();
private:
uint64_t composite;
uint64_t prime;
primesieve::iterator pi;
};
composite_iterator::composite_iterator() {
composite = prime = pi.next_prime();
for (; composite == prime; ++composite)
prime = pi.next_prime();
}
uint64_t composite_iterator::next_composite() {
uint64_t result = composite;
while (++composite == prime)
prime = pi.next_prime();
return result;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
composite_iterator ci;
primesieve::iterator pi;
uint64_t prime_sum = pi.next_prime();
uint64_t composite_sum = ci.next_composite();
uint64_t prime_index = 1, composite_index = 1;
std::cout << "Sum | Prime Index | Composite Index\n";
std::cout << "------------------------------------------------------\n";
for (int count = 0; count < 11;) {
if (prime_sum == composite_sum) {
std::cout << std::right << std::setw(21) << prime_sum << " | "
<< std::setw(12) << prime_index << " | " << std::setw(15)
<< composite_index << '\n';
composite_sum += ci.next_composite();
prime_sum += pi.next_prime();
++prime_index;
++composite_index;
++count;
} else if (prime_sum < composite_sum) {
prime_sum += pi.next_prime();
++prime_index;
} else {
composite_sum += ci.next_composite();
++composite_index;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"github.com/nsf/termbox-go"
"github.com/simulatedsimian/joystick"
"log"
"os"
"strconv"
"time"
)
func printAt(x, y int, s string) {
for _, r := range s {
termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)
x++
}
}
func readJoystick(js joystick.Joystick, hidden bool) {
jinfo, err := js.Read()
check(err)
w, h := termbox.Size()
tbcd := termbox.ColorDefault
termbox.Clear(tbcd, tbcd)
printAt(1, h-1, "q - quit")
if hidden {
printAt(11, h-1, "s - show buttons:")
} else {
bs := ""
printAt(11, h-1, "h - hide buttons:")
for button := 0; button < js.ButtonCount(); button++ {
if jinfo.Buttons&(1<<uint32(button)) != 0 {
bs += fmt.Sprintf(" %X", button+1)
}
}
printAt(28, h-1, bs)
}
x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)
y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)
printAt(x, y, "+")
termbox.Flush()
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
jsid := 0
if len(os.Args) > 1 {
i, err := strconv.Atoi(os.Args[1])
check(err)
jsid = i
}
js, jserr := joystick.Open(jsid)
check(jserr)
err := termbox.Init()
check(err)
defer termbox.Close()
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
ticker := time.NewTicker(time.Millisecond * 40)
hidden := false
for doQuit := false; !doQuit; {
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Ch == 'q' {
doQuit = true
} else if ev.Ch == 'h' {
hidden = true
} else if ev.Ch == 's' {
hidden = false
}
}
if ev.Type == termbox.EventResize {
termbox.Flush()
}
case <-ticker.C:
readJoystick(js, hidden)
}
}
}
| #include <stdio.h>
#include <stdlib.h>
void clear() {
for(int n = 0;n < 10; n++) {
printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n");
}
}
#define UP "00^00\r\n00|00\r\n00000\r\n"
#define DOWN "00000\r\n00|00\r\n00v00\r\n"
#define LEFT "00000\r\n<--00\r\n00000\r\n"
#define RIGHT "00000\r\n00-->\r\n00000\r\n"
#define HOME "00000\r\n00+00\r\n00000\r\n"
int main() {
clear();
system("stty raw");
printf(HOME);
printf("space to exit; wasd to move\r\n");
char c = 1;
while(c) {
c = getc(stdin);
clear();
switch (c)
{
case 'a':
printf(LEFT);
break;
case 'd':
printf(RIGHT);
break;
case 'w':
printf(UP);
break;
case 's':
printf(DOWN);
break;
case ' ':
c = 0;
break;
default:
printf(HOME);
};
printf("space to exit; wasd key to move\r\n");
}
system("stty cooked");
system("clear");
return 1;
}
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package main
import (
"fmt"
"rcu"
)
func main() {
limit := int(1e9)
gapStarts := make(map[int]int)
primes := rcu.Primes(limit * 5)
for i := 1; i < len(primes); i++ {
gap := primes[i] - primes[i-1]
if _, ok := gapStarts[gap]; !ok {
gapStarts[gap] = primes[i-1]
}
}
pm := 10
gap1 := 2
for {
for _, ok := gapStarts[gap1]; !ok; {
gap1 += 2
}
start1 := gapStarts[gap1]
gap2 := gap1 + 2
if _, ok := gapStarts[gap2]; !ok {
gap1 = gap2 + 2
continue
}
start2 := gapStarts[gap2]
diff := start2 - start1
if diff < 0 {
diff = -diff
}
if diff > pm {
cpm := rcu.Commatize(pm)
cst1 := rcu.Commatize(start1)
cst2 := rcu.Commatize(start2)
cd := rcu.Commatize(diff)
fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm)
fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd)
if pm == limit {
break
}
pm *= 10
} else {
gap1 = gap2
}
}
}
| #include <iostream>
#include <locale>
#include <unordered_map>
#include <primesieve.hpp>
class prime_gaps {
public:
prime_gaps() { last_prime_ = iterator_.next_prime(); }
uint64_t find_gap_start(uint64_t gap);
private:
primesieve::iterator iterator_;
uint64_t last_prime_;
std::unordered_map<uint64_t, uint64_t> gap_starts_;
};
uint64_t prime_gaps::find_gap_start(uint64_t gap) {
auto i = gap_starts_.find(gap);
if (i != gap_starts_.end())
return i->second;
for (;;) {
uint64_t prev = last_prime_;
last_prime_ = iterator_.next_prime();
uint64_t diff = last_prime_ - prev;
gap_starts_.emplace(diff, prev);
if (gap == diff)
return prev;
}
}
int main() {
std::cout.imbue(std::locale(""));
const uint64_t limit = 100000000000;
prime_gaps pg;
for (uint64_t pm = 10, gap1 = 2;;) {
uint64_t start1 = pg.find_gap_start(gap1);
uint64_t gap2 = gap1 + 2;
uint64_t start2 = pg.find_gap_start(gap2);
uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
std::cout << "Earliest difference > " << pm
<< " between adjacent prime gap starting primes:\n"
<< "Gap " << gap1 << " starts at " << start1 << ", gap "
<< gap2 << " starts at " << start2 << ", difference is "
<< diff << ".\n\n";
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import (
"fmt"
"sort"
)
type matrix [][]int
func dList(n, start int) (r matrix) {
start--
a := make([]int, n)
for i := range a {
a[i] = i
}
a[0], a[start] = start, a[0]
sort.Ints(a[1:])
first := a[1]
var recurse func(last int)
recurse = func(last int) {
if last == first {
for j, v := range a[1:] {
if j+1 == v {
return
}
}
b := make([]int, n)
copy(b, a)
for i := range b {
b[i]++
}
r = append(r, b)
return
}
for i := last; i >= 1; i-- {
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
}
}
recurse(n - 1)
return
}
func reducedLatinSquare(n int, echo bool) uint64 {
if n <= 0 {
if echo {
fmt.Println("[]\n")
}
return 0
} else if n == 1 {
if echo {
fmt.Println("[1]\n")
}
return 1
}
rlatin := make(matrix, n)
for i := 0; i < n; i++ {
rlatin[i] = make([]int, n)
}
for j := 0; j < n; j++ {
rlatin[0][j] = j + 1
}
count := uint64(0)
var recurse func(i int)
recurse = func(i int) {
rows := dList(n, i)
outer:
for r := 0; r < len(rows); r++ {
copy(rlatin[i-1], rows[r])
for k := 0; k < i-1; k++ {
for j := 1; j < n; j++ {
if rlatin[k][j] == rlatin[i-1][j] {
if r < len(rows)-1 {
continue outer
} else if i > 2 {
return
}
}
}
}
if i < n {
recurse(i + 1)
} else {
count++
if echo {
printSquare(rlatin, n)
}
}
}
return
}
recurse(2)
return count
}
func printSquare(latin matrix, n int) {
for i := 0; i < n; i++ {
fmt.Println(latin[i])
}
fmt.Println()
}
func factorial(n uint64) uint64 {
if n == 0 {
return 1
}
prod := uint64(1)
for i := uint64(2); i <= n; i++ {
prod *= i
}
return prod
}
func main() {
fmt.Println("The four reduced latin squares of order 4 are:\n")
reducedLatinSquare(4, true)
fmt.Println("The size of the set of reduced latin squares for the following orders")
fmt.Println("and hence the total number of latin squares of these orders are:\n")
for n := uint64(1); n <= 6; n++ {
size := reducedLatinSquare(int(n), false)
f := factorial(n - 1)
f *= f * n * size
fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f)
}
}
| #include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
typedef std::vector<std::vector<int>> matrix;
matrix dList(int n, int start) {
start--;
std::vector<int> a(n);
std::iota(a.begin(), a.end(), 0);
a[start] = a[0];
a[0] = start;
std::sort(a.begin() + 1, a.end());
auto first = a[1];
matrix r;
std::function<void(int)> recurse;
recurse = [&](int last) {
if (last == first) {
for (size_t j = 1; j < a.size(); j++) {
auto v = a[j];
if (j == v) {
return;
}
}
std::vector<int> b;
std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });
r.push_back(b);
return;
}
for (int i = last; i >= 1; i--) {
std::swap(a[i], a[last]);
recurse(last - 1);
std::swap(a[i], a[last]);
}
};
recurse(n - 1);
return r;
}
void printSquare(const matrix &latin, int n) {
for (auto &row : latin) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
std::cout << '\n';
}
unsigned long reducedLatinSquares(int n, bool echo) {
if (n <= 0) {
if (echo) {
std::cout << "[]\n";
}
return 0;
} else if (n == 1) {
if (echo) {
std::cout << "[1]\n";
}
return 1;
}
matrix rlatin;
for (int i = 0; i < n; i++) {
rlatin.push_back({});
for (int j = 0; j < n; j++) {
rlatin[i].push_back(j);
}
}
for (int j = 0; j < n; j++) {
rlatin[0][j] = j + 1;
}
unsigned long count = 0;
std::function<void(int)> recurse;
recurse = [&](int i) {
auto rows = dList(n, i);
for (size_t r = 0; r < rows.size(); r++) {
rlatin[i - 1] = rows[r];
for (int k = 0; k < i - 1; k++) {
for (int j = 1; j < n; j++) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.size() - 1) {
goto outer;
}
if (i > 2) {
return;
}
}
}
}
if (i < n) {
recurse(i + 1);
} else {
count++;
if (echo) {
printSquare(rlatin, n);
}
}
outer: {}
}
};
recurse(2);
return count;
}
unsigned long factorial(unsigned long n) {
if (n <= 0) return 1;
unsigned long prod = 1;
for (unsigned long i = 2; i <= n; i++) {
prod *= i;
}
return prod;
}
int main() {
std::cout << "The four reduced lating squares of order 4 are:\n";
reducedLatinSquares(4, true);
std::cout << "The size of the set of reduced latin squares for the following orders\n";
std::cout << "and hence the total number of latin squares of these orders are:\n\n";
for (int n = 1; n < 7; n++) {
auto size = reducedLatinSquares(n, false);
auto f = factorial(n - 1);
f *= f * n * size;
std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n';
}
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"rcu"
)
func main() {
const limit = 1e9
primes := rcu.Primes(limit)
var orm30 [][2]int
j := int(1e5)
count := 0
var counts []int
for i := 0; i < len(primes)-1; i++ {
p1 := primes[i]
p2 := primes[i+1]
if (p2-p1)%18 != 0 {
continue
}
key1 := 1
for _, dig := range rcu.Digits(p1, 10) {
key1 *= primes[dig]
}
key2 := 1
for _, dig := range rcu.Digits(p2, 10) {
key2 *= primes[dig]
}
if key1 == key2 {
if count < 30 {
orm30 = append(orm30, [2]int{p1, p2})
}
if p1 >= j {
counts = append(counts, count)
j *= 10
}
count++
}
}
counts = append(counts, count)
fmt.Println("First 30 Ormiston pairs:")
for i := 0; i < 30; i++ {
fmt.Printf("%5v ", orm30[i])
if (i+1)%3 == 0 {
fmt.Println()
}
}
fmt.Println()
j = int(1e5)
for i := 0; i < len(counts); i++ {
fmt.Printf("%s Ormiston pairs before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j))
j *= 10
}
}
| #include <array>
#include <iomanip>
#include <iostream>
#include <utility>
#include <primesieve.hpp>
class ormiston_pair_generator {
public:
ormiston_pair_generator() { prime_ = pi_.next_prime(); }
std::pair<uint64_t, uint64_t> next_pair() {
for (;;) {
uint64_t prime = prime_;
auto digits = digits_;
prime_ = pi_.next_prime();
digits_ = get_digits(prime_);
if (digits_ == digits)
return std::make_pair(prime, prime_);
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
uint64_t prime_;
std::array<int, 10> digits_;
};
int main() {
ormiston_pair_generator generator;
int count = 0;
std::cout << "First 30 Ormiston pairs:\n";
for (; count < 30; ++count) {
auto [p1, p2] = generator.next_pair();
std::cout << '(' << std::setw(5) << p1 << ", " << std::setw(5) << p2
<< ')' << ((count + 1) % 3 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {
auto [p1, p2] = generator.next_pair();
if (p1 > limit) {
std::cout << "Number of Ormiston pairs < " << limit << ": " << count
<< '\n';
limit *= 10;
}
}
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import (
"fmt"
"regexp"
)
var bits = []string{
"0 0 0 1 1 0 1 ",
"0 0 1 1 0 0 1 ",
"0 0 1 0 0 1 1 ",
"0 1 1 1 1 0 1 ",
"0 1 0 0 0 1 1 ",
"0 1 1 0 0 0 1 ",
"0 1 0 1 1 1 1 ",
"0 1 1 1 0 1 1 ",
"0 1 1 0 1 1 1 ",
"0 0 0 1 0 1 1 ",
}
var (
lhs = make(map[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
}
expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
rx := regexp.MustCompile(expr)
fmt.Println("UPC-A barcodes:")
for i, bc := range barcodes {
for j := 0; j <= 1; j++ {
if !rx.MatchString(bc) {
fmt.Printf("%2d: Invalid format\n", i+1)
break
}
codes := rx.FindStringSubmatch(bc)
digits := make([]int, 12)
var invalid, ok bool
for i := 1; i <= 6; i++ {
digits[i-1], ok = lhs[codes[i]]
if !ok {
invalid = true
}
digits[i+5], ok = rhs[codes[i+6]]
if !ok {
invalid = true
}
}
if invalid {
if j == 0 {
bc = reverse(bc)
continue
} else {
fmt.Printf("%2d: Invalid digit(s)\n", i+1)
break
}
}
sum := 0
for i, d := range digits {
sum += weights[i] * d
}
if sum%10 != 0 {
fmt.Printf("%2d: Checksum error\n", i+1)
break
} else {
ud := ""
if j == 1 {
ud = "(upside down)"
}
fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
break
}
}
}
}
| #include <iostream>
#include <locale>
#include <map>
#include <vector>
std::string trim(const std::string &str) {
auto s = str;
auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(it1.base(), s.end());
auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(s.begin(), it2);
return s;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
const std::map<std::string, int> LEFT_DIGITS = {
{" ## #", 0},
{" ## #", 1},
{" # ##", 2},
{" #### #", 3},
{" # ##", 4},
{" ## #", 5},
{" # ####", 6},
{" ### ##", 7},
{" ## ###", 8},
{" # ##", 9}
};
const std::map<std::string, int> RIGHT_DIGITS = {
{"### # ", 0},
{"## ## ", 1},
{"## ## ", 2},
{"# # ", 3},
{"# ### ", 4},
{"# ### ", 5},
{"# # ", 6},
{"# # ", 7},
{"# # ", 8},
{"### # ", 9}
};
const std::string END_SENTINEL = "# #";
const std::string MID_SENTINEL = " # # ";
void decodeUPC(const std::string &input) {
auto decode = [](const std::string &candidate) {
using OT = std::vector<int>;
OT output;
size_t pos = 0;
auto part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = LEFT_DIGITS.find(part);
if (e != LEFT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, MID_SENTINEL.length());
if (part == MID_SENTINEL) {
pos += MID_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = RIGHT_DIGITS.find(part);
if (e != RIGHT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
int sum = 0;
for (size_t i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output[i];
} else {
sum += output[i];
}
}
return std::make_pair(sum % 10 == 0, output);
};
auto candidate = trim(input);
auto out = decode(candidate);
if (out.first) {
std::cout << out.second << '\n';
} else {
std::reverse(candidate.begin(), candidate.end());
out = decode(candidate);
if (out.first) {
std::cout << out.second << " Upside down\n";
} else if (out.second.size()) {
std::cout << "Invalid checksum\n";
} else {
std::cout << "Invalid digit(s)\n";
}
}
}
int main() {
std::vector<std::string> barcodes = {
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
};
for (auto &barcode : barcodes) {
decodeUPC(barcode);
}
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type playfairOption int
const (
noQ playfairOption = iota
iEqualsJ
)
type playfair struct {
keyword string
pfo playfairOption
table [5][5]byte
}
func (p *playfair) init() {
var used [26]bool
if p.pfo == noQ {
used[16] = true
} else {
used[9] = true
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
plainText = strings.ToUpper(plainText)
var cleanText strings.Builder
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}
| #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type playfairOption int
const (
noQ playfairOption = iota
iEqualsJ
)
type playfair struct {
keyword string
pfo playfairOption
table [5][5]byte
}
func (p *playfair) init() {
var used [26]bool
if p.pfo == noQ {
used[16] = true
} else {
used[9] = true
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
plainText = strings.ToUpper(plainText)
var cleanText strings.Builder
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}
| #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math/big"
)
func harmonic(n int) *big.Rat {
sum := new(big.Rat)
for i := int64(1); i <= int64(n); i++ {
r := big.NewRat(1, i)
sum.Add(sum, r)
}
return sum
}
func main() {
fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
numbers := make([]int, 21)
for i := 1; i <= 20; i++ {
numbers[i-1] = i
}
numbers[20] = 100
for _, i := range numbers {
fmt.Printf("%3d : %s\n", i, harmonic(i))
}
fmt.Println("\nThe first harmonic number to exceed the following integers is:")
const limit = 10
for i, n, h := 1, 1, 0.0; i <= limit; n++ {
h += 1.0 / float64(n)
if h > float64(i) {
fmt.Printf("integer = %2d -> n = %6d -> harmonic number = %9.6f (to 6dp)\n", i, n, h)
i++
}
}
}
| #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/gmp.hpp>
using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;
class harmonic_generator {
public:
rational next() {
rational result = term_;
term_ += rational(1, ++n_);
return result;
}
void reset() {
n_ = 1;
term_ = 1;
}
private:
integer n_ = 1;
rational term_ = 1;
};
int main() {
std::cout << "First 20 harmonic numbers:\n";
harmonic_generator hgen;
for (int i = 1; i <= 20; ++i)
std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';
rational h;
for (int i = 1; i <= 80; ++i)
h = hgen.next();
std::cout << "\n100th harmonic number: " << h << "\n\n";
int n = 1;
hgen.reset();
for (int i = 1; n <= 10; ++i) {
if (hgen.next() > n)
std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
}
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"fmt"
"io"
"log"
"math"
"math/rand"
"os"
"time"
)
type MinHeapNode struct{ element, index int }
type MinHeap struct{ nodes []MinHeapNode }
func left(i int) int {
return (2*i + 1)
}
func right(i int) int {
return (2*i + 2)
}
func newMinHeap(nodes []MinHeapNode) *MinHeap {
mh := new(MinHeap)
mh.nodes = nodes
for i := (len(nodes) - 1) / 2; i >= 0; i-- {
mh.minHeapify(i)
}
return mh
}
func (mh *MinHeap) getMin() MinHeapNode {
return mh.nodes[0]
}
func (mh *MinHeap) replaceMin(x MinHeapNode) {
mh.nodes[0] = x
mh.minHeapify(0)
}
func (mh *MinHeap) minHeapify(i int) {
l, r := left(i), right(i)
smallest := i
heapSize := len(mh.nodes)
if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {
smallest = l
}
if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {
smallest = r
}
if smallest != i {
mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]
mh.minHeapify(smallest)
}
}
func merge(arr []int, l, m, r int) {
n1, n2 := m-l+1, r-m
tl := make([]int, n1)
tr := make([]int, n2)
copy(tl, arr[l:])
copy(tr, arr[m+1:])
i, j, k := 0, 0, l
for i < n1 && j < n2 {
if tl[i] <= tr[j] {
arr[k] = tl[i]
k++
i++
} else {
arr[k] = tr[j]
k++
j++
}
}
for i < n1 {
arr[k] = tl[i]
k++
i++
}
for j < n2 {
arr[k] = tr[j]
k++
j++
}
}
func mergeSort(arr []int, l, r int) {
if l < r {
m := l + (r-l)/2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
}
}
func mergeFiles(outputFile string, n, k int) {
in := make([]*os.File, k)
var err error
for i := 0; i < k; i++ {
fileName := fmt.Sprintf("es%d", i)
in[i], err = os.Open(fileName)
check(err)
}
out, err := os.Create(outputFile)
check(err)
nodes := make([]MinHeapNode, k)
i := 0
for ; i < k; i++ {
_, err = fmt.Fscanf(in[i], "%d", &nodes[i].element)
if err == io.EOF {
break
}
check(err)
nodes[i].index = i
}
hp := newMinHeap(nodes[:i])
count := 0
for count != i {
root := hp.getMin()
fmt.Fprintf(out, "%d ", root.element)
_, err = fmt.Fscanf(in[root.index], "%d", &root.element)
if err == io.EOF {
root.element = math.MaxInt32
count++
} else {
check(err)
}
hp.replaceMin(root)
}
for j := 0; j < k; j++ {
in[j].Close()
}
out.Close()
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func createInitialRuns(inputFile string, runSize, numWays int) {
in, err := os.Open(inputFile)
out := make([]*os.File, numWays)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
out[i], err = os.Create(fileName)
check(err)
}
arr := make([]int, runSize)
moreInput := true
nextOutputFile := 0
var i int
for moreInput {
for i = 0; i < runSize; i++ {
_, err := fmt.Fscanf(in, "%d", &arr[i])
if err == io.EOF {
moreInput = false
break
}
check(err)
}
mergeSort(arr, 0, i-1)
for j := 0; j < i; j++ {
fmt.Fprintf(out[nextOutputFile], "%d ", arr[j])
}
nextOutputFile++
}
for j := 0; j < numWays; j++ {
out[j].Close()
}
in.Close()
}
func externalSort(inputFile, outputFile string, numWays, runSize int) {
createInitialRuns(inputFile, runSize, numWays)
mergeFiles(outputFile, runSize, numWays)
}
func main() {
numWays := 4
runSize := 10
inputFile := "input.txt"
outputFile := "output.txt"
in, err := os.Create(inputFile)
check(err)
rand.Seed(time.Now().UnixNano())
for i := 0; i < numWays*runSize; i++ {
fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32))
}
in.Close()
externalSort(inputFile, outputFile, numWays, runSize)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
err = os.Remove(fileName)
check(err)
}
}
|
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
int main(int argc, char* argv[]);
void write_vals(int* const, const size_t, const size_t);
std::string mergeFiles(size_t);
struct Compare
{
bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 )
{
return p1.first >= p2.first;
}
};
using ipair = std::pair<int,int>;
using pairvector = std::vector<ipair>;
using MinHeap = std::priority_queue< ipair, pairvector, Compare >;
const size_t memsize = 32;
const size_t chunksize = memsize / sizeof(int);
const std::string tmp_prefix{"tmp_out_"};
const std::string tmp_suffix{".txt"};
const std::string merged_file{"merged.txt"};
void write_vals( int* const values, const size_t size, const size_t chunk )
{
std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);
std::ofstream ofs(output_file.c_str());
for (int i=0; i<size; i++)
ofs << values[i] << '\t';
ofs << '\n';
ofs.close();
}
std::string mergeFiles(size_t chunks, const std::string& merge_file )
{
std::ofstream ofs( merge_file.c_str() );
MinHeap minHeap;
std::ifstream* ifs_tempfiles = new std::ifstream[chunks];
for (size_t i = 1; i<=chunks; i++)
{
int topval = 0;
std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);
ifs_tempfiles[i-1].open( sorted_file.c_str() );
if (ifs_tempfiles[i-1].is_open())
{
ifs_tempfiles[i-1] >> topval;
ipair top(topval, (i-1));
minHeap.push( top );
}
}
while (minHeap.size() > 0)
{
int next_val = 0;
ipair min_pair = minHeap.top();
minHeap.pop();
ofs << min_pair.first << ' ';
std::flush(ofs);
if ( ifs_tempfiles[min_pair.second] >> next_val)
{
ipair np( next_val, min_pair.second );
minHeap.push( np );
}
}
for (int i = 1; i <= chunks; i++)
{
ifs_tempfiles[i-1].close();
}
ofs << '\n';
ofs.close();
delete[] ifs_tempfiles;
return merged_file;
}
int main(int argc, char* argv[] )
{
if (argc < 2)
{
std::cerr << "usage: ExternalSort <filename> \n";
return 1;
}
std::ifstream ifs( argv[1] );
if ( ifs.fail() )
{
std::cerr << "error opening " << argv[1] << "\n";
return 2;
}
int* inputValues = new int[chunksize];
int chunk = 1;
int val = 0;
int count = 0;
bool done = false;
std::cout << "internal buffer is " << memsize << " bytes" << "\n";
while (ifs >> val)
{
done = false;
inputValues[count] = val;
count++;
if (count == chunksize)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
chunk ++;
count = 0;
done = true;
}
}
if (! done)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
}
else
{
chunk --;
}
ifs.close();
delete[] inputValues;
if ( chunk == 0 )
std::cout << "no data found\n";
else
std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n";
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
"io"
"log"
"math"
"math/rand"
"os"
"time"
)
type MinHeapNode struct{ element, index int }
type MinHeap struct{ nodes []MinHeapNode }
func left(i int) int {
return (2*i + 1)
}
func right(i int) int {
return (2*i + 2)
}
func newMinHeap(nodes []MinHeapNode) *MinHeap {
mh := new(MinHeap)
mh.nodes = nodes
for i := (len(nodes) - 1) / 2; i >= 0; i-- {
mh.minHeapify(i)
}
return mh
}
func (mh *MinHeap) getMin() MinHeapNode {
return mh.nodes[0]
}
func (mh *MinHeap) replaceMin(x MinHeapNode) {
mh.nodes[0] = x
mh.minHeapify(0)
}
func (mh *MinHeap) minHeapify(i int) {
l, r := left(i), right(i)
smallest := i
heapSize := len(mh.nodes)
if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {
smallest = l
}
if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {
smallest = r
}
if smallest != i {
mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]
mh.minHeapify(smallest)
}
}
func merge(arr []int, l, m, r int) {
n1, n2 := m-l+1, r-m
tl := make([]int, n1)
tr := make([]int, n2)
copy(tl, arr[l:])
copy(tr, arr[m+1:])
i, j, k := 0, 0, l
for i < n1 && j < n2 {
if tl[i] <= tr[j] {
arr[k] = tl[i]
k++
i++
} else {
arr[k] = tr[j]
k++
j++
}
}
for i < n1 {
arr[k] = tl[i]
k++
i++
}
for j < n2 {
arr[k] = tr[j]
k++
j++
}
}
func mergeSort(arr []int, l, r int) {
if l < r {
m := l + (r-l)/2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
}
}
func mergeFiles(outputFile string, n, k int) {
in := make([]*os.File, k)
var err error
for i := 0; i < k; i++ {
fileName := fmt.Sprintf("es%d", i)
in[i], err = os.Open(fileName)
check(err)
}
out, err := os.Create(outputFile)
check(err)
nodes := make([]MinHeapNode, k)
i := 0
for ; i < k; i++ {
_, err = fmt.Fscanf(in[i], "%d", &nodes[i].element)
if err == io.EOF {
break
}
check(err)
nodes[i].index = i
}
hp := newMinHeap(nodes[:i])
count := 0
for count != i {
root := hp.getMin()
fmt.Fprintf(out, "%d ", root.element)
_, err = fmt.Fscanf(in[root.index], "%d", &root.element)
if err == io.EOF {
root.element = math.MaxInt32
count++
} else {
check(err)
}
hp.replaceMin(root)
}
for j := 0; j < k; j++ {
in[j].Close()
}
out.Close()
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func createInitialRuns(inputFile string, runSize, numWays int) {
in, err := os.Open(inputFile)
out := make([]*os.File, numWays)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
out[i], err = os.Create(fileName)
check(err)
}
arr := make([]int, runSize)
moreInput := true
nextOutputFile := 0
var i int
for moreInput {
for i = 0; i < runSize; i++ {
_, err := fmt.Fscanf(in, "%d", &arr[i])
if err == io.EOF {
moreInput = false
break
}
check(err)
}
mergeSort(arr, 0, i-1)
for j := 0; j < i; j++ {
fmt.Fprintf(out[nextOutputFile], "%d ", arr[j])
}
nextOutputFile++
}
for j := 0; j < numWays; j++ {
out[j].Close()
}
in.Close()
}
func externalSort(inputFile, outputFile string, numWays, runSize int) {
createInitialRuns(inputFile, runSize, numWays)
mergeFiles(outputFile, runSize, numWays)
}
func main() {
numWays := 4
runSize := 10
inputFile := "input.txt"
outputFile := "output.txt"
in, err := os.Create(inputFile)
check(err)
rand.Seed(time.Now().UnixNano())
for i := 0; i < numWays*runSize; i++ {
fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32))
}
in.Close()
externalSort(inputFile, outputFile, numWays, runSize)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
err = os.Remove(fileName)
check(err)
}
}
|
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
int main(int argc, char* argv[]);
void write_vals(int* const, const size_t, const size_t);
std::string mergeFiles(size_t);
struct Compare
{
bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 )
{
return p1.first >= p2.first;
}
};
using ipair = std::pair<int,int>;
using pairvector = std::vector<ipair>;
using MinHeap = std::priority_queue< ipair, pairvector, Compare >;
const size_t memsize = 32;
const size_t chunksize = memsize / sizeof(int);
const std::string tmp_prefix{"tmp_out_"};
const std::string tmp_suffix{".txt"};
const std::string merged_file{"merged.txt"};
void write_vals( int* const values, const size_t size, const size_t chunk )
{
std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);
std::ofstream ofs(output_file.c_str());
for (int i=0; i<size; i++)
ofs << values[i] << '\t';
ofs << '\n';
ofs.close();
}
std::string mergeFiles(size_t chunks, const std::string& merge_file )
{
std::ofstream ofs( merge_file.c_str() );
MinHeap minHeap;
std::ifstream* ifs_tempfiles = new std::ifstream[chunks];
for (size_t i = 1; i<=chunks; i++)
{
int topval = 0;
std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);
ifs_tempfiles[i-1].open( sorted_file.c_str() );
if (ifs_tempfiles[i-1].is_open())
{
ifs_tempfiles[i-1] >> topval;
ipair top(topval, (i-1));
minHeap.push( top );
}
}
while (minHeap.size() > 0)
{
int next_val = 0;
ipair min_pair = minHeap.top();
minHeap.pop();
ofs << min_pair.first << ' ';
std::flush(ofs);
if ( ifs_tempfiles[min_pair.second] >> next_val)
{
ipair np( next_val, min_pair.second );
minHeap.push( np );
}
}
for (int i = 1; i <= chunks; i++)
{
ifs_tempfiles[i-1].close();
}
ofs << '\n';
ofs.close();
delete[] ifs_tempfiles;
return merged_file;
}
int main(int argc, char* argv[] )
{
if (argc < 2)
{
std::cerr << "usage: ExternalSort <filename> \n";
return 1;
}
std::ifstream ifs( argv[1] );
if ( ifs.fail() )
{
std::cerr << "error opening " << argv[1] << "\n";
return 2;
}
int* inputValues = new int[chunksize];
int chunk = 1;
int val = 0;
int count = 0;
bool done = false;
std::cout << "internal buffer is " << memsize << " bytes" << "\n";
while (ifs >> val)
{
done = false;
inputValues[count] = val;
count++;
if (count == chunksize)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
chunk ++;
count = 0;
done = true;
}
}
if (! done)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
}
else
{
chunk --;
}
ifs.close();
delete[] inputValues;
if ( chunk == 0 )
std::cout << "no data found\n";
else
std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n";
return EXIT_SUCCESS;
}
|
Generate an equivalent C++ version of this Go code. | package cf
type NG4 struct {
A1, A int64
B1, B int64
}
func (ng NG4) needsIngest() bool {
if ng.isDone() {
panic("b₁==b==0")
}
return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}
func (ng NG4) isDone() bool {
return ng.B1 == 0 && ng.B == 0
}
func (ng *NG4) ingest(t int64) {
ng.A1, ng.A, ng.B1, ng.B =
ng.A+ng.A1*t, ng.A1,
ng.B+ng.B1*t, ng.B1
}
func (ng *NG4) ingestInfinite() {
ng.A, ng.B = ng.A1, ng.B1
}
func (ng *NG4) egest(t int64) {
ng.A1, ng.A, ng.B1, ng.B =
ng.B1, ng.B,
ng.A1-ng.B1*t, ng.A-ng.B*t
}
func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {
return func() NextFn {
next := cf()
done := false
return func() (int64, bool) {
if done {
return 0, false
}
for ng.needsIngest() {
if t, ok := next(); ok {
ng.ingest(t)
} else {
ng.ingestInfinite()
}
}
t := ng.A1 / ng.B1
ng.egest(t)
done = ng.isDone()
return t, true
}
}
}
|
class matrixNG {
private:
virtual void consumeTerm(){}
virtual void consumeTerm(int n){}
virtual const bool needTerm(){}
protected: int cfn = 0, thisTerm;
bool haveTerm = false;
friend class NG;
};
class NG_4 : public matrixNG {
private: int a1, a, b1, b, t;
const bool needTerm() {
if (b1==0 and b==0) return false;
if (b1==0 or b==0) return true; else thisTerm = a/b;
if (thisTerm==(int)(a1/b1)){
t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;
haveTerm=true; return false;
}
return true;
}
void consumeTerm(){a=a1; b=b1;}
void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}
public:
NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}
};
class NG : public ContinuedFraction {
private:
matrixNG* ng;
ContinuedFraction* n[2];
public:
NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}
NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}
const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}
const bool moreTerms(){
while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();
return ng->haveTerm;
}
};
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
func calkinWilf(n int) []*big.Rat {
cw := make([]*big.Rat, n+1)
cw[0] = big.NewRat(1, 1)
one := big.NewRat(1, 1)
two := big.NewRat(2, 1)
for i := 1; i < n; i++ {
t := new(big.Rat).Set(cw[i-1])
f, _ := t.Float64()
f = math.Floor(f)
t.SetFloat64(f)
t.Mul(t, two)
t.Sub(t, cw[i-1])
t.Add(t, one)
t.Inv(t)
cw[i] = new(big.Rat).Set(t)
}
return cw
}
func toContinued(r *big.Rat) []int {
a := r.Num().Int64()
b := r.Denom().Int64()
var res []int
for {
res = append(res, int(a/b))
t := a % b
a, b = b, t
if a == 1 {
break
}
}
le := len(res)
if le%2 == 0 {
res[le-1]--
res = append(res, 1)
}
return res
}
func getTermNumber(cf []int) int {
b := ""
d := "1"
for _, n := range cf {
b = strings.Repeat(d, n) + b
if d == "1" {
d = "0"
} else {
d = "1"
}
}
i, _ := strconv.ParseInt(b, 2, 64)
return int(i)
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
cw := calkinWilf(20)
fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:")
for i := 1; i <= 20; i++ {
fmt.Printf("%2d: %s\n", i, cw[i-1].RatString())
}
fmt.Println()
r := big.NewRat(83116, 51639)
cf := toContinued(r)
tn := getTermNumber(cf)
fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn))
}
| #include <iostream>
#include <vector>
#include <boost/rational.hpp>
using rational = boost::rational<unsigned long>;
unsigned long floor(const rational& r) {
return r.numerator()/r.denominator();
}
rational calkin_wilf_next(const rational& term) {
return 1UL/(2UL * floor(term) + 1UL - term);
}
std::vector<unsigned long> continued_fraction(const rational& r) {
unsigned long a = r.numerator();
unsigned long b = r.denominator();
std::vector<unsigned long> result;
do {
result.push_back(a/b);
unsigned long c = a;
a = b;
b = c % b;
} while (a != 1);
if (result.size() > 0 && result.size() % 2 == 0) {
--result.back();
result.push_back(1);
}
return result;
}
unsigned long term_number(const rational& r) {
unsigned long result = 0;
unsigned long d = 1;
unsigned long p = 0;
for (unsigned long n : continued_fraction(r)) {
for (unsigned long i = 0; i < n; ++i, ++p)
result |= (d << p);
d = !d;
}
return result;
}
int main() {
rational term = 1;
std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n";
for (int i = 1; i <= 20; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
term = calkin_wilf_next(term);
}
rational r(83116, 51639);
std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n";
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
func calkinWilf(n int) []*big.Rat {
cw := make([]*big.Rat, n+1)
cw[0] = big.NewRat(1, 1)
one := big.NewRat(1, 1)
two := big.NewRat(2, 1)
for i := 1; i < n; i++ {
t := new(big.Rat).Set(cw[i-1])
f, _ := t.Float64()
f = math.Floor(f)
t.SetFloat64(f)
t.Mul(t, two)
t.Sub(t, cw[i-1])
t.Add(t, one)
t.Inv(t)
cw[i] = new(big.Rat).Set(t)
}
return cw
}
func toContinued(r *big.Rat) []int {
a := r.Num().Int64()
b := r.Denom().Int64()
var res []int
for {
res = append(res, int(a/b))
t := a % b
a, b = b, t
if a == 1 {
break
}
}
le := len(res)
if le%2 == 0 {
res[le-1]--
res = append(res, 1)
}
return res
}
func getTermNumber(cf []int) int {
b := ""
d := "1"
for _, n := range cf {
b = strings.Repeat(d, n) + b
if d == "1" {
d = "0"
} else {
d = "1"
}
}
i, _ := strconv.ParseInt(b, 2, 64)
return int(i)
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
cw := calkinWilf(20)
fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:")
for i := 1; i <= 20; i++ {
fmt.Printf("%2d: %s\n", i, cw[i-1].RatString())
}
fmt.Println()
r := big.NewRat(83116, 51639)
cf := toContinued(r)
tn := getTermNumber(cf)
fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn))
}
| #include <iostream>
#include <vector>
#include <boost/rational.hpp>
using rational = boost::rational<unsigned long>;
unsigned long floor(const rational& r) {
return r.numerator()/r.denominator();
}
rational calkin_wilf_next(const rational& term) {
return 1UL/(2UL * floor(term) + 1UL - term);
}
std::vector<unsigned long> continued_fraction(const rational& r) {
unsigned long a = r.numerator();
unsigned long b = r.denominator();
std::vector<unsigned long> result;
do {
result.push_back(a/b);
unsigned long c = a;
a = b;
b = c % b;
} while (a != 1);
if (result.size() > 0 && result.size() % 2 == 0) {
--result.back();
result.push_back(1);
}
return result;
}
unsigned long term_number(const rational& r) {
unsigned long result = 0;
unsigned long d = 1;
unsigned long p = 0;
for (unsigned long n : continued_fraction(r)) {
for (unsigned long i = 0; i < n; ++i, ++p)
result |= (d << p);
d = !d;
}
return result;
}
int main() {
rational term = 1;
std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n";
for (int i = 1; i <= 20; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
term = calkin_wilf_next(term);
}
rational r(83116, 51639);
std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n";
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
func main() {
fact := big.NewInt(1)
sum := 0.0
first := int64(0)
firstRatio := 0.0
fmt.Println("The mean proportion of zero digits in factorials up to the following are:")
for n := int64(1); n <= 50000; n++ {
fact.Mul(fact, big.NewInt(n))
bytes := []byte(fact.String())
digits := len(bytes)
zeros := 0
for _, b := range bytes {
if b == '0' {
zeros++
}
}
sum += float64(zeros)/float64(digits)
ratio := sum / float64(n)
if n == 100 || n == 1000 || n == 10000 {
fmt.Printf("%6s = %12.10f\n", rcu.Commatize(int(n)), ratio)
}
if first > 0 && ratio >= 0.16 {
first = 0
firstRatio = 0.0
} else if first == 0 && ratio < 0.16 {
first = n
firstRatio = ratio
}
}
fmt.Printf("%6s = %12.10f", rcu.Commatize(int(first)), firstRatio)
fmt.Println(" (stays below 0.16 after this)")
fmt.Printf("%6s = %12.10f\n", "50,000", sum / 50000)
}
| #include <array>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
auto init_zc() {
std::array<int, 1000> zc;
zc.fill(0);
zc[0] = 3;
for (int x = 1; x <= 9; ++x) {
zc[x] = 2;
zc[10 * x] = 2;
zc[100 * x] = 2;
for (int y = 10; y <= 90; y += 10) {
zc[y + x] = 1;
zc[10 * y + x] = 1;
zc[10 * (y + x)] = 1;
}
}
return zc;
}
template <typename clock_type>
auto elapsed(const std::chrono::time_point<clock_type>& t0) {
auto t1 = clock_type::now();
auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);
return duration.count();
}
int main() {
auto zc = init_zc();
auto t0 = std::chrono::high_resolution_clock::now();
int trail = 1, first = 0;
double total = 0;
std::vector<int> rfs{1};
std::cout << std::fixed << std::setprecision(10);
for (int f = 2; f <= 50000; ++f) {
int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size();
for (int j = trail - 1; j < len || carry != 0; ++j) {
if (j < len)
carry += rfs[j] * f;
d999 = carry % 1000;
if (j < len)
rfs[j] = d999;
else
rfs.push_back(d999);
zeroes += zc[d999];
carry /= 1000;
}
while (rfs[trail - 1] == 0)
++trail;
d999 = rfs.back();
d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0;
zeroes -= d999;
int digits = rfs.size() * 3 - d999;
total += double(zeroes) / digits;
double ratio = total / f;
if (ratio >= 0.16)
first = 0;
else if (first == 0)
first = f;
if (f == 100 || f == 1000 || f == 10000) {
std::cout << "Mean proportion of zero digits in factorials to " << f
<< " is " << ratio << ". (" << elapsed(t0) << "ms)\n";
}
}
std::cout << "The mean proportion dips permanently below 0.16 at " << first
<< ". (" << elapsed(t0) << "ms)\n";
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type xy struct {
x, y float64
}
const n = 1000
const scale = 100.
func d(p1, p2 xy) float64 {
return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}
func main() {
rand.Seed(time.Now().Unix())
points := make([]xy, n)
for i := range points {
points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
}
p1, p2 := closestPair(points)
fmt.Println(p1, p2)
fmt.Println("distance:", d(p1, p2))
}
func closestPair(points []xy) (p1, p2 xy) {
if len(points) < 2 {
panic("at least two points expected")
}
min := 2 * scale
for i, q1 := range points[:len(points)-1] {
for _, q2 := range points[i+1:] {
if dq := d(q1, q2); dq < min {
p1, p2 = q1, q2
min = dq
}
}
}
return
}
|
#include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>
typedef std::pair<double, double> point_t;
typedef std::pair<point_t, point_t> points_t;
double distance_between(const point_t& a, const point_t& b) {
return std::sqrt(std::pow(b.first - a.first, 2)
+ std::pow(b.second - a.second, 2));
}
std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {
if (points.size() < 2) {
return { -1, { { 0, 0 }, { 0, 0 } } };
}
auto minDistance = std::abs(distance_between(points.at(0), points.at(1)));
points_t minPoints = { points.at(0), points.at(1) };
for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {
for (auto j = i + 1; j < std::end(points); ++j) {
auto newDistance = std::abs(distance_between(*i, *j));
if (newDistance < minDistance) {
minDistance = newDistance;
minPoints.first = *i;
minPoints.second = *j;
}
}
}
return { minDistance, minPoints };
}
std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,
const std::vector<point_t>& yP) {
if (xP.size() <= 3) {
return find_closest_brute(xP);
}
auto N = xP.size();
auto xL = std::vector<point_t>();
auto xR = std::vector<point_t>();
std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));
std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));
auto xM = xP.at((N-1) / 2).first;
auto yL = std::vector<point_t>();
auto yR = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {
return p.first <= xM;
});
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {
return p.first > xM;
});
auto p1 = find_closest_optimized(xL, yL);
auto p2 = find_closest_optimized(xR, yR);
auto minPair = (p1.first <= p2.first) ? p1 : p2;
auto yS = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {
return std::abs(xM - p.first) < minPair.first;
});
auto result = minPair;
for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {
for (auto k = i + 1; k != std::end(yS) &&
((k->second - i->second) < minPair.first); ++k) {
auto newDistance = std::abs(distance_between(*k, *i));
if (newDistance < result.first) {
result = { newDistance, { *k, *i } };
}
}
}
return result;
}
void print_point(const point_t& point) {
std::cout << "(" << point.first
<< ", " << point.second
<< ")";
}
int main(int argc, char * argv[]) {
std::default_random_engine re(std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now()));
std::uniform_real_distribution<double> urd(-500.0, 500.0);
std::vector<point_t> points(100);
std::generate(std::begin(points), std::end(points), [&urd, &re]() {
return point_t { 1000 + urd(re), 1000 + urd(re) };
});
auto answer = find_closest_brute(points);
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.first < b.first;
});
auto xP = points;
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.second < b.second;
});
auto yP = points;
std::cout << "Min distance (brute): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
answer = find_closest_optimized(xP, yP);
std::cout << "\nMin distance (optimized): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
return 0;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = int64(uintptr(ptr))
fmt.Printf("Pointer stored in int64: %#016x\n", addr64)
}
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
addr32 = int32(uintptr(ptr))
fmt.Printf("Pointer stored in int32: %#08x\n", addr32)
}
addr := uintptr(ptr)
fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)
fmt.Println("value as float:", myVar)
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *i)
}
| int i;
void* address_of_i = &i;
|
Please provide an equivalent version of this Go code in C++. | package main
type animal struct {
alive bool
}
type dog struct {
animal
obedienceTrained bool
}
type cat struct {
animal
litterBoxTrained bool
}
type lab struct {
dog
color string
}
type collie struct {
dog
catchesFrisbee bool
}
func main() {
var pet lab
pet.alive = true
pet.obedienceTrained = false
pet.color = "yellow"
}
| class Animal
{
};
class Dog: public Animal
{
};
class Lab: public Dog
{
};
class Collie: public Dog
{
};
class Cat: public Animal
{
};
|
Transform the following Go implementation into C++, maintaining the same output and logic. |
var x map[string]int
x = make(map[string]int)
x = make(map[string]int, 42)
x["foo"] = 3
y1 := x["bar"]
y2, ok := x["bar"]
delete(x, "foo")
x = map[string]int{
"foo": 2, "bar": 42, "baz": -1,
}
| #include <map>
|
Write the same code in C++ as shown below in Go. | package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
const LIMIT = 11000
primes := rcu.Primes(LIMIT)
facts := make([]*big.Int, LIMIT)
facts[0] = big.NewInt(1)
for i := int64(1); i < LIMIT; i++ {
facts[i] = new(big.Int)
facts[i].Mul(facts[i-1], big.NewInt(i))
}
sign := int64(1)
f := new(big.Int)
zero := new(big.Int)
fmt.Println(" n: Wilson primes")
fmt.Println("--------------------")
for n := 1; n < 12; n++ {
fmt.Printf("%2d: ", n)
sign = -sign
for _, p := range primes {
if p < n {
continue
}
f.Mul(facts[n-1], facts[p-n])
f.Sub(f, big.NewInt(sign))
p2 := int64(p * p)
bp2 := big.NewInt(p2)
if f.Rem(f, bp2).Cmp(zero) == 0 {
fmt.Printf("%d ", p)
}
}
fmt.Println()
}
}
| #include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
std::vector<int> generate_primes(int limit) {
std::vector<bool> sieve(limit >> 1, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
int main() {
using big_int = mpz_class;
const int limit = 11000;
std::vector<big_int> f{1};
f.reserve(limit);
big_int factorial = 1;
for (int i = 1; i < limit; ++i) {
factorial *= i;
f.push_back(factorial);
}
std::vector<int> primes = generate_primes(limit);
std::cout << " n | Wilson primes\n--------------------\n";
for (int n = 1, s = -1; n <= 11; ++n, s = -s) {
std::cout << std::setw(2) << n << " |";
for (int p : primes) {
if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)
std::cout << ' ' << p;
}
std::cout << '\n';
}
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
"rcu"
)
var maxDepth = 6
var maxBase = 36
var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true)
var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var maxStrings [][][]int
var mostBases = -1
func maxSlice(a []int) int {
max := 0
for _, e := range a {
if e > max {
max = e
}
}
return max
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
func process(indices []int) {
minBase := maxInt(2, maxSlice(indices)+1)
if maxBase - minBase + 1 < mostBases {
return
}
var bases []int
for b := minBase; b <= maxBase; b++ {
n := 0
for _, i := range indices {
n = n*b + i
}
if !c[n] {
bases = append(bases, b)
}
}
count := len(bases)
if count > mostBases {
mostBases = count
indices2 := make([]int, len(indices))
copy(indices2, indices)
maxStrings = [][][]int{[][]int{indices2, bases}}
} else if count == mostBases {
indices2 := make([]int, len(indices))
copy(indices2, indices)
maxStrings = append(maxStrings, [][]int{indices2, bases})
}
}
func printResults() {
fmt.Printf("%d\n", len(maxStrings[0][1]))
for _, m := range maxStrings {
s := ""
for _, i := range m[0] {
s = s + string(digits[i])
}
fmt.Printf("%s -> %v\n", s, m[1])
}
}
func nestedFor(indices []int, length, level int) {
if level == len(indices) {
process(indices)
} else {
indices[level] = 0
if level == 0 {
indices[level] = 1
}
for indices[level] < length {
nestedFor(indices, length, level+1)
indices[level]++
}
}
}
func main() {
for depth := 1; depth <= maxDepth; depth++ {
fmt.Print(depth, " character strings which are prime in most bases: ")
maxStrings = maxStrings[:0]
mostBases = -1
indices := make([]int, depth)
nestedFor(indices, maxBase, 0)
printResults()
fmt.Println()
}
}
| #include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <primesieve.hpp>
class prime_sieve {
public:
explicit prime_sieve(uint64_t limit);
bool is_prime(uint64_t n) const {
return n == 2 || ((n & 1) == 1 && sieve[n >> 1]);
}
private:
std::vector<bool> sieve;
};
prime_sieve::prime_sieve(uint64_t limit) : sieve((limit + 1) / 2, false) {
primesieve::iterator iter;
uint64_t prime = iter.next_prime();
while ((prime = iter.next_prime()) <= limit) {
sieve[prime >> 1] = true;
}
}
template <typename T> void print(std::ostream& out, const std::vector<T>& v) {
if (!v.empty()) {
out << '[';
auto i = v.begin();
out << *i++;
for (; i != v.end(); ++i)
out << ", " << *i;
out << ']';
}
}
std::string to_string(const std::vector<unsigned int>& v) {
static constexpr char digits[] =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (auto i : v)
str += digits[i];
return str;
}
bool increment(std::vector<unsigned int>& digits, unsigned int max_base) {
for (auto i = digits.rbegin(); i != digits.rend(); ++i) {
if (*i + 1 != max_base) {
++*i;
return true;
}
*i = 0;
}
return false;
}
void multi_base_primes(unsigned int max_base, unsigned int max_length) {
prime_sieve sieve(static_cast<uint64_t>(std::pow(max_base, max_length)));
for (unsigned int length = 1; length <= max_length; ++length) {
std::cout << length
<< "-character strings which are prime in most bases: ";
unsigned int most_bases = 0;
std::vector<
std::pair<std::vector<unsigned int>, std::vector<unsigned int>>>
max_strings;
std::vector<unsigned int> digits(length, 0);
digits[0] = 1;
std::vector<unsigned int> bases;
do {
auto max = std::max_element(digits.begin(), digits.end());
unsigned int min_base = 2;
if (max != digits.end())
min_base = std::max(min_base, *max + 1);
if (most_bases > max_base - min_base + 1)
continue;
bases.clear();
for (unsigned int b = min_base; b <= max_base; ++b) {
if (max_base - b + 1 + bases.size() < most_bases)
break;
uint64_t n = 0;
for (auto d : digits)
n = n * b + d;
if (sieve.is_prime(n))
bases.push_back(b);
}
if (bases.size() > most_bases) {
most_bases = bases.size();
max_strings.clear();
}
if (bases.size() == most_bases)
max_strings.emplace_back(digits, bases);
} while (increment(digits, max_base));
std::cout << most_bases << '\n';
for (const auto& m : max_strings) {
std::cout << to_string(m.first) << " -> ";
print(std::cout, m.second);
std::cout << '\n';
}
std::cout << '\n';
}
}
int main(int argc, char** argv) {
unsigned int max_base = 36;
unsigned int max_length = 4;
for (int arg = 1; arg + 1 < argc; ++arg) {
if (strcmp(argv[arg], "-max_base") == 0)
max_base = strtoul(argv[++arg], nullptr, 10);
else if (strcmp(argv[arg], "-max_length") == 0)
max_length = strtoul(argv[++arg], nullptr, 10);
}
if (max_base > 62) {
std::cerr << "Max base cannot be greater than 62.\n";
return EXIT_FAILURE;
}
if (max_base < 2) {
std::cerr << "Max base cannot be less than 2.\n";
return EXIT_FAILURE;
}
multi_base_primes(max_base, max_length);
return EXIT_SUCCESS;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"github.com/fogleman/gg"
"math"
)
const tau = 2 * math.Pi
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func colorWheel(dc *gg.Context) {
width, height := dc.Width(), dc.Height()
centerX, centerY := width/2, height/2
radius := centerX
if centerY < radius {
radius = centerY
}
for y := 0; y < height; y++ {
dy := float64(y - centerY)
for x := 0; x < width; x++ {
dx := float64(x - centerX)
dist := math.Sqrt(dx*dx + dy*dy)
if dist <= float64(radius) {
theta := math.Atan2(dy, dx)
hue := (theta + math.Pi) / tau
r, g, b := hsb2rgb(hue, 1, 1)
dc.SetRGB255(r, g, b)
dc.SetPixel(x, y)
}
}
}
}
func main() {
const width, height = 480, 480
dc := gg.NewContext(width, height)
dc.SetRGB(1, 1, 1)
dc.Clear()
colorWheel(dc)
dc.SavePNG("color_wheel.png")
}
|
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"image"
"image/color"
"image/gif"
"log"
"math"
"os"
)
func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
img.SetColorIndex(x, y, ci)
}
}
}
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func main() {
const degToRad = math.Pi / 180
const nframes = 100
const delay = 4
w, h := 640, 640
anim := gif.GIF{LoopCount: nframes}
rect := image.Rect(0, 0, w, h)
palette := make([]color.Color, nframes+1)
palette[0] = color.White
for i := 1; i <= nframes; i++ {
r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)
palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}
}
for f := 1; f <= nframes; f++ {
img := image.NewPaletted(rect, palette)
setBackgroundColor(img, w, h, 0)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
fx, fy := float64(x), float64(y)
value := math.Sin(fx / 16)
value += math.Sin(fy / 8)
value += math.Sin((fx + fy) / 16)
value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)
value += 4
value /= 8
_, rem := math.Modf(value + float64(f)/float64(nframes))
ci := uint8(nframes*rem) + 1
img.SetColorIndex(x, y, ci)
}
}
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
file, err := os.Create("plasma.gif")
if err != nil {
log.Fatal(err)
}
defer file.Close()
if err2 := gif.EncodeAll(file, &anim); err != nil {
log.Fatal(err2)
}
}
| #include <windows.h>
#include <math.h>
#include <string>
const int BMP_SIZE = 240, MY_TIMER = 987654;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
DWORD* bits() { return ( DWORD* )pBits; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class plasma
{
public:
plasma() {
currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;
_bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();
plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
int i, j, dst = 0;
double temp;
for( j = 0; j < BMP_SIZE * 2; j++ ) {
for( i = 0; i < BMP_SIZE * 2; i++ ) {
plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );
plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) +
( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );
dst++;
}
}
}
void update() {
DWORD dst;
BYTE a, c1,c2, c3;
currentTime += ( double )( rand() % 2 + 1 );
int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ),
x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ),
x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),
y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ),
y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ),
y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );
int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;
DWORD* bits = _bmp.bits();
for( int j = 0; j < BMP_SIZE; j++ ) {
dst = j * BMP_SIZE;
for( int i= 0; i < BMP_SIZE; i++ ) {
a = plasma2[src1] + plasma1[src2] + plasma2[src3];
c1 = a << 1; c2 = a << 2; c3 = a << 3;
bits[dst + i] = RGB( c1, c2, c3 );
src1++; src2++; src3++;
}
src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;
}
draw();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
void draw() {
HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
}
myBitmap _bmp; HWND _hwnd; float _ang;
BYTE *plasma1, *plasma2;
double currentTime; int _WD, _WV;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst; _hwnd = InitAll();
SetTimer( _hwnd, MY_TIMER, 15, NULL );
_plasma.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT ) {
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_MY_PLASMA_", _hInst );
}
private:
void wnd::doPaint( HDC dc ) { _plasma.update(); }
void wnd::doTimer() { _plasma.update(); }
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_PAINT: {
PAINTSTRUCT ps;
_inst->doPaint( BeginPaint( hWnd, &ps ) );
EndPaint( hWnd, &ps );
return 0;
}
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_TIMER: _inst->doTimer(); break;
default: return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll() {
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_MY_PLASMA_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;
};
wnd* wnd::_inst = 0;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
wnd myWnd;
return myWnd.Run( hInstance );
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
"strconv"
"strings"
)
type sandpile struct{ a [9]int }
var neighbors = [][]int{
{1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},
}
func newSandpile(a [9]int) *sandpile { return &sandpile{a} }
func (s *sandpile) plus(other *sandpile) *sandpile {
b := [9]int{}
for i := 0; i < 9; i++ {
b[i] = s.a[i] + other.a[i]
}
return &sandpile{b}
}
func (s *sandpile) isStable() bool {
for _, e := range s.a {
if e > 3 {
return false
}
}
return true
}
func (s *sandpile) topple() {
for i := 0; i < 9; i++ {
if s.a[i] > 3 {
s.a[i] -= 4
for _, j := range neighbors[i] {
s.a[j]++
}
return
}
}
}
func (s *sandpile) String() string {
var sb strings.Builder
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ")
}
sb.WriteString("\n")
}
return sb.String()
}
func main() {
fmt.Println("Avalanche of topplings:\n")
s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})
fmt.Println(s4)
for !s4.isStable() {
s4.topple()
fmt.Println(s4)
}
fmt.Println("Commutative additions:\n")
s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})
s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})
s3_a := s1.plus(s2)
for !s3_a.isStable() {
s3_a.topple()
}
s3_b := s2.plus(s1)
for !s3_b.isStable() {
s3_b.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a)
fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b)
fmt.Println("Addition of identity sandpile:\n")
s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})
s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})
s4 = s3.plus(s3_id)
for !s4.isStable() {
s4.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4)
fmt.Println("Addition of identities:\n")
s5 := s3_id.plus(s3_id)
for !s5.isStable() {
s5.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5)
}
| #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);
public:
abelian_sandpile();
explicit abelian_sandpile(std::initializer_list<int> init);
void stabilize();
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile&);
bool operator==(const abelian_sandpile&);
private:
int& cell_value(size_t row, size_t column) {
return cells_[cell_index(row, column)];
}
static size_t cell_index(size_t row, size_t column) {
return row * sp_columns + column;
}
static size_t row_index(size_t cell_index) {
return cell_index/sp_columns;
}
static size_t column_index(size_t cell_index) {
return cell_index % sp_columns;
}
std::array<int, sp_cells> cells_;
};
abelian_sandpile::abelian_sandpile() {
cells_.fill(0);
}
abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {
assert(init.size() == sp_cells);
std::copy(init.begin(), init.end(), cells_.begin());
}
abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {
for (size_t i = 0; i < sp_cells; ++i)
cells_[i] += other.cells_[i];
stabilize();
return *this;
}
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return cells_ == other.cells_;
}
bool abelian_sandpile::is_stable() const {
return std::none_of(cells_.begin(), cells_.end(),
[](int a) { return a >= sp_limit; });
}
void abelian_sandpile::topple() {
for (size_t i = 0; i < sp_cells; ++i) {
if (cells_[i] >= sp_limit) {
cells_[i] -= sp_limit;
size_t row = row_index(i);
size_t column = column_index(i);
if (row > 0)
++cell_value(row - 1, column);
if (row + 1 < sp_rows)
++cell_value(row + 1, column);
if (column > 0)
++cell_value(row, column - 1);
if (column + 1 < sp_columns)
++cell_value(row, column + 1);
break;
}
}
}
void abelian_sandpile::stabilize() {
while (!is_stable())
topple();
}
abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {
abelian_sandpile c(a);
c += b;
return c;
}
std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
int main() {
std::cout << std::boolalpha;
std::cout << "Avalanche:\n";
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "Commutativity:\n";
abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};
abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};
abelian_sandpile sum1(s1 + s2);
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
std::cout << "\ns2 + s1 = \n" << sum2;
std::cout << '\n';
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};
abelian_sandpile sum3(s3 + s3_id);
abelian_sandpile sum4(s3_id + s3_id);
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
std::cout << "\ns3_id + s3_id = \n" << sum4;
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
"strconv"
"strings"
)
type sandpile struct{ a [9]int }
var neighbors = [][]int{
{1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},
}
func newSandpile(a [9]int) *sandpile { return &sandpile{a} }
func (s *sandpile) plus(other *sandpile) *sandpile {
b := [9]int{}
for i := 0; i < 9; i++ {
b[i] = s.a[i] + other.a[i]
}
return &sandpile{b}
}
func (s *sandpile) isStable() bool {
for _, e := range s.a {
if e > 3 {
return false
}
}
return true
}
func (s *sandpile) topple() {
for i := 0; i < 9; i++ {
if s.a[i] > 3 {
s.a[i] -= 4
for _, j := range neighbors[i] {
s.a[j]++
}
return
}
}
}
func (s *sandpile) String() string {
var sb strings.Builder
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ")
}
sb.WriteString("\n")
}
return sb.String()
}
func main() {
fmt.Println("Avalanche of topplings:\n")
s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})
fmt.Println(s4)
for !s4.isStable() {
s4.topple()
fmt.Println(s4)
}
fmt.Println("Commutative additions:\n")
s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})
s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})
s3_a := s1.plus(s2)
for !s3_a.isStable() {
s3_a.topple()
}
s3_b := s2.plus(s1)
for !s3_b.isStable() {
s3_b.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a)
fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b)
fmt.Println("Addition of identity sandpile:\n")
s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})
s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})
s4 = s3.plus(s3_id)
for !s4.isStable() {
s4.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4)
fmt.Println("Addition of identities:\n")
s5 := s3_id.plus(s3_id)
for !s5.isStable() {
s5.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5)
}
| #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);
public:
abelian_sandpile();
explicit abelian_sandpile(std::initializer_list<int> init);
void stabilize();
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile&);
bool operator==(const abelian_sandpile&);
private:
int& cell_value(size_t row, size_t column) {
return cells_[cell_index(row, column)];
}
static size_t cell_index(size_t row, size_t column) {
return row * sp_columns + column;
}
static size_t row_index(size_t cell_index) {
return cell_index/sp_columns;
}
static size_t column_index(size_t cell_index) {
return cell_index % sp_columns;
}
std::array<int, sp_cells> cells_;
};
abelian_sandpile::abelian_sandpile() {
cells_.fill(0);
}
abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {
assert(init.size() == sp_cells);
std::copy(init.begin(), init.end(), cells_.begin());
}
abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {
for (size_t i = 0; i < sp_cells; ++i)
cells_[i] += other.cells_[i];
stabilize();
return *this;
}
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return cells_ == other.cells_;
}
bool abelian_sandpile::is_stable() const {
return std::none_of(cells_.begin(), cells_.end(),
[](int a) { return a >= sp_limit; });
}
void abelian_sandpile::topple() {
for (size_t i = 0; i < sp_cells; ++i) {
if (cells_[i] >= sp_limit) {
cells_[i] -= sp_limit;
size_t row = row_index(i);
size_t column = column_index(i);
if (row > 0)
++cell_value(row - 1, column);
if (row + 1 < sp_rows)
++cell_value(row + 1, column);
if (column > 0)
++cell_value(row, column - 1);
if (column + 1 < sp_columns)
++cell_value(row, column + 1);
break;
}
}
}
void abelian_sandpile::stabilize() {
while (!is_stable())
topple();
}
abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {
abelian_sandpile c(a);
c += b;
return c;
}
std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
int main() {
std::cout << std::boolalpha;
std::cout << "Avalanche:\n";
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "Commutativity:\n";
abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};
abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};
abelian_sandpile sum1(s1 + s2);
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
std::cout << "\ns2 + s1 = \n" << sum2;
std::cout << '\n';
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};
abelian_sandpile sum3(s3 + s3_id);
abelian_sandpile sum4(s3_id + s3_id);
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
std::cout << "\ns3_id + s3_id = \n" << sum4;
return 0;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"fmt"
"rcu"
"strconv"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
func main() {
for b := 2; b <= 36; b++ {
if rcu.IsPrime(b) {
continue
}
count := 0
var rhonda []int
for n := 1; count < 15; n++ {
digits := rcu.Digits(n, b)
if !contains(digits, 0) {
var anyEven = false
for _, d := range digits {
if d%2 == 0 {
anyEven = true
break
}
}
if b != 10 || (contains(digits, 5) && anyEven) {
calc1 := 1
for _, d := range digits {
calc1 *= d
}
calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))
if calc1 == calc2 {
rhonda = append(rhonda, n)
count++
}
}
}
}
if len(rhonda) > 0 {
fmt.Printf("\nFirst 15 Rhonda numbers in base %d:\n", b)
rhonda2 := make([]string, len(rhonda))
counts2 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda2[i] = fmt.Sprintf("%d", r)
counts2[i] = len(rhonda2[i])
}
rhonda3 := make([]string, len(rhonda))
counts3 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda3[i] = strconv.FormatInt(int64(r), b)
counts3[i] = len(rhonda3[i])
}
maxLen2 := rcu.MaxInts(counts2)
maxLen3 := rcu.MaxInts(counts3)
maxLen := maxLen2
if maxLen3 > maxLen {
maxLen = maxLen3
}
maxLen++
fmt.Printf("In base 10: %*s\n", maxLen, rhonda2)
fmt.Printf("In base %-2d: %*s\n", b, maxLen, rhonda3)
}
}
}
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int digit_product(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
bool is_rhonda(int base, int n) {
return digit_product(base, n) == base * prime_factor_sum(n);
}
std::string to_string(int base, int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
int main() {
const int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (is_prime(base))
continue;
std::cout << "First " << limit << " Rhonda numbers to base " << base
<< ":\n";
int numbers[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (is_rhonda(base, n))
numbers[count++] = n;
}
std::cout << "In base 10:";
for (int i = 0; i < limit; ++i)
std::cout << ' ' << numbers[i];
std::cout << "\nIn base " << base << ':';
for (int i = 0; i < limit; ++i)
std::cout << ' ' << to_string(base, numbers[i]);
std::cout << "\n\n";
}
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import "fmt"
type point struct {
x, y float64
}
type circle struct {
x, y, r float64
}
type printer interface {
print()
}
func (p *point) print() {
fmt.Println(p.x, p.y)
}
func (c *circle) print() {
fmt.Println(c.x, c.y, c.r)
}
func main() {
var i printer
i = newPoint(3, 4)
i.print()
i = newCircle(5, 12, 13)
i.print()
}
func (p *point) getX() float64 { return p.x }
func (p *point) getY() float64 { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }
func (c *circle) getX() float64 { return c.x }
func (c *circle) getY() float64 { return c.y }
func (c *circle) getR() float64 { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }
func (p *point) clone() *point { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }
func (p *point) set(q *point) { *p = *q }
func (c *circle) set(d *circle) { *c = *d }
func newPoint(x, y float64) *point {
return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
return &circle{x, y, r}
}
| #include <cstdio>
#include <cstdlib>
class Point {
protected:
int x, y;
public:
Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
Point(const Point &p) : x(p.x), y(p.y) {}
virtual ~Point() {}
const Point& operator=(const Point &p) {
if (this != &p) {
x = p.x;
y = p.y;
}
return *this;
}
int getX() { return x; }
int getY() { return y; }
void setX(int x0) { x = x0; }
void setY(int y0) { y = y0; }
virtual void print() { printf("Point\n"); }
};
class Circle: public Point {
private:
int r;
public:
Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
virtual ~Circle() {}
const Circle& operator=(const Circle &c) {
if (this != &c) {
x = c.x;
y = c.y;
r = c.r;
}
return *this;
}
int getR() { return r; }
void setR(int r0) { r = r0; }
virtual void print() { printf("Circle\n"); }
};
int main() {
Point *p = new Point();
Point *c = new Circle();
p->print();
c->print();
delete p;
delete c;
return EXIT_SUCCESS;
}
|
Convert this Go block to C++, preserving its control flow and logic. | package romap
type Romap struct{ imap map[byte]int }
func New(m map[byte]int) *Romap {
if m == nil {
return nil
}
return &Romap{m}
}
func (rom *Romap) Get(key byte) (int, bool) {
i, ok := rom.imap[key]
return i, ok
}
func (rom *Romap) Reset(key byte) {
_, ok := rom.imap[key]
if ok {
rom.imap[key] = 0
}
}
| #include <iostream>
#include <map>
#include <utility>
using namespace std;
template<typename T>
class FixedMap : private T
{
T m_defaultValues;
public:
FixedMap(T map)
: T(map), m_defaultValues(move(map)){}
using T::cbegin;
using T::cend;
using T::empty;
using T::find;
using T::size;
using T::at;
using T::begin;
using T::end;
auto& operator[](typename T::key_type&& key)
{
return this->at(forward<typename T::key_type>(key));
}
void erase(typename T::key_type&& key)
{
T::operator[](key) = m_defaultValues.at(key);
}
void clear()
{
T::operator=(m_defaultValues);
}
};
auto PrintMap = [](const auto &map)
{
for(auto &[key, value] : map)
{
cout << "{" << key << " : " << value << "} ";
}
cout << "\n\n";
};
int main(void)
{
cout << "Map intialized with values\n";
FixedMap<map<string, int>> fixedMap ({
{"a", 1},
{"b", 2}});
PrintMap(fixedMap);
cout << "Change the values of the keys\n";
fixedMap["a"] = 55;
fixedMap["b"] = 56;
PrintMap(fixedMap);
cout << "Reset the 'a' key\n";
fixedMap.erase("a");
PrintMap(fixedMap);
cout << "Change the values the again\n";
fixedMap["a"] = 88;
fixedMap["b"] = 99;
PrintMap(fixedMap);
cout << "Reset all keys\n";
fixedMap.clear();
PrintMap(fixedMap);
try
{
cout << "Try to add a new key\n";
fixedMap["newKey"] = 99;
}
catch (exception &ex)
{
cout << "error: " << ex.what();
}
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func contains(list []int, value int) bool {
for _, v := range list {
if v == value {
return true
}
}
return false
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 10 {
words = append(words, s)
}
}
vowelIndices := []int{0, 4, 8, 14, 20}
wordGroups := make([][]string, 12)
for _, word := range words {
letters := make([]int, 26)
for _, c := range word {
index := c - 97
if index >= 0 && index < 26 {
letters[index]++
}
}
eligible := true
uc := 0
for i := 0; i < 26; i++ {
if !contains(vowelIndices, i) {
if letters[i] > 1 {
eligible = false
break
} else if letters[i] == 1 {
uc++
}
}
}
if eligible {
wordGroups[uc] = append(wordGroups[uc], word)
}
}
for i := 11; i >= 0; i-- {
count := len(wordGroups[i])
if count > 0 {
s := "s"
if count == 1 {
s = ""
}
fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i)
for j := 0; j < count; j++ {
fmt.Printf("%-15s", wordGroups[i][j])
if j > 0 && (j+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
if count%5 != 0 {
fmt.Println()
}
}
}
}
| #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
if (ch < 'a' || ch > 'z')
continue;
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
bit = ch - 'a';
if (bits.test(bit))
return 0;
bits.set(bit);
break;
}
}
return bits.count();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
std::map<size_t, std::vector<std::string>, std::greater<int>> map;
while (getline(in, word)) {
if (word.size() <= 10)
continue;
size_t count = consonants(word);
if (count != 0)
map[count].push_back(word);
}
const int columns = 4;
for (const auto& p : map) {
std::cout << p.first << " consonants (" << p.second.size() << "):\n";
int n = 0;
for (const auto& word : p.second) {
std::cout << std::left << std::setw(18) << word;
++n;
if (n % columns == 0)
std::cout << '\n';
}
if (n % columns != 0)
std::cout << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func isPrime(n int) bool {
if n < 2 {
return false
}
if n%2 == 0 {
return n == 2
}
if n%3 == 0 {
return n == 3
}
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
func main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
| #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func isPrime(n int) bool {
if n < 2 {
return false
}
if n%2 == 0 {
return n == 2
}
if n%3 == 0 {
return n == 3
}
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
func main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
| #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func isPrime(n int) bool {
if n < 2 {
return false
}
if n%2 == 0 {
return n == 2
}
if n%3 == 0 {
return n == 3
}
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
func main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
| #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
|
Produce a functionally identical C++ code for the snippet given in Go. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func isPrime(n int) bool {
if n < 2 {
return false
}
if n%2 == 0 {
return n == 2
}
if n%3 == 0 {
return n == 3
}
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
func main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
| #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"fmt"
"math"
"rcu"
)
func divisorCount(n int) int {
k := 1
if n%2 == 1 {
k = 2
}
count := 0
sqrt := int(math.Sqrt(float64(n)))
for i := 1; i <= sqrt; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
}
return count
}
func main() {
var numbers50 []int
count := 0
for n := 1; count < 50000; n++ {
dc := divisorCount(n)
if n == 1 || dc == 8 {
count++
if count <= 50 {
numbers50 = append(numbers50, n)
if count == 50 {
rcu.PrintTable(numbers50, 10, 3, false)
}
} else if count == 500 {
fmt.Printf("\n500th : %s", rcu.Commatize(n))
} else if count == 5000 {
fmt.Printf("\n5,000th : %s", rcu.Commatize(n))
} else if count == 50000 {
fmt.Printf("\n50,000th: %s\n", rcu.Commatize(n))
}
}
}
}
| #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "First 50 numbers which are the cube roots of the products of "
"their proper divisors:\n";
for (unsigned int n = 1, count = 0; count < 50000; ++n) {
if (n == 1 || divisor_count(n) == 8) {
++count;
if (count <= 50)
std::cout << std::setw(3) << n
<< (count % 10 == 0 ? '\n' : ' ');
else if (count == 500 || count == 5000 || count == 50000)
std::cout << std::setw(6) << count << "th: " << n << '\n';
}
}
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import (
"fmt"
"rcu"
)
func main() {
const limit = 1e10
primes := rcu.Primes(limit)
var orm25 []int
j := int(1e9)
count := 0
var counts []int
for i := 0; i < len(primes)-2; i++ {
p1 := primes[i]
p2 := primes[i+1]
p3 := primes[i+2]
if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {
continue
}
key1 := 1
for _, dig := range rcu.Digits(p1, 10) {
key1 *= primes[dig]
}
key2 := 1
for _, dig := range rcu.Digits(p2, 10) {
key2 *= primes[dig]
}
if key1 != key2 {
continue
}
key3 := 1
for _, dig := range rcu.Digits(p3, 10) {
key3 *= primes[dig]
}
if key2 == key3 {
if count < 25 {
orm25 = append(orm25, p1)
}
if p1 >= j {
counts = append(counts, count)
j *= 10
}
count++
}
}
counts = append(counts, count)
fmt.Println("Smallest members of first 25 Ormiston triples:")
for i := 0; i < 25; i++ {
fmt.Printf("%8v ", orm25[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
j = int(1e9)
for i := 0; i < len(counts); i++ {
fmt.Printf("%s Ormiston triples before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j))
j *= 10
fmt.Println()
}
}
| #include <array>
#include <iostream>
#include <primesieve.hpp>
class ormiston_triple_generator {
public:
ormiston_triple_generator() {
for (int i = 0; i < 2; ++i) {
primes_[i] = pi_.next_prime();
digits_[i] = get_digits(primes_[i]);
}
}
std::array<uint64_t, 3> next_triple() {
for (;;) {
uint64_t prime = pi_.next_prime();
auto digits = get_digits(prime);
bool is_triple = digits == digits_[0] && digits == digits_[1];
uint64_t prime0 = primes_[0];
primes_[0] = primes_[1];
primes_[1] = prime;
digits_[0] = digits_[1];
digits_[1] = digits;
if (is_triple)
return {prime0, primes_[0], primes_[1]};
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
std::array<uint64_t, 2> primes_;
std::array<std::array<int, 10>, 2> digits_;
};
int main() {
ormiston_triple_generator generator;
int count = 0;
std::cout << "Smallest members of first 25 Ormiston triples:\n";
for (; count < 25; ++count) {
auto primes = generator.next_triple();
std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {
auto primes = generator.next_triple();
if (primes[2] > limit) {
std::cout << "Number of Ormiston triples < " << limit << ": "
<< count << '\n';
limit *= 10;
}
}
}
|
Write a version of this Go function in C++ with identical behavior. | package main
import (
"fmt"
"rcu"
)
func main() {
const limit = 1e10
primes := rcu.Primes(limit)
var orm25 []int
j := int(1e9)
count := 0
var counts []int
for i := 0; i < len(primes)-2; i++ {
p1 := primes[i]
p2 := primes[i+1]
p3 := primes[i+2]
if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {
continue
}
key1 := 1
for _, dig := range rcu.Digits(p1, 10) {
key1 *= primes[dig]
}
key2 := 1
for _, dig := range rcu.Digits(p2, 10) {
key2 *= primes[dig]
}
if key1 != key2 {
continue
}
key3 := 1
for _, dig := range rcu.Digits(p3, 10) {
key3 *= primes[dig]
}
if key2 == key3 {
if count < 25 {
orm25 = append(orm25, p1)
}
if p1 >= j {
counts = append(counts, count)
j *= 10
}
count++
}
}
counts = append(counts, count)
fmt.Println("Smallest members of first 25 Ormiston triples:")
for i := 0; i < 25; i++ {
fmt.Printf("%8v ", orm25[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
j = int(1e9)
for i := 0; i < len(counts); i++ {
fmt.Printf("%s Ormiston triples before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j))
j *= 10
fmt.Println()
}
}
| #include <array>
#include <iostream>
#include <primesieve.hpp>
class ormiston_triple_generator {
public:
ormiston_triple_generator() {
for (int i = 0; i < 2; ++i) {
primes_[i] = pi_.next_prime();
digits_[i] = get_digits(primes_[i]);
}
}
std::array<uint64_t, 3> next_triple() {
for (;;) {
uint64_t prime = pi_.next_prime();
auto digits = get_digits(prime);
bool is_triple = digits == digits_[0] && digits == digits_[1];
uint64_t prime0 = primes_[0];
primes_[0] = primes_[1];
primes_[1] = prime;
digits_[0] = digits_[1];
digits_[1] = digits;
if (is_triple)
return {prime0, primes_[0], primes_[1]};
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
std::array<uint64_t, 2> primes_;
std::array<std::array<int, 10>, 2> digits_;
};
int main() {
ormiston_triple_generator generator;
int count = 0;
std::cout << "Smallest members of first 25 Ormiston triples:\n";
for (; count < 25; ++count) {
auto primes = generator.next_triple();
std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {
auto primes = generator.next_triple();
if (primes[2] > limit) {
std::cout << "Number of Ormiston triples < " << limit << ": "
<< count << '\n';
limit *= 10;
}
}
}
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strings"
)
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func evolve(l, rule int) {
fmt.Printf(" Rule #%d:\n", rule)
cells := "O"
for x := 0; x < l; x++ {
cells = addNoCells(cells)
width := 40 + (len(cells) >> 1)
fmt.Printf("%*s\n", width, cells)
cells = step(cells, rule)
}
}
func step(cells string, rule int) string {
newCells := new(strings.Builder)
for i := 0; i < len(cells)-2; i++ {
bin := 0
b := uint(2)
for n := i; n < i+3; n++ {
bin += btoi(cells[n] == 'O') << b
b >>= 1
}
a := '.'
if rule&(1<<uint(bin)) != 0 {
a = 'O'
}
newCells.WriteRune(a)
}
return newCells.String()
}
func addNoCells(cells string) string {
l, r := "O", "O"
if cells[0] == 'O' {
l = "."
}
if cells[len(cells)-1] == 'O' {
r = "."
}
cells = l + cells + r
cells = l + cells + r
return cells
}
func main() {
for _, r := range []int{90, 30} {
evolve(25, r)
fmt.Println()
}
}
| #include <iostream>
#include <iomanip>
#include <string>
class oo {
public:
void evolve( int l, int rule ) {
std::string cells = "O";
std::cout << " Rule #" << rule << ":\n";
for( int x = 0; x < l; x++ ) {
addNoCells( cells );
std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n";
step( cells, rule );
}
}
private:
void step( std::string& cells, int rule ) {
int bin;
std::string newCells;
for( size_t i = 0; i < cells.length() - 2; i++ ) {
bin = 0;
for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {
bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );
}
newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );
}
cells = newCells;
}
void addNoCells( std::string& s ) {
char l = s.at( 0 ) == 'O' ? '.' : 'O',
r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';
s = l + s + r;
s = l + s + r;
}
};
int main( int argc, char* argv[] ) {
oo o;
o.evolve( 35, 90 );
std::cout << "\n";
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import (
"fmt"
"strings"
)
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func evolve(l, rule int) {
fmt.Printf(" Rule #%d:\n", rule)
cells := "O"
for x := 0; x < l; x++ {
cells = addNoCells(cells)
width := 40 + (len(cells) >> 1)
fmt.Printf("%*s\n", width, cells)
cells = step(cells, rule)
}
}
func step(cells string, rule int) string {
newCells := new(strings.Builder)
for i := 0; i < len(cells)-2; i++ {
bin := 0
b := uint(2)
for n := i; n < i+3; n++ {
bin += btoi(cells[n] == 'O') << b
b >>= 1
}
a := '.'
if rule&(1<<uint(bin)) != 0 {
a = 'O'
}
newCells.WriteRune(a)
}
return newCells.String()
}
func addNoCells(cells string) string {
l, r := "O", "O"
if cells[0] == 'O' {
l = "."
}
if cells[len(cells)-1] == 'O' {
r = "."
}
cells = l + cells + r
cells = l + cells + r
return cells
}
func main() {
for _, r := range []int{90, 30} {
evolve(25, r)
fmt.Println()
}
}
| #include <iostream>
#include <iomanip>
#include <string>
class oo {
public:
void evolve( int l, int rule ) {
std::string cells = "O";
std::cout << " Rule #" << rule << ":\n";
for( int x = 0; x < l; x++ ) {
addNoCells( cells );
std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n";
step( cells, rule );
}
}
private:
void step( std::string& cells, int rule ) {
int bin;
std::string newCells;
for( size_t i = 0; i < cells.length() - 2; i++ ) {
bin = 0;
for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {
bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );
}
newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );
}
cells = newCells;
}
void addNoCells( std::string& s ) {
char l = s.at( 0 ) == 'O' ? '.' : 'O',
r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';
s = l + s + r;
s = l + s + r;
}
};
int main( int argc, char* argv[] ) {
oo o;
o.evolve( 35, 90 );
std::cout << "\n";
return 0;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. |
package main
import (
"fmt"
"github.com/atotto/clipboard"
"io/ioutil"
"log"
"os"
"runtime"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
clipboard.WriteAll("")
log.Fatal(err)
}
}
func interpret(source string) {
source2 := source
if runtime.GOOS == "windows" {
source2 = strings.ReplaceAll(source, "\r\n", "\n")
}
lines := strings.Split(source2, "\n")
le := len(lines)
for i := 0; i < le; i++ {
lines[i] = strings.TrimSpace(lines[i])
switch lines[i] {
case "Copy":
if i == le-1 {
log.Fatal("There are no lines after the Copy command.")
}
i++
err := clipboard.WriteAll(lines[i])
check(err)
case "CopyFile":
if i == le-1 {
log.Fatal("There are no lines after the CopyFile command.")
}
i++
if lines[i] == "TheF*ckingCode" {
err := clipboard.WriteAll(source)
check(err)
} else {
bytes, err := ioutil.ReadFile(lines[i])
check(err)
err = clipboard.WriteAll(string(bytes))
check(err)
}
case "Duplicate":
if i == le-1 {
log.Fatal("There are no lines after the Duplicate command.")
}
i++
times, err := strconv.Atoi(lines[i])
check(err)
if times < 0 {
log.Fatal("Can't duplicate text a negative number of times.")
}
text, err := clipboard.ReadAll()
check(err)
err = clipboard.WriteAll(strings.Repeat(text, times+1))
check(err)
case "Pasta!":
text, err := clipboard.ReadAll()
check(err)
fmt.Println(text)
return
default:
if lines[i] == "" {
continue
}
log.Fatal("Unknown command, " + lines[i])
}
}
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There should be exactly one command line argument, the CopyPasta file path.")
}
bytes, err := ioutil.ReadFile(os.Args[1])
check(err)
interpret(string(bytes))
err = clipboard.WriteAll("")
check(err)
}
| #include <fstream>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>
#include <stdlib.h>
using namespace std;
void fatal_error(string errtext, char *argv[])
{
cout << "%" << errtext << endl;
cout << "usage: " << argv[0] << " [filename.cp]" << endl;
exit(1);
}
string& ltrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(0, str.find_first_not_of(chars));
return str;
}
string& rtrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(str.find_last_not_of(chars) + 1);
return str;
}
string& trim(string& str, const string& chars = "\t\n\v\f\r ")
{
return ltrim(rtrim(str, chars), chars);
}
int main(int argc, char *argv[])
{
string fname = "";
string source = "";
try
{
fname = argv[1];
ifstream t(fname);
t.seekg(0, ios::end);
source.reserve(t.tellg());
t.seekg(0, ios::beg);
source.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
}
catch(const exception& e)
{
fatal_error("error while trying to read from specified file", argv);
}
string clipboard = "";
int loc = 0;
string remaining = source;
string line = "";
string command = "";
stringstream ss;
while(remaining.find("\n") != string::npos)
{
line = remaining.substr(0, remaining.find("\n"));
command = trim(line);
remaining = remaining.substr(remaining.find("\n") + 1);
try
{
if(line == "Copy")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
clipboard += line;
}
else if(line == "CopyFile")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
if(line == "TheF*ckingCode")
clipboard += source;
else
{
string filetext = "";
ifstream t(line);
t.seekg(0, ios::end);
filetext.reserve(t.tellg());
t.seekg(0, ios::beg);
filetext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
clipboard += filetext;
}
}
else if(line == "Duplicate")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
int amount = stoi(line);
string origClipboard = clipboard;
for(int i = 0; i < amount - 1; i++) {
clipboard += origClipboard;
}
}
else if(line == "Pasta!")
{
cout << clipboard << endl;
return 0;
}
else
{
ss << (loc + 1);
fatal_error("unknown command '" + command + "' encounter on line " + ss.str(), argv);
}
}
catch(const exception& e)
{
ss << (loc + 1);
fatal_error("error while executing command '" + command + "' on line " + ss.str(), argv);
}
loc += 2;
}
return 0;
}
|
Convert the following code from Go to C++, ensuring the logic remains intact. | package main
import (
"fmt"
"rcu"
)
const limit = 100000
func nonTwinSums(twins []int) []int {
sieve := make([]bool, limit+1)
for i := 0; i < len(twins); i++ {
for j := i; j < len(twins); j++ {
sum := twins[i] + twins[j]
if sum > limit {
break
}
sieve[sum] = true
}
}
var res []int
for i := 2; i < limit; i += 2 {
if !sieve[i] {
res = append(res, i)
}
}
return res
}
func main() {
primes := rcu.Primes(limit)[2:]
twins := []int{3}
for i := 0; i < len(primes)-1; i++ {
if primes[i+1]-primes[i] == 2 {
if twins[len(twins)-1] != primes[i] {
twins = append(twins, primes[i])
}
twins = append(twins, primes[i+1])
}
}
fmt.Println("Non twin prime sums:")
ntps := nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
fmt.Println("\nNon twin prime sums (including 1):")
twins = append([]int{1}, twins...)
ntps = nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
}
| #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
void print_non_twin_prime_sums(const std::vector<bool>& sums) {
int count = 0;
for (size_t i = 2; i < sums.size(); i += 2) {
if (!sums[i]) {
++count;
std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' ');
}
}
std::cout << "\nFound " << count << '\n';
}
int main() {
const int limit = 100001;
std::vector<bool> sieve = prime_sieve(limit + 2);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))
sieve[i] = false;
}
std::vector<bool> twin_prime_sums(limit, false);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i]) {
for (size_t j = i; i + j < limit; ++j) {
if (sieve[j])
twin_prime_sums[i + j] = true;
}
}
}
std::cout << "Non twin prime sums:\n";
print_non_twin_prime_sums(twin_prime_sums);
sieve[1] = true;
for (size_t i = 1; i + 1 < limit; ++i) {
if (sieve[i])
twin_prime_sums[i + 1] = true;
}
std::cout << "\nNon twin prime sums (including 1):\n";
print_non_twin_prime_sums(twin_prime_sums);
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"fmt"
"rcu"
)
const limit = 100000
func nonTwinSums(twins []int) []int {
sieve := make([]bool, limit+1)
for i := 0; i < len(twins); i++ {
for j := i; j < len(twins); j++ {
sum := twins[i] + twins[j]
if sum > limit {
break
}
sieve[sum] = true
}
}
var res []int
for i := 2; i < limit; i += 2 {
if !sieve[i] {
res = append(res, i)
}
}
return res
}
func main() {
primes := rcu.Primes(limit)[2:]
twins := []int{3}
for i := 0; i < len(primes)-1; i++ {
if primes[i+1]-primes[i] == 2 {
if twins[len(twins)-1] != primes[i] {
twins = append(twins, primes[i])
}
twins = append(twins, primes[i+1])
}
}
fmt.Println("Non twin prime sums:")
ntps := nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
fmt.Println("\nNon twin prime sums (including 1):")
twins = append([]int{1}, twins...)
ntps = nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
}
| #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
void print_non_twin_prime_sums(const std::vector<bool>& sums) {
int count = 0;
for (size_t i = 2; i < sums.size(); i += 2) {
if (!sums[i]) {
++count;
std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' ');
}
}
std::cout << "\nFound " << count << '\n';
}
int main() {
const int limit = 100001;
std::vector<bool> sieve = prime_sieve(limit + 2);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))
sieve[i] = false;
}
std::vector<bool> twin_prime_sums(limit, false);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i]) {
for (size_t j = i; i + j < limit; ++j) {
if (sieve[j])
twin_prime_sums[i + j] = true;
}
}
}
std::cout << "Non twin prime sums:\n";
print_non_twin_prime_sums(twin_prime_sums);
sieve[1] = true;
for (size_t i = 1; i + 1 < limit; ++i) {
if (sieve[i])
twin_prime_sums[i + 1] = true;
}
std::cout << "\nNon twin prime sums (including 1):\n";
print_non_twin_prime_sums(twin_prime_sums);
}
|
Change the following Go code into C++ without altering its purpose. | package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
vis := make([]bool, len(g))
L := make([]int, len(g))
x := len(L)
t := make([][]int, len(g))
var Visit func(int)
Visit = func(u int) {
if !vis[u] {
vis[u] = true
for _, v := range g[u] {
Visit(v)
t[v] = append(t[v], u)
}
x--
L[x] = u
}
}
for u := range g {
Visit(u)
}
c := make([]int, len(g))
var Assign func(int, int)
Assign = func(u, root int) {
if vis[u] {
vis[u] = false
c[u] = root
for _, v := range t[u] {
Assign(v, root)
}
}
}
for _, u := range L {
Assign(u, u)
}
return c
}
| #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << "]";
}
std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
auto size = g.size();
std::vector<bool> vis(size);
std::vector<int> l(size);
auto x = size;
std::vector<std::vector<int>> t(size);
std::function<void(int)> visit;
visit = [&](int u) {
if (!vis[u]) {
vis[u] = true;
for (auto v : g[u]) {
visit(v);
t[v].push_back(u);
}
l[--x] = u;
}
};
for (int i = 0; i < g.size(); ++i) {
visit(i);
}
std::vector<int> c(size);
std::function<void(int, int)> assign;
assign = [&](int u, int root) {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (auto v : t[u]) {
assign(v, root);
}
}
};
for (auto u : l) {
assign(u, u);
}
return c;
}
std::vector<std::vector<int>> g = {
{1},
{2},
{0},
{1, 2, 4},
{3, 5},
{2, 6},
{5},
{4, 6, 7},
};
int main() {
using namespace std;
cout << kosaraju(g) << endl;
return 0;
}
|
Convert the following code from Go to C++, ensuring the logic remains intact. | package main
import (
"fmt"
"math"
)
type mwriter struct {
value float64
log string
}
func (m mwriter) bind(f func(v float64) mwriter) mwriter {
n := f(m.value)
n.log = m.log + n.log
return n
}
func unit(v float64, s string) mwriter {
return mwriter{v, fmt.Sprintf(" %-17s: %g\n", s, v)}
}
func root(v float64) mwriter {
return unit(math.Sqrt(v), "Took square root")
}
func addOne(v float64) mwriter {
return unit(v+1, "Added one")
}
func half(v float64) mwriter {
return unit(v/2, "Divided by two")
}
func main() {
mw1 := unit(5, "Initial value")
mw2 := mw1.bind(root).bind(addOne).bind(half)
fmt.Println("The Golden Ratio is", mw2.value)
fmt.Println("\nThis was derived as follows:-")
fmt.Println(mw2.log)
}
| #include <cmath>
#include <iostream>
#include <string>
using namespace std;
struct LoggingMonad
{
double Value;
string Log;
};
auto operator>>(const LoggingMonad& monad, auto f)
{
auto result = f(monad.Value);
return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}
auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };
auto MakeWriter = [](auto f, string message)
{
return [=](double x){return LoggingMonad(f(x), message);};
};
auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");
int main()
{
auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
cout << result.Log << "\nResult: " << result.Value;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"fmt"
"os"
"sort"
"strings"
"text/template"
)
func main() {
const t = `[[[{{index .P 1}}, {{index .P 2}}],
[{{index .P 3}}, {{index .P 4}}, {{index .P 1}}],
{{index .P 5}}]]
`
type S struct {
P map[int]string
}
var s S
s.P = map[int]string{
0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'",
4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'",
}
tmpl := template.Must(template.New("").Parse(t))
tmpl.Execute(os.Stdout, s)
var unused []int
for k, _ := range s.P {
if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) {
unused = append(unused, k)
}
}
sort.Ints(unused)
fmt.Println("\nThe unused payloads have indices of :", unused)
}
| #include <iostream>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
if(index < 0 || index >= (int)size(payloads)) cout << "null";
else cout << "'" << payloads[index] << "'";
if (!isLast) cout << ", ";
}
template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
std::apply
(
[&payloads, isLast](Ts const&... tupleArgs)
{
size_t n{0};
cout << "[";
(PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
cout << "]";
cout << (isLast ? "\n" : ",\n");
}, nestedTuple
);
}
void FindUniqueIndexes(set<int> &indexes, int index)
{
indexes.insert(index);
}
template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
std::apply
(
[&indexes](Ts const&... tupleArgs)
{
(FindUniqueIndexes(indexes, tupleArgs),...);
}, nestedTuple
);
}
template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
for(size_t i = 0; i < size(payloads); i++)
{
if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
}
}
int main()
{
vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"};
auto tpl = make_tuple(make_tuple(
make_tuple(1, 2),
make_tuple(3, 4, 1),
5));
cout << "Mapping indexes to payloads:\n";
PrintPayloads(payloads, tpl);
cout << "\nFinding unused payloads:\n";
set<int> usedIndexes;
FindUniqueIndexes(usedIndexes, tpl);
PrintUnusedPayloads(usedIndexes, payloads);
cout << "\nMapping to some out of range payloads:\n";
PrintPayloads(shortPayloads, tpl);
return 0;
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import "fmt"
type Outer struct {
field int
Inner struct {
field int
}
}
func (o *Outer) outerMethod() {
fmt.Println("Outer's field has a value of", o.field)
}
func (o *Outer) innerMethod() {
fmt.Println("Inner's field has a value of", o.Inner.field)
}
func main() {
o := &Outer{field: 43}
o.Inner.field = 42
o.innerMethod()
o.outerMethod()
p := &Outer{
field: 45,
Inner: struct {
field int
}{
field: 44,
},
}
p.innerMethod()
p.outerMethod()
}
| #include <iostream>
#include <vector>
class Outer
{
int m_privateField;
public:
Outer(int value) : m_privateField{value}{}
class Inner
{
int m_innerValue;
public:
Inner(int innerValue) : m_innerValue{innerValue}{}
int AddOuter(Outer outer) const
{
return outer.m_privateField + m_innerValue;
}
};
};
int main()
{
Outer::Inner inner{42};
Outer outer{1};
auto sum = inner.AddOuter(outer);
std::cout << "sum: " << sum << "\n";
std::vector<int> vec{1,2,3};
std::vector<int>::iterator itr = vec.begin();
std::cout << "vec[0] = " << *itr << "\n";
}
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
for a := 3; ; a++ {
for b := a + 1; ; b++ {
c := 1000 - a - b
if c <= b {
break
}
if a*a+b*b == c*c {
fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
fmt.Println("a + b + c =", a+b+c)
fmt.Println("a * b * c =", a*b*c)
fmt.Println("\nTook", time.Since(start))
return
}
}
}
}
| #include <cmath>
#include <concepts>
#include <iostream>
#include <numeric>
#include <optional>
#include <tuple>
using namespace std;
optional<tuple<int, int ,int>> FindPerimeterTriplet(int perimeter)
{
unsigned long long perimeterULL = perimeter;
auto max_M = (unsigned long long)sqrt(perimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto primitive = a + b + c;
auto factor = perimeterULL / primitive;
if(primitive * factor == perimeterULL)
{
if(b<a) swap(a, b);
return tuple{a * factor, b * factor, c * factor};
}
}
}
return nullopt;
}
int main()
{
auto t1 = FindPerimeterTriplet(1000);
if(t1)
{
auto [a, b, c] = *t1;
cout << "[" << a << ", " << b << ", " << c << "]\n";
cout << "a * b * c = " << a * b * c << "\n";
}
else
{
cout << "Perimeter not found\n";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.