Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import(
"fmt"
"unsafe"
"reflect"
)
func pointer() {
fmt.Printf("Pointer:\n")
var i int
p := &i
fmt.Printf("Before:\n\t%v: %v, %v\n", p, *p, i)
*p = 3
fmt.Printf("After:\n\t%v: %v, %v\n", p, *p, i)
}
func slice() {
fmt.Printf("Slice:\n")
var a [10]byte
var h reflect.SliceHeader
h.Data = uintptr(unsafe.Pointer(&a))
h.Len = len(a)
h.Cap = len(a)
s := *(*[]byte)(unsafe.Pointer(&h))
fmt.Printf("Before:\n\ts: %v\n\ta: %v\n", s, a)
copy(s, "A string.")
fmt.Printf("After:\n\ts: %v\n\ta: %v\n", s, a)
}
func main() {
pointer()
fmt.Println()
slice()
}
| #include <string>
#include <iostream>
int main()
{
char* data = new char[sizeof(std::string)];
std::string* stringPtr = new (data) std::string("ABCD");
std::cout << *stringPtr << " 0x" << stringPtr << std::endl;
stringPtr->~basic_string();
stringPtr = new (data) std::string("123456");
std::cout << *stringPtr << " 0x" << stringPtr << std::endl;
stringPtr->~basic_string();
delete[] data;
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
pm := big.NewInt(1)
var px, nx int
var pb big.Int
primes(4000, func(p int64) bool {
pm.Mul(pm, pb.SetInt64(p))
px++
if pb.Add(pm, one).ProbablyPrime(0) ||
pb.Sub(pm, one).ProbablyPrime(0) {
fmt.Print(px, " ")
nx++
if nx == 20 {
fmt.Println()
return false
}
}
return true
})
}
func primes(limit int, f func(int64) bool) {
c := make([]bool, limit)
c[0] = true
c[1] = true
lm := int64(limit)
p := int64(2)
for {
f(p)
p2 := p * p
if p2 >= lm {
break
}
for i := p2; i < lm; i += p {
c[i] = true
}
for {
p++
if !c[p] {
break
}
}
}
for p++; p < lm; p++ {
if !c[p] && !f(p) {
break
}
}
}
| #include <cstdint>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_probably_prime(const integer& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
int main() {
const unsigned int max = 20;
integer primorial = 1;
for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {
if (!is_prime(p))
continue;
primorial *= p;
++index;
if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {
if (count > 0)
std::cout << ' ';
std::cout << index;
++count;
}
}
std::cout << '\n';
return 0;
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
| #include <map>
#include <string>
#include <iostream>
#include <iomanip>
const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";
class DnaBase {
public:
DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {
for (auto elm : dna) {
if (count.find(elm) == count.end())
count[elm] = 0;
++count[elm];
}
}
void viewGenome() {
std::cout << "Sequence:" << std::endl;
std::cout << std::endl;
int limit = genome.size() / displayWidth;
if (genome.size() % displayWidth != 0)
++limit;
for (int i = 0; i < limit; ++i) {
int beginPos = i * displayWidth;
std::cout << std::setw(4) << beginPos << " :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;
}
std::cout << std::endl;
std::cout << "Base Count" << std::endl;
std::cout << "----------" << std::endl;
std::cout << std::endl;
int total = 0;
for (auto elm : count) {
std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl;
total += elm.second;
}
std::cout << std::endl;
std::cout << "Total: " << total << std::endl;
}
private:
std::string genome;
std::map<char, int> count;
int displayWidth;
};
int main(void) {
auto d = new DnaBase();
d->viewGenome();
delete d;
return 0;
}
|
Write a version of this Go function in C++ with identical behavior. | package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
| #include <map>
#include <string>
#include <iostream>
#include <iomanip>
const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";
class DnaBase {
public:
DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {
for (auto elm : dna) {
if (count.find(elm) == count.end())
count[elm] = 0;
++count[elm];
}
}
void viewGenome() {
std::cout << "Sequence:" << std::endl;
std::cout << std::endl;
int limit = genome.size() / displayWidth;
if (genome.size() % displayWidth != 0)
++limit;
for (int i = 0; i < limit; ++i) {
int beginPos = i * displayWidth;
std::cout << std::setw(4) << beginPos << " :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;
}
std::cout << std::endl;
std::cout << "Base Count" << std::endl;
std::cout << "----------" << std::endl;
std::cout << std::endl;
int total = 0;
for (auto elm : count) {
std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl;
total += elm.second;
}
std::cout << std::endl;
std::cout << "Total: " << total << std::endl;
}
private:
std::string genome;
std::map<char, int> count;
int displayWidth;
};
int main(void) {
auto d = new DnaBase();
d->viewGenome();
delete d;
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"hash/fnv"
"log"
"math/rand"
"os"
"time"
)
var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
const hunger = 3
const think = time.Second / 100
const eat = time.Second / 100
var fmt = log.New(os.Stdout, "", 0)
var done = make(chan bool)
type fork byte
func philosopher(phName string,
dominantHand, otherHand chan fork, done chan bool) {
fmt.Println(phName, "seated")
h := fnv.New64a()
h.Write([]byte(phName))
rg := rand.New(rand.NewSource(int64(h.Sum64())))
rSleep := func(t time.Duration) {
time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))
}
for h := hunger; h > 0; h-- {
fmt.Println(phName, "hungry")
<-dominantHand
<-otherHand
fmt.Println(phName, "eating")
rSleep(eat)
dominantHand <- 'f'
otherHand <- 'f'
fmt.Println(phName, "thinking")
rSleep(think)
}
fmt.Println(phName, "satisfied")
done <- true
fmt.Println(phName, "left the table")
}
func main() {
fmt.Println("table empty")
place0 := make(chan fork, 1)
place0 <- 'f'
placeLeft := place0
for i := 1; i < len(ph); i++ {
placeRight := make(chan fork, 1)
placeRight <- 'f'
go philosopher(ph[i], placeLeft, placeRight, done)
placeLeft = placeRight
}
go philosopher(ph[0], place0, placeLeft, done)
for range ph {
<-done
}
fmt.Println("table empty")
}
| #include <algorithm>
#include <array>
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <string>
#include <string_view>
#include <thread>
const int timeScale = 42;
void Message(std::string_view message)
{
static std::mutex cout_mutex;
std::scoped_lock cout_lock(cout_mutex);
std::cout << message << std::endl;
}
struct Fork {
std::mutex mutex;
};
struct Dinner {
std::array<Fork, 5> forks;
~Dinner() { Message("Dinner is over"); }
};
class Philosopher
{
std::mt19937 rng{std::random_device {}()};
const std::string name;
Fork& left;
Fork& right;
std::thread worker;
void live();
void dine();
void ponder();
public:
Philosopher(std::string name_, Fork& l, Fork& r)
: name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)
{}
~Philosopher()
{
worker.join();
Message(name + " went to sleep.");
}
};
void Philosopher::live()
{
for(;;)
{
{
std::scoped_lock dine_lock(left.mutex, right.mutex);
dine();
}
ponder();
}
}
void Philosopher::dine()
{
Message(name + " started eating.");
thread_local std::array<const char*, 3> foods {"chicken", "rice", "soda"};
thread_local std::array<const char*, 3> reactions {
"I like this %s!", "This %s is good.", "Mmm, %s..."
};
thread_local std::uniform_int_distribution<> dist(1, 6);
std::shuffle( foods.begin(), foods.end(), rng);
std::shuffle(reactions.begin(), reactions.end(), rng);
constexpr size_t buf_size = 64;
char buffer[buf_size];
for(int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));
snprintf(buffer, buf_size, reactions[i], foods[i]);
Message(name + ": " + buffer);
}
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);
Message(name + " finished and left.");
}
void Philosopher::ponder()
{
static constexpr std::array<const char*, 5> topics {{
"politics", "art", "meaning of life", "source of morality", "how many straws makes a bale"
}};
thread_local std::uniform_int_distribution<> wait(1, 6);
thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);
while(dist(rng) > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is pondering about " + topics[dist(rng)] + ".");
}
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is hungry again!");
}
int main()
{
Dinner dinner;
Message("Dinner started!");
std::array<Philosopher, 5> philosophers {{
{"Aristotle", dinner.forks[0], dinner.forks[1]},
{"Democritus", dinner.forks[1], dinner.forks[2]},
{"Plato", dinner.forks[2], dinner.forks[3]},
{"Pythagoras", dinner.forks[3], dinner.forks[4]},
{"Socrates", dinner.forks[4], dinner.forks[0]},
}};
Message("It is dark outside...");
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
| #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return sum == i;
}
private:
ulong f[12];
};
int main() {
factorion_t factorion;
for (uint b = 9u; b <= 12u; ++b) {
std::cout << "factorions for base " << b << ':';
for (uint i = 1u; i < 1500000u; ++i)
if (factorion(i, b))
std::cout << ' ' << i;
std::cout << std::endl;
}
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
| #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return sum == i;
}
private:
ulong f[12];
};
int main() {
factorion_t factorion;
for (uint b = 9u; b <= 12u; ++b) {
std::cout << "factorions for base " << b << ':';
for (uint i = 1u; i < 1500000u; ++i)
if (factorion(i, b))
std::cout << ' ' << i;
std::cout << std::endl;
}
return 0;
}
|
Convert the following code from Go to C++, ensuring the logic remains intact. | package main
import (
"fmt"
"github.com/maorshutman/lm"
"log"
"math"
)
const (
K = 7_800_000_000
n0 = 27
)
var y = []float64{
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,
2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,
24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,
60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,
76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,
85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,
105824, 109695, 114232, 118610, 125497, 133852, 143227,
151367, 167418, 180096, 194836, 213150, 242364, 271106,
305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054,
1174652,
}
func f(dst, p []float64) {
for i := 0; i < len(y); i++ {
t := float64(i)
dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]
}
}
func main() {
j := lm.NumJac{Func: f}
prob := lm.LMProblem{
Dim: 1,
Size: len(y),
Func: f,
Jac: j.Jac,
InitParams: []float64{0.5},
Tau: 1e-6,
Eps1: 1e-8,
Eps2: 1e-8,
}
res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})
if err != nil {
log.Fatal(err)
}
r := res.X[0]
fmt.Printf("The logistic curve r for the world data is %.8f\n", r)
fmt.Printf("R0 is then approximately equal to %.7f\n", math.Exp(12*r))
}
| #include <cmath>
#include <functional>
#include <iostream>
constexpr double K = 7.8e9;
constexpr int n0 = 27;
constexpr double actual[] = {
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,
4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,
31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,
69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,
80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,
95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,
133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,
271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652
};
double f(double r) {
double sq = 0;
constexpr size_t len = std::size(actual);
for (size_t i = 0; i < len; ++i) {
double eri = std::exp(r * i);
double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);
double diff = guess - actual[i];
sq += diff * diff;
}
return sq;
}
double solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {
for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2;
delta > epsilon && guess != guess - delta;
delta *= factor) {
double nf = fn(guess - delta);
if (nf < f0) {
f0 = nf;
guess -= delta;
} else {
nf = fn(guess + delta);
if (nf < f0) {
f0 = nf;
guess += delta;
} else
factor = 0.5;
}
}
return guess;
}
int main() {
double r = solve(f);
double R0 = std::exp(12 * r);
std::cout << "r = " << r << ", R0 = " << R0 << '\n';
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import "fmt"
type link struct {
int
next *link
}
func linkInts(s []int) *link {
if len(s) == 0 {
return nil
}
return &link{s[0], linkInts(s[1:])}
}
func (l *link) String() string {
if l == nil {
return "nil"
}
r := fmt.Sprintf("[%d", l.int)
for l = l.next; l != nil; l = l.next {
r = fmt.Sprintf("%s %d", r, l.int)
}
return r + "]"
}
func main() {
a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})
fmt.Println("before:", a)
b := strandSort(a)
fmt.Println("after: ", b)
}
func strandSort(a *link) (result *link) {
for a != nil {
sublist := a
a = a.next
sTail := sublist
for p, pPrev := a, a; p != nil; p = p.next {
if p.int > sTail.int {
sTail.next = p
sTail = p
if p == a {
a = p.next
} else {
pPrev.next = p.next
}
} else {
pPrev = p
}
}
sTail.next = nil
if result == nil {
result = sublist
continue
}
var m, rr *link
if sublist.int < result.int {
m = sublist
sublist = m.next
rr = result
} else {
m = result
rr = m.next
}
result = m
for {
if sublist == nil {
m.next = rr
break
}
if rr == nil {
m.next = sublist
break
}
if sublist.int < rr.int {
m.next = sublist
m = sublist
sublist = m.next
} else {
m.next = rr
m = rr
rr = m.next
}
}
}
return
}
| #include <list>
template <typename T>
std::list<T> strandSort(std::list<T> lst) {
if (lst.size() <= 1)
return lst;
std::list<T> result;
std::list<T> sorted;
while (!lst.empty()) {
sorted.push_back(lst.front());
lst.pop_front();
for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {
if (sorted.back() <= *it) {
sorted.push_back(*it);
it = lst.erase(it);
} else
it++;
}
result.merge(sorted);
}
return result;
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
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 sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func main() {
fmt.Println("Additive primes less than 500:")
i := 2
count := 0
for {
if isPrime(i) && isPrime(sumDigits(i)) {
count++
fmt.Printf("%3d ", i)
if count%10 == 0 {
fmt.Println()
}
}
if i > 2 {
i += 2
} else {
i++
}
if i > 499 {
break
}
}
fmt.Printf("\n\n%d additive primes found.\n", count)
}
| #include <iomanip>
#include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int digit_sum(unsigned int n) {
unsigned int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
int main() {
const unsigned int limit = 500;
std::cout << "Additive primes less than " << limit << ":\n";
unsigned int count = 0;
for (unsigned int n = 1; n < limit; ++n) {
if (is_prime(digit_sum(n)) && is_prime(n)) {
std::cout << std::setw(3) << n;
if (++count % 10 == 0)
std::cout << '\n';
else
std::cout << ' ';
}
}
std::cout << '\n' << count << " additive primes found.\n";
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
if raining {
needUmbrella = true
}
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
raining = false
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
| class invertedAssign {
int data;
public:
invertedAssign(int data):data(data){}
int getData(){return data;}
void operator=(invertedAssign& other) const {
other.data = this->data;
}
};
#include <iostream>
int main(){
invertedAssign a = 0;
invertedAssign b = 42;
std::cout << a.getData() << ' ' << b.getData() << '\n';
b = a;
std::cout << a.getData() << ' ' << b.getData() << '\n';
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
if raining {
needUmbrella = true
}
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
raining = false
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
| class invertedAssign {
int data;
public:
invertedAssign(int data):data(data){}
int getData(){return data;}
void operator=(invertedAssign& other) const {
other.data = this->data;
}
};
#include <iostream>
int main(){
invertedAssign a = 0;
invertedAssign b = 42;
std::cout << a.getData() << ' ' << b.getData() << '\n';
b = a;
std::cout << a.getData() << ' ' << b.getData() << '\n';
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
bool perfect_totient_number(const totient_calculator& tc, int n) {
int sum = 0;
for (int m = n; m > 1; ) {
int t = tc.totient(m);
sum += t;
m = t;
}
return sum == n;
}
int main() {
totient_calculator tc(10000);
int count = 0, n = 1;
std::cout << "First 20 perfect totient numbers:\n";
for (; count < 20; ++n) {
if (perfect_totient_number(tc, n)) {
if (count > 0)
std::cout << ' ';
++count;
std::cout << n;
}
}
std::cout << '\n';
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
bool perfect_totient_number(const totient_calculator& tc, int n) {
int sum = 0;
for (int m = n; m > 1; ) {
int t = tc.totient(m);
sum += t;
m = t;
}
return sum == n;
}
int main() {
totient_calculator tc(10000);
int count = 0, n = 1;
std::cout << "First 20 perfect totient numbers:\n";
for (; count < 20; ++n) {
if (perfect_totient_number(tc, n)) {
if (count > 0)
std::cout << ' ';
++count;
std::cout << n;
}
}
std::cout << '\n';
return 0;
}
|
Generate an equivalent C++ version of this Go code. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
bool perfect_totient_number(const totient_calculator& tc, int n) {
int sum = 0;
for (int m = n; m > 1; ) {
int t = tc.totient(m);
sum += t;
m = t;
}
return sum == n;
}
int main() {
totient_calculator tc(10000);
int count = 0, n = 1;
std::cout << "First 20 perfect totient numbers:\n";
for (; count < 20; ++n) {
if (perfect_totient_number(tc, n)) {
if (count > 0)
std::cout << ' ';
++count;
std::cout << n;
}
}
std::cout << '\n';
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import "fmt"
type Delegator struct {
delegate interface{}
}
type Thingable interface {
thing() string
}
func (self Delegator) operation() string {
if v, ok := self.delegate.(Thingable); ok {
return v.thing()
}
return "default implementation"
}
type Delegate int
func (Delegate) thing() string {
return "delegate implementation"
}
func main() {
a := Delegator{}
fmt.Println(a.operation())
a.delegate = "A delegate may be any object"
fmt.Println(a.operation())
var d Delegate
a.delegate = d
fmt.Println(a.operation())
}
| #include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace std::tr1;
using std::tr1::function;
class IDelegate
{
public:
virtual ~IDelegate() {}
};
class IThing
{
public:
virtual ~IThing() {}
virtual std::string Thing() = 0;
};
class DelegateA : virtual public IDelegate
{
};
class DelegateB : public IThing, public IDelegate
{
std::string Thing()
{
return "delegate implementation";
}
};
class Delegator
{
public:
std::string Operation()
{
if(Delegate)
if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))
return pThing->Thing();
return "default implementation";
}
shared_ptr<IDelegate> Delegate;
};
int main()
{
shared_ptr<DelegateA> delegateA(new DelegateA());
shared_ptr<DelegateB> delegateB(new DelegateB());
Delegator delegator;
std::cout << delegator.Operation() << std::endl;
delegator.Delegate = delegateA;
std::cout << delegator.Operation() << std::endl;
delegator.Delegate = delegateB;
std::cout << delegator.Operation() << std::endl;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
| #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(4) << divisor_sum(n);
if (n % 10 == 0)
std::cout << '\n';
}
}
|
Write the same code in C++ as shown below in Go. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
| #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(4) << divisor_sum(n);
if (n % 10 == 0)
std::cout << '\n';
}
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
| #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(4) << divisor_sum(n);
if (n % 10 == 0)
std::cout << '\n';
}
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
| #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
| #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
func main() {
s := "immutable"
s[0] = 'a'
}
| #include <iostream>
class MyOtherClass
{
public:
const int m_x;
MyOtherClass(const int initX = 0) : m_x(initX) { }
};
int main()
{
MyOtherClass mocA, mocB(7);
std::cout << mocA.m_x << std::endl;
std::cout << mocB.m_x << std::endl;
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import "fmt"
type point struct {
x, y float32
}
var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}
var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}
func main() {
var cp1, cp2, s, e point
inside := func(p point) bool {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
}
intersection := func() (p point) {
dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y
dpx, dpy := s.x-e.x, s.y-e.y
n1 := cp1.x*cp2.y - cp1.y*cp2.x
n2 := s.x*e.y - s.y*e.x
n3 := 1 / (dcx*dpy - dcy*dpx)
p.x = (n1*dpx - n2*dcx) * n3
p.y = (n1*dpy - n2*dcy) * n3
return
}
outputList := subjectPolygon
cp1 = clipPolygon[len(clipPolygon)-1]
for _, cp2 = range clipPolygon {
inputList := outputList
outputList = nil
s = inputList[len(inputList)-1]
for _, e = range inputList {
if inside(e) {
if !inside(s) {
outputList = append(outputList, intersection())
}
outputList = append(outputList, e)
} else if inside(s) {
outputList = append(outputList, intersection())
}
s = e
}
cp1 = cp2
}
fmt.Println(outputList)
}
| #include <iostream>
#include <span>
#include <vector>
struct vec2 {
float x = 0.0f, y = 0.0f;
constexpr vec2 operator+(vec2 other) const {
return vec2{x + other.x, y + other.y};
}
constexpr vec2 operator-(vec2 other) const {
return vec2{x - other.x, y - other.y};
}
};
constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }
constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }
constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }
constexpr bool is_inside(vec2 point, vec2 a, vec2 b) {
return (cross(a - b, point) + cross(b, a)) < 0.0f;
}
constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {
return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *
(1.0f / cross(a1 - a2, b1 - b2));
}
std::vector<vec2> suther_land_hodgman(
std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {
if (clip_polygon.empty() || subject_polygon.empty()) {
return {};
}
std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};
vec2 p1 = clip_polygon[clip_polygon.size() - 1];
std::vector<vec2> input;
for (vec2 p2 : clip_polygon) {
input.clear();
input.insert(input.end(), ring.begin(), ring.end());
vec2 s = input[input.size() - 1];
ring.clear();
for (vec2 e : input) {
if (is_inside(e, p1, p2)) {
if (!is_inside(s, p1, p2)) {
ring.push_back(intersection(p1, p2, s, e));
}
ring.push_back(e);
} else if (is_inside(s, p1, p2)) {
ring.push_back(intersection(p1, p2, s, e));
}
s = e;
}
p1 = p2;
}
return ring;
}
int main(int argc, char **argv) {
vec2 subject_polygon[] = {{50, 150}, {200, 50}, {350, 150},
{350, 300}, {250, 300}, {200, 250},
{150, 350}, {100, 250}, {100, 200}};
vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};
std::vector<vec2> clipped_polygon =
suther_land_hodgman(subject_polygon, clip_polygon);
std::cout << "Clipped polygon points:" << std::endl;
for (vec2 p : clipped_polygon) {
std::cout << "(" << p.x << ", " << p.y << ")" << std::endl;
}
return EXIT_SUCCESS;
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
| #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
| #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
|
Change the following Go code into C++ without altering its purpose. | package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
| #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"fmt"
"strconv"
)
var n = 5
func main() {
if n < 1 {
return
}
top, left, bottom, right := 0, 0, n-1, n-1
sz := n * n
a := make([]int, sz)
i := 0
for left < right {
for c := left; c <= right; c++ {
a[top*n+c] = i
i++
}
top++
for r := top; r <= bottom; r++ {
a[r*n+right] = i
i++
}
right--
if top == bottom {
break
}
for c := right; c >= left; c-- {
a[bottom*n+c] = i
i++
}
bottom--
for r := bottom; r >= top; r-- {
a[r*n+left] = i
i++
}
left++
}
a[top*n+left] = i
w := len(strconv.Itoa(n*n - 1))
for i, e := range a {
fmt.Printf("%*d ", w, e)
if i%n == n-1 {
fmt.Println("")
}
}
}
| #include <vector>
#include <memory>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;
auto_ptr< IntTable > getSpiralArray( int dimension )
{
auto_ptr< IntTable > spiralArrayPtr( new IntTable(
dimension, IntRow( dimension ) ) );
int numConcentricSquares = static_cast< int >( ceil(
static_cast< double >( dimension ) / 2.0 ) );
int j;
int sideLen = dimension;
int currNum = 0;
for ( int i = 0; i < numConcentricSquares; i++ )
{
for ( j = 0; j < sideLen; j++ )
( *spiralArrayPtr )[ i ][ i + j ] = currNum++;
for ( j = 1; j < sideLen; j++ )
( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;
for ( j = sideLen - 2; j > -1; j-- )
( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;
for ( j = sideLen - 2; j > 0; j-- )
( *spiralArrayPtr )[ i + j ][ i ] = currNum++;
sideLen -= 2;
}
return spiralArrayPtr;
}
void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )
{
size_t dimension = spiralArrayPtr->size();
int fieldWidth = static_cast< int >( floor( log10(
static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;
size_t col;
for ( size_t row = 0; row < dimension; row++ )
{
for ( col = 0; col < dimension; col++ )
cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];
cout << endl;
}
}
int main()
{
printSpiralArray( getSpiralArray( 5 ) );
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"fmt"
"strconv"
)
var n = 5
func main() {
if n < 1 {
return
}
top, left, bottom, right := 0, 0, n-1, n-1
sz := n * n
a := make([]int, sz)
i := 0
for left < right {
for c := left; c <= right; c++ {
a[top*n+c] = i
i++
}
top++
for r := top; r <= bottom; r++ {
a[r*n+right] = i
i++
}
right--
if top == bottom {
break
}
for c := right; c >= left; c-- {
a[bottom*n+c] = i
i++
}
bottom--
for r := bottom; r >= top; r-- {
a[r*n+left] = i
i++
}
left++
}
a[top*n+left] = i
w := len(strconv.Itoa(n*n - 1))
for i, e := range a {
fmt.Printf("%*d ", w, e)
if i%n == n-1 {
fmt.Println("")
}
}
}
| #include <vector>
#include <memory>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;
auto_ptr< IntTable > getSpiralArray( int dimension )
{
auto_ptr< IntTable > spiralArrayPtr( new IntTable(
dimension, IntRow( dimension ) ) );
int numConcentricSquares = static_cast< int >( ceil(
static_cast< double >( dimension ) / 2.0 ) );
int j;
int sideLen = dimension;
int currNum = 0;
for ( int i = 0; i < numConcentricSquares; i++ )
{
for ( j = 0; j < sideLen; j++ )
( *spiralArrayPtr )[ i ][ i + j ] = currNum++;
for ( j = 1; j < sideLen; j++ )
( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;
for ( j = sideLen - 2; j > -1; j-- )
( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;
for ( j = sideLen - 2; j > 0; j-- )
( *spiralArrayPtr )[ i + j ][ i ] = currNum++;
sideLen -= 2;
}
return spiralArrayPtr;
}
void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )
{
size_t dimension = spiralArrayPtr->size();
int fieldWidth = static_cast< int >( floor( log10(
static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;
size_t col;
for ( size_t row = 0; row < dimension; row++ )
{
for ( col = 0; col < dimension; col++ )
cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];
cout << endl;
}
}
int main()
{
printSpiralArray( getSpiralArray( 5 ) );
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | type cell string
type spec struct {
less func(cell, cell) bool
column int
reverse bool
}
func newSpec() (s spec) {
return
}
t.sort(newSpec())
s := newSpec
s.reverse = true
t.sort(s)
| #include <vector>
#include <algorithm>
#include <string>
template <class T>
struct sort_table_functor {
typedef bool (*CompFun)(const T &, const T &);
const CompFun ordering;
const int column;
const bool reverse;
sort_table_functor(CompFun o, int c, bool r) :
ordering(o), column(c), reverse(r) { }
bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {
const T &a = x[column],
&b = y[column];
return reverse ? ordering(b, a)
: ordering(a, b);
}
};
template <class T>
bool myLess(const T &x, const T &y) { return x < y; }
template <class T>
void sort_table(std::vector<std::vector<T> > &table,
int column = 0, bool reverse = false,
bool (*ordering)(const T &, const T &) = myLess) {
std::sort(table.begin(), table.end(),
sort_table_functor<T>(ordering, column, reverse));
}
#include <iostream>
template <class T>
void print_matrix(std::vector<std::vector<T> > &data) {
for () {
for (int j = 0; j < 3; j++)
std::cout << data[i][j] << "\t";
std::cout << std::endl;
}
}
bool desc_len_comparator(const std::string &x, const std::string &y) {
return x.length() > y.length();
}
int main() {
std::string data_array[3][3] =
{
{"a", "b", "c"},
{"", "q", "z"},
{"zap", "zip", "Zot"}
};
std::vector<std::vector<std::string> > data_orig;
for (int i = 0; i < 3; i++) {
std::vector<std::string> row;
for (int j = 0; j < 3; j++)
row.push_back(data_array[i][j]);
data_orig.push_back(row);
}
print_matrix(data_orig);
std::vector<std::vector<std::string> > data = data_orig;
sort_table(data);
print_matrix(data);
data = data_orig;
sort_table(data, 2);
print_matrix(data);
data = data_orig;
sort_table(data, 1);
print_matrix(data);
data = data_orig;
sort_table(data, 1, true);
print_matrix(data);
data = data_orig;
sort_table(data, 0, false, desc_len_comparator);
print_matrix(data);
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
void *bits_ptr = nullptr;
HDC dc = GetDC(GetConsoleWindow());
bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);
if (!bmp_) return false;
hdc_ = CreateCompatibleDC(dc);
SelectObject(hdc_, bmp_);
ReleaseDC(GetConsoleWindow(), dc);
width_ = w;
height_ = h;
return true;
}
void SetPenColor(DWORD clr) {
if (pen_) DeleteObject(pen_);
pen_ = CreatePen(PS_SOLID, 1, clr);
SelectObject(hdc_, pen_);
}
bool SaveBitmap(const char* path) {
HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return false;
}
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
GetObject(bmp_, sizeof(bitmap), &bitmap);
DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));
ZeroMemory(&infoheader, sizeof(BITMAPINFO));
ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));
infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);
DWORD wb;
WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);
WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);
WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);
CloseHandle(file);
delete[] dwp_bits;
return true;
}
HDC hdc() { return hdc_; }
int width() { return width_; }
int height() { return height_; }
private:
HBITMAP bmp_;
HDC hdc_;
HPEN pen_;
int width_, height_;
};
static int DistanceSqrd(const Point& point, int x, int y) {
int xd = x - point.x;
int yd = y - point.y;
return (xd * xd) + (yd * yd);
}
class Voronoi {
public:
void Make(MyBitmap* bmp, int count) {
bmp_ = bmp;
CreatePoints(count);
CreateColors();
CreateSites();
SetSitesPoints();
}
private:
void CreateSites() {
int w = bmp_->width(), h = bmp_->height(), d;
for (int hh = 0; hh < h; hh++) {
for (int ww = 0; ww < w; ww++) {
int ind = -1, dist = INT_MAX;
for (size_t it = 0; it < points_.size(); it++) {
const Point& p = points_[it];
d = DistanceSqrd(p, ww, hh);
if (d < dist) {
dist = d;
ind = it;
}
}
if (ind > -1)
SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);
else
__asm nop
}
}
}
void SetSitesPoints() {
for (const auto& point : points_) {
int x = point.x, y = point.y;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
SetPixel(bmp_->hdc(), x + i, y + j, 0);
}
}
void CreatePoints(int count) {
const int w = bmp_->width() - 20, h = bmp_->height() - 20;
for (int i = 0; i < count; i++) {
points_.push_back({ rand() % w + 10, rand() % h + 10 });
}
}
void CreateColors() {
for (size_t i = 0; i < points_.size(); i++) {
DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);
colors_.push_back(c);
}
}
vector<Point> points_;
vector<DWORD> colors_;
MyBitmap* bmp_;
};
int main(int argc, char* argv[]) {
ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
srand(GetTickCount());
MyBitmap bmp;
bmp.Create(512, 512);
bmp.SetPenColor(0);
Voronoi v;
v.Make(&bmp, 50);
BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);
bmp.SaveBitmap("v.bmp");
system("pause");
return 0;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
void *bits_ptr = nullptr;
HDC dc = GetDC(GetConsoleWindow());
bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);
if (!bmp_) return false;
hdc_ = CreateCompatibleDC(dc);
SelectObject(hdc_, bmp_);
ReleaseDC(GetConsoleWindow(), dc);
width_ = w;
height_ = h;
return true;
}
void SetPenColor(DWORD clr) {
if (pen_) DeleteObject(pen_);
pen_ = CreatePen(PS_SOLID, 1, clr);
SelectObject(hdc_, pen_);
}
bool SaveBitmap(const char* path) {
HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return false;
}
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
GetObject(bmp_, sizeof(bitmap), &bitmap);
DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD));
ZeroMemory(&infoheader, sizeof(BITMAPINFO));
ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER));
infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader);
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD);
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER);
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS);
DWORD wb;
WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);
WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);
WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);
CloseHandle(file);
delete[] dwp_bits;
return true;
}
HDC hdc() { return hdc_; }
int width() { return width_; }
int height() { return height_; }
private:
HBITMAP bmp_;
HDC hdc_;
HPEN pen_;
int width_, height_;
};
static int DistanceSqrd(const Point& point, int x, int y) {
int xd = x - point.x;
int yd = y - point.y;
return (xd * xd) + (yd * yd);
}
class Voronoi {
public:
void Make(MyBitmap* bmp, int count) {
bmp_ = bmp;
CreatePoints(count);
CreateColors();
CreateSites();
SetSitesPoints();
}
private:
void CreateSites() {
int w = bmp_->width(), h = bmp_->height(), d;
for (int hh = 0; hh < h; hh++) {
for (int ww = 0; ww < w; ww++) {
int ind = -1, dist = INT_MAX;
for (size_t it = 0; it < points_.size(); it++) {
const Point& p = points_[it];
d = DistanceSqrd(p, ww, hh);
if (d < dist) {
dist = d;
ind = it;
}
}
if (ind > -1)
SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);
else
__asm nop
}
}
}
void SetSitesPoints() {
for (const auto& point : points_) {
int x = point.x, y = point.y;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
SetPixel(bmp_->hdc(), x + i, y + j, 0);
}
}
void CreatePoints(int count) {
const int w = bmp_->width() - 20, h = bmp_->height() - 20;
for (int i = 0; i < count; i++) {
points_.push_back({ rand() % w + 10, rand() % h + 10 });
}
}
void CreateColors() {
for (size_t i = 0; i < points_.size(); i++) {
DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);
colors_.push_back(c);
}
}
vector<Point> points_;
vector<DWORD> colors_;
MyBitmap* bmp_;
};
int main(int argc, char* argv[]) {
ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
srand(GetTickCount());
MyBitmap bmp;
bmp.Create(512, 512);
bmp.SetPenColor(0);
Voronoi v;
v.Make(&bmp, 50);
BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);
bmp.SaveBitmap("v.bmp");
system("pause");
return 0;
}
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package main
import "C"
import (
"fmt"
"unsafe"
)
func main() {
go1 := "hello C"
c1 := C.CString(go1)
go1 = ""
c2 := C.strdup(c1)
C.free(unsafe.Pointer(c1))
go2 := C.GoString(c2)
C.free(unsafe.Pointer(c2))
fmt.Println(go2)
}
| FUNCTION MULTIPLY(X, Y)
DOUBLE PRECISION MULTIPLY, X, Y
|
Maintain the same structure and functionality when rewriting this code in C++. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| #include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <ctime>
template <typename T>
std::function<std::vector<T>(T)> s_of_n_creator(int n) {
std::vector<T> sample;
int i = 0;
return [=](T item) mutable {
i++;
if (i <= n) {
sample.push_back(item);
} else if (std::rand() % i < n) {
sample[std::rand() % n] = item;
}
return sample;
};
}
int main() {
std::srand(std::time(NULL));
int bin[10] = {0};
for (int trial = 0; trial < 100000; trial++) {
auto s_of_n = s_of_n_creator<int>(3);
std::vector<int> sample;
for (int i = 0; i < 10; i++)
sample = s_of_n(i);
for (int s : sample)
bin[s]++;
}
for (int x : bin)
std::cout << x << std::endl;
return 0;
}
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| #include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <ctime>
template <typename T>
std::function<std::vector<T>(T)> s_of_n_creator(int n) {
std::vector<T> sample;
int i = 0;
return [=](T item) mutable {
i++;
if (i <= n) {
sample.push_back(item);
} else if (std::rand() % i < n) {
sample[std::rand() % n] = item;
}
return sample;
};
}
int main() {
std::srand(std::time(NULL));
int bin[10] = {0};
for (int trial = 0; trial < 100000; trial++) {
auto s_of_n = s_of_n_creator<int>(3);
std::vector<int> sample;
for (int i = 0; i < 10; i++)
sample = s_of_n(i);
for (int s : sample)
bin[s]++;
}
for (int x : bin)
std::cout << x << std::endl;
return 0;
}
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package main
import (
"fmt"
"math/big"
)
func bernoulli(n uint) *big.Rat {
a := make([]big.Rat, n+1)
z := new(big.Rat)
for m := range a {
a[m].SetFrac64(1, int64(m+1))
for j := m; j >= 1; j-- {
d := &a[j-1]
d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))
}
}
if n != 1 {
return &a[0]
}
a[0].Neg(&a[0])
return &a[0]
}
func binomial(n, k int) int64 {
if n <= 0 || k <= 0 || n < k {
return 1
}
var num, den int64 = 1, 1
for i := k + 1; i <= n; i++ {
num *= int64(i)
}
for i := 2; i <= n-k; i++ {
den *= int64(i)
}
return num / den
}
func faulhaberTriangle(p int) []big.Rat {
coeffs := make([]big.Rat, p+1)
q := big.NewRat(1, int64(p)+1)
t := new(big.Rat)
u := new(big.Rat)
sign := -1
for j := range coeffs {
sign *= -1
d := &coeffs[p-j]
t.SetInt64(int64(sign))
u.SetInt64(binomial(p+1, j))
d.Mul(q, t)
d.Mul(d, u)
d.Mul(d, bernoulli(uint(j)))
}
return coeffs
}
func main() {
for i := 0; i < 10; i++ {
coeffs := faulhaberTriangle(i)
for _, coeff := range coeffs {
fmt.Printf("%5s ", coeff.RatString())
}
fmt.Println()
}
fmt.Println()
k := 17
cc := faulhaberTriangle(k)
n := int64(1000)
nn := big.NewRat(n, 1)
np := big.NewRat(1, 1)
sum := new(big.Rat)
tmp := new(big.Rat)
for _, c := range cc {
np.Mul(np, nn)
tmp.Set(np)
tmp.Mul(tmp, &c)
sum.Add(sum, tmp)
}
fmt.Println(sum.RatString())
}
| #include <exception>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
class Frac {
public:
Frac() : num(0), denom(1) {}
Frac(int n, int d) {
if (d == 0) {
throw std::runtime_error("d must not be zero");
}
int sign_of_d = d < 0 ? -1 : 1;
int g = std::gcd(n, d);
num = sign_of_d * n / g;
denom = sign_of_d * d / g;
}
Frac operator-() const {
return Frac(-num, denom);
}
Frac operator+(const Frac& rhs) const {
return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);
}
Frac operator-(const Frac& rhs) const {
return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);
}
Frac operator*(const Frac& rhs) const {
return Frac(num*rhs.num, denom*rhs.denom);
}
Frac operator*(int rhs) const {
return Frac(num * rhs, denom);
}
friend std::ostream& operator<<(std::ostream&, const Frac&);
private:
int num;
int denom;
};
std::ostream & operator<<(std::ostream & os, const Frac &f) {
if (f.num == 0 || f.denom == 1) {
return os << f.num;
}
std::stringstream ss;
ss << f.num << "/" << f.denom;
return os << ss.str();
}
Frac bernoulli(int n) {
if (n < 0) {
throw std::runtime_error("n may not be negative or zero");
}
std::vector<Frac> a;
for (int m = 0; m <= n; m++) {
a.push_back(Frac(1, m + 1));
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * j;
}
}
if (n != 1) return a[0];
return -a[0];
}
int binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw std::runtime_error("parameters are invalid");
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num *= i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom *= i;
}
return num / denom;
}
std::vector<Frac> faulhaberTraingle(int p) {
std::vector<Frac> coeffs(p + 1);
Frac q{ 1, p + 1 };
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);
}
return coeffs;
}
int main() {
for (int i = 0; i < 10; i++) {
std::vector<Frac> coeffs = faulhaberTraingle(i);
for (auto frac : coeffs) {
std::cout << std::right << std::setw(5) << frac << " ";
}
std::cout << std::endl;
}
return 0;
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| #include <iostream>
int main(int argc, char* argv[])
{
std::cout << "This program is named " << argv[0] << std::endl;
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
for (int i = 1; i < argc; ++i)
std::cout << "the argument #" << i << " is " << argv[i] << std::endl;
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| #include <iostream>
int main(int argc, char* argv[])
{
std::cout << "This program is named " << argv[0] << std::endl;
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
for (int i = 1; i < argc; ++i)
std::cout << "the argument #" << i << " is " << argv[i] << std::endl;
return 0;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
letters := "deegklnow"
wordsAll := bytes.Split(b, []byte{'\n'})
var words [][]byte
for _, word := range wordsAll {
word = bytes.TrimSpace(word)
le := len(word)
if le > 2 && le < 10 {
words = append(words, word)
}
}
var found []string
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, 'k') >= 0 {
lets := letters
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = append(found, string(word))
}
}
}
fmt.Println("The following", len(found), "words are the solutions to the puzzle:")
fmt.Println(strings.Join(found, "\n"))
mostFound := 0
var mostWords9 []string
var mostLetters []byte
var words9 [][]byte
for _, word := range words {
if len(word) == 9 {
words9 = append(words9, word)
}
}
for _, word9 := range words9 {
letterBytes := make([]byte, len(word9))
copy(letterBytes, word9)
sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })
distinctBytes := []byte{letterBytes[0]}
for _, b := range letterBytes[1:] {
if b != distinctBytes[len(distinctBytes)-1] {
distinctBytes = append(distinctBytes, b)
}
}
distinctLetters := string(distinctBytes)
for _, letter := range distinctLetters {
found := 0
letterByte := byte(letter)
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, letterByte) >= 0 {
lets := string(letterBytes)
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = found + 1
}
}
}
if found > mostFound {
mostFound = found
mostWords9 = []string{string(word9)}
mostLetters = []byte{letterByte}
} else if found == mostFound {
mostWords9 = append(mostWords9, string(word9))
mostLetters = append(mostLetters, letterByte)
}
}
}
fmt.Println("\nMost words found =", mostFound)
fmt.Println("Nine letter words producing this total:")
for i := 0; i < len(mostWords9); i++ {
fmt.Println(mostWords9[i], "with central letter", string(mostLetters[i]))
}
}
| #include <array>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
class letterset {
public:
letterset() {
count_.fill(0);
}
explicit letterset(const std::string& str) {
count_.fill(0);
for (char c : str)
add(c);
}
bool contains(const letterset& set) const {
for (size_t i = 0; i < count_.size(); ++i) {
if (set.count_[i] > count_[i])
return false;
}
return true;
}
unsigned int count(char c) const {
return count_[index(c)];
}
bool is_valid() const {
return count_[0] == 0;
}
void add(char c) {
++count_[index(c)];
}
private:
static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }
std::array<unsigned int, 27> count_;
};
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
using dictionary = std::vector<std::pair<std::string, letterset>>;
dictionary load_dictionary(const std::string& filename, int min_length,
int max_length) {
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Cannot open file " + filename);
std::string word;
dictionary result;
while (getline(in, word)) {
if (word.size() < min_length)
continue;
if (word.size() > max_length)
continue;
letterset set(word);
if (set.is_valid())
result.emplace_back(word, set);
}
return result;
}
void word_wheel(const dictionary& dict, const std::string& letters,
char central_letter) {
letterset set(letters);
if (central_letter == 0 && !letters.empty())
central_letter = letters.at(letters.size()/2);
std::map<size_t, std::vector<std::string>> words;
for (const auto& pair : dict) {
const auto& word = pair.first;
const auto& subset = pair.second;
if (subset.count(central_letter) > 0 && set.contains(subset))
words[word.size()].push_back(word);
}
size_t total = 0;
for (const auto& p : words) {
const auto& v = p.second;
auto n = v.size();
total += n;
std::cout << "Found " << n << " " << (n == 1 ? "word" : "words")
<< " of length " << p.first << ": "
<< join(v.begin(), v.end(), ", ") << '\n';
}
std::cout << "Number of words found: " << total << '\n';
}
void find_max_word_count(const dictionary& dict, int word_length) {
size_t max_count = 0;
std::vector<std::pair<std::string, char>> max_words;
for (const auto& pair : dict) {
const auto& word = pair.first;
if (word.size() != word_length)
continue;
const auto& set = pair.second;
dictionary subsets;
for (const auto& p : dict) {
if (set.contains(p.second))
subsets.push_back(p);
}
letterset done;
for (size_t index = 0; index < word_length; ++index) {
char central_letter = word[index];
if (done.count(central_letter) > 0)
continue;
done.add(central_letter);
size_t count = 0;
for (const auto& p : subsets) {
const auto& subset = p.second;
if (subset.count(central_letter) > 0)
++count;
}
if (count > max_count) {
max_words.clear();
max_count = count;
}
if (count == max_count)
max_words.emplace_back(word, central_letter);
}
}
std::cout << "Maximum word count: " << max_count << '\n';
std::cout << "Words of " << word_length << " letters producing this count:\n";
for (const auto& pair : max_words)
std::cout << pair.first << " with central letter " << pair.second << '\n';
}
constexpr const char* option_filename = "filename";
constexpr const char* option_wheel = "wheel";
constexpr const char* option_central = "central";
constexpr const char* option_min_length = "min-length";
constexpr const char* option_part2 = "part2";
int main(int argc, char** argv) {
const int word_length = 9;
int min_length = 3;
std::string letters = "ndeokgelw";
std::string filename = "unixdict.txt";
char central_letter = 0;
bool do_part2 = false;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
(option_filename, po::value<std::string>(), "name of dictionary file")
(option_wheel, po::value<std::string>(), "word wheel letters")
(option_central, po::value<char>(), "central letter (defaults to middle letter of word)")
(option_min_length, po::value<int>(), "minimum word length")
(option_part2, "include part 2");
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count(option_filename))
filename = vm[option_filename].as<std::string>();
if (vm.count(option_wheel))
letters = vm[option_wheel].as<std::string>();
if (vm.count(option_central))
central_letter = vm[option_central].as<char>();
if (vm.count(option_min_length))
min_length = vm[option_min_length].as<int>();
if (vm.count(option_part2))
do_part2 = true;
auto dict = load_dictionary(filename, min_length, word_length);
word_wheel(dict, letters, central_letter);
if (do_part2) {
std::cout << '\n';
find_max_word_count(dict, word_length);
}
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{7, 12, 60}
c := append(a, b...)
fmt.Println(c)
i := []interface{}{1, 2, 3}
j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
k := append(i, j...)
fmt.Println(k)
l := [...]int{1, 2, 3}
m := [...]int{7, 12, 60}
var n [len(l) + len(m)]int
copy(n[:], l[:])
copy(n[len(l):], m[:])
fmt.Println(n)
}
| #include <vector>
#include <iostream>
int main()
{
std::vector<int> a(3), b(4);
a[0] = 11; a[1] = 12; a[2] = 13;
b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;
a.insert(a.end(), b.begin(), b.end());
for (int i = 0; i < a.size(); ++i)
std::cout << "a[" << i << "] = " << a[i] << "\n";
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
}
| #include <iostream>
#include <string>
using namespace std;
int main()
{
long int integer_input;
string string_input;
cout << "Enter an integer: ";
cin >> integer_input;
cout << "Enter a string: ";
cin >> string_input;
return 0;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
}
| #include <iostream>
#include <string>
using namespace std;
int main()
{
long int integer_input;
string string_input;
cout << "Enter an integer: ";
cin >> integer_input;
cout << "Enter a string: ";
cin >> string_input;
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
| #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
{
std::cout << "Error opening MIDI Output..." << std::endl;
device = 0;
}
}
~midi()
{
midiOutReset( device );
midiOutClose( device );
}
bool isOpen() { return device != 0; }
void setInstrument( byte i )
{
message.data[0] = 0xc0; message.data[1] = i;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void playNote( byte n, unsigned i )
{
playNote( n ); Sleep( i ); stopNote( n );
}
private:
void playNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 127; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void stopNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
HMIDIOUT device;
midi_msg message;
};
int main( int argc, char* argv[] )
{
midi m;
if( m.isOpen() )
{
byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
m.setInstrument( 42 );
for( int x = 0; x < 8; x++ )
m.playNote( notes[x], rand() % 100 + 158 );
Sleep( 1000 );
}
return 0;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
| #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
{
std::cout << "Error opening MIDI Output..." << std::endl;
device = 0;
}
}
~midi()
{
midiOutReset( device );
midiOutClose( device );
}
bool isOpen() { return device != 0; }
void setInstrument( byte i )
{
message.data[0] = 0xc0; message.data[1] = i;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void playNote( byte n, unsigned i )
{
playNote( n ); Sleep( i ); stopNote( n );
}
private:
void playNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 127; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void stopNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
HMIDIOUT device;
midi_msg message;
};
int main( int argc, char* argv[] )
{
midi m;
if( m.isOpen() )
{
byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
m.setInstrument( 42 );
for( int x = 0; x < 8; x++ )
m.playNote( notes[x], rand() % 100 + 158 );
Sleep( 1000 );
}
return 0;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import "fmt"
type item struct {
string
w, v int
}
var wants = []item{
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
}
const maxWt = 400
func main() {
items, w, v := m(len(wants)-1, maxWt)
fmt.Println(items)
fmt.Println("weight:", w)
fmt.Println("value:", v)
}
func m(i, w int) ([]string, int, int) {
if i < 0 || w == 0 {
return nil, 0, 0
} else if wants[i].w > w {
return m(i-1, w)
}
i0, w0, v0 := m(i-1, w)
i1, w1, v1 := m(i-1, w-wants[i].w)
v1 += wants[i].v
if v1 > v0 {
return append(i1, wants[i].string), w1 + wants[i].w, v1
}
return i0, w0, v0
}
| #include <vector>
#include <string>
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <set>
int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & ,
std::set<int> & , const int ) ;
int main( ) {
std::vector<boost::tuple<std::string , int , int> > items ;
items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ;
items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ;
items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ;
items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ;
items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ;
items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ;
items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ;
items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ;
items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ;
items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ;
items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ;
items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ;
items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ;
items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ;
items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ;
items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ;
items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ;
items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ;
items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ;
items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ;
items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ;
items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ;
items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ;
const int maximumWeight = 400 ;
std::set<int> bestItems ;
int bestValue = findBestPack( items , bestItems , maximumWeight ) ;
std::cout << "The best value that can be packed in the given knapsack is " <<
bestValue << " !\n" ;
int totalweight = 0 ;
std::cout << "The following items should be packed in the knapsack:\n" ;
for ( std::set<int>::const_iterator si = bestItems.begin( ) ;
si != bestItems.end( ) ; si++ ) {
std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ;
totalweight += (items.begin( ) + *si)->get<1>( ) ;
}
std::cout << "The total weight of all items is " << totalweight << " !\n" ;
return 0 ;
}
int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {
const int n = items.size( ) ;
int bestValues [ n ][ weightlimit ] ;
std::set<int> solutionSets[ n ][ weightlimit ] ;
std::set<int> emptyset ;
for ( int i = 0 ; i < n ; i++ ) {
for ( int j = 0 ; j < weightlimit ; j++ ) {
bestValues[ i ][ j ] = 0 ;
solutionSets[ i ][ j ] = emptyset ;
}
}
for ( int i = 0 ; i < n ; i++ ) {
for ( int weight = 0 ; weight < weightlimit ; weight++ ) {
if ( i == 0 )
bestValues[ i ][ weight ] = 0 ;
else {
int itemweight = (items.begin( ) + i)->get<1>( ) ;
if ( weight < itemweight ) {
bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
} else {
if ( bestValues[ i - 1 ][ weight - itemweight ] +
(items.begin( ) + i)->get<2>( ) >
bestValues[ i - 1 ][ weight ] ) {
bestValues[ i ][ weight ] =
bestValues[ i - 1 ][ weight - itemweight ] +
(items.begin( ) + i)->get<2>( ) ;
solutionSets[ i ][ weight ] =
solutionSets[ i - 1 ][ weight - itemweight ] ;
solutionSets[ i ][ weight ].insert( i ) ;
}
else {
bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
}
}
}
}
}
bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;
return bestValues[ n - 1 ][ weightlimit - 1 ] ;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import (
"fmt"
"sort"
)
func getPrimes(max int) []int {
if max < 2 {
return []int{}
}
lprimes := []int{2}
outer:
for x := 3; x <= max; x += 2 {
for _, p := range lprimes {
if x%p == 0 {
continue outer
}
}
lprimes = append(lprimes, x)
}
return lprimes
}
func main() {
const maxSum = 99
descendants := make([][]int64, maxSum+1)
ancestors := make([][]int, maxSum+1)
for i := 0; i <= maxSum; i++ {
descendants[i] = []int64{}
ancestors[i] = []int{}
}
primes := getPrimes(maxSum)
for _, p := range primes {
descendants[p] = append(descendants[p], int64(p))
for s := 1; s < len(descendants)-p; s++ {
temp := make([]int64, len(descendants[s]))
for i := 0; i < len(descendants[s]); i++ {
temp[i] = int64(p) * descendants[s][i]
}
descendants[s+p] = append(descendants[s+p], temp...)
}
}
for _, p := range append(primes, 4) {
le := len(descendants[p])
if le == 0 {
continue
}
descendants[p][le-1] = 0
descendants[p] = descendants[p][:le-1]
}
total := 0
for s := 1; s <= maxSum; s++ {
x := descendants[s]
sort.Slice(x, func(i, j int) bool {
return x[i] < x[j]
})
total += len(descendants[s])
index := 0
for ; index < len(descendants[s]); index++ {
if descendants[s][index] > int64(maxSum) {
break
}
}
for _, d := range descendants[s][:index] {
ancestors[d] = append(ancestors[s], s)
}
if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {
continue
}
temp := fmt.Sprintf("%v", ancestors[s])
fmt.Printf("%2d: %d Ancestor(s): %-14s", s, len(ancestors[s]), temp)
le := len(descendants[s])
if le <= 10 {
fmt.Printf("%5d Descendant(s): %v\n", le, descendants[s])
} else {
fmt.Printf("%5d Descendant(s): %v\b ...]\n", le, descendants[s][:10])
}
}
fmt.Println("\nTotal descendants", total)
}
| #include <algorithm>
#include <iostream>
#include <vector>
typedef unsigned long long integer;
std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {
std::vector<integer> result;
for (integer a = ancestor[n]; a != 0 && a != n; ) {
n = a;
a = ancestor[n];
result.push_back(n);
}
return result;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty()) {
std::cout << "none\n";
return;
}
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
for (integer p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
const size_t limit = 100;
std::vector<integer> ancestor(limit, 0);
std::vector<std::vector<integer>> descendants(limit);
for (size_t prime = 0; prime < limit; ++prime) {
if (!is_prime(prime))
continue;
descendants[prime].push_back(prime);
for (size_t i = 0; i + prime < limit; ++i) {
integer s = i + prime;
for (integer n : descendants[i]) {
integer prod = n * prime;
descendants[s].push_back(prod);
if (prod < limit)
ancestor[prod] = s;
}
}
}
size_t total_descendants = 0;
for (integer i = 1; i < limit; ++i) {
std::vector<integer> ancestors(get_ancestors(ancestor, i));
std::cout << "[" << i << "] Level: " << ancestors.size() << '\n';
std::cout << "Ancestors: ";
std::sort(ancestors.begin(), ancestors.end());
print_vector(ancestors);
std::cout << "Descendants: ";
std::vector<integer>& desc = descendants[i];
if (!desc.empty()) {
std::sort(desc.begin(), desc.end());
if (desc[0] == i)
desc.erase(desc.begin());
}
std::cout << desc.size() << '\n';
total_descendants += desc.size();
if (!desc.empty())
print_vector(desc);
std::cout << '\n';
}
std::cout << "Total descendants: " << total_descendants << '\n';
return 0;
}
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
| #include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector<std::vector<int>>& v) {
std::cout << "{ ";
for (const auto& p : v) {
std::cout << "(";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << ") ";
}
std::cout << "}" << std::endl;
}
auto product(const std::vector<std::vector<int>>& lists) {
std::vector<std::vector<int>> result;
if (std::find_if(std::begin(lists), std::end(lists),
[](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
return result;
}
for (auto& e : lists[0]) {
result.push_back({ e });
}
for (size_t i = 1; i < lists.size(); ++i) {
std::vector<std::vector<int>> temp;
for (auto& e : result) {
for (auto f : lists[i]) {
auto e_tmp = e;
e_tmp.push_back(f);
temp.push_back(e_tmp);
}
}
result = temp;
}
return result;
}
int main() {
std::vector<std::vector<int>> prods[] = {
{ { 1, 2 }, { 3, 4 } },
{ { 3, 4 }, { 1, 2} },
{ { 1, 2 }, { } },
{ { }, { 1, 2 } },
{ { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
{ { 1, 2, 3 }, { 30 }, { 500, 100 } },
{ { 1, 2, 3 }, { }, { 500, 100 } }
};
for (const auto& p : prods) {
print(product(p));
}
std::cin.ignore();
std::cin.get();
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
| #include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector<std::vector<int>>& v) {
std::cout << "{ ";
for (const auto& p : v) {
std::cout << "(";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << ") ";
}
std::cout << "}" << std::endl;
}
auto product(const std::vector<std::vector<int>>& lists) {
std::vector<std::vector<int>> result;
if (std::find_if(std::begin(lists), std::end(lists),
[](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
return result;
}
for (auto& e : lists[0]) {
result.push_back({ e });
}
for (size_t i = 1; i < lists.size(); ++i) {
std::vector<std::vector<int>> temp;
for (auto& e : result) {
for (auto f : lists[i]) {
auto e_tmp = e;
e_tmp.push_back(f);
temp.push_back(e_tmp);
}
}
result = temp;
}
return result;
}
int main() {
std::vector<std::vector<int>> prods[] = {
{ { 1, 2 }, { 3, 4 } },
{ { 3, 4 }, { 1, 2} },
{ { 1, 2 }, { } },
{ { }, { 1, 2 } },
{ { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
{ { 1, 2, 3 }, { 30 }, { 500, 100 } },
{ { 1, 2, 3 }, { }, { 500, 100 } }
};
for (const auto& p : prods) {
print(product(p));
}
std::cin.ignore();
std::cin.get();
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import "math"
import "fmt"
func cube(x float64) float64 { return math.Pow(x, 3) }
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
funclist := []ffType{math.Sin, math.Cos, cube}
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}
| #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;
typedef function<double(double)> FunType;
vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
int main() {
vector<FunType> composedFuns;
auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};
transform(B.begin(), B.end(),
A.begin(),
back_inserter(composedFuns),
compose<double, double, double>);
for (auto num: exNums)
for (auto fun: composedFuns)
cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;
return 0;
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import "math"
import "fmt"
func cube(x float64) float64 { return math.Pow(x, 3) }
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
funclist := []ffType{math.Sin, math.Cos, cube}
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}
| #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;
typedef function<double(double)> FunType;
vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
int main() {
vector<FunType> composedFuns;
auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};
transform(B.begin(), B.end(),
A.begin(),
back_inserter(composedFuns),
compose<double, double, double>);
for (auto num: exNums)
for (auto fun: composedFuns)
cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;
return 0;
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"fmt"
"strconv"
)
func listProperDivisors(limit int) {
if limit < 1 {
return
}
width := len(strconv.Itoa(limit))
for i := 1; i <= limit; i++ {
fmt.Printf("%*d -> ", width, i)
if i == 1 {
fmt.Println("(None)")
continue
}
for j := 1; j <= i/2; j++ {
if i%j == 0 {
fmt.Printf(" %d", j)
}
}
fmt.Println()
}
}
func countProperDivisors(n int) int {
if n < 2 {
return 0
}
count := 0
for i := 1; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
fmt.Println()
maxCount := 0
most := []int{1}
for n := 2; n <= 20000; n++ {
count := countProperDivisors(n)
if count == maxCount {
most = append(most, n)
} else if count > maxCount {
maxCount = count
most = most[0:1]
most[0] = n
}
}
fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
fmt.Println("namely", maxCount, "\b\n")
for _, n := range most {
fmt.Println(n)
}
}
| #include <vector>
#include <iostream>
#include <algorithm>
std::vector<int> properDivisors ( int number ) {
std::vector<int> divisors ;
for ( int i = 1 ; i < number / 2 + 1 ; i++ )
if ( number % i == 0 )
divisors.push_back( i ) ;
return divisors ;
}
int main( ) {
std::vector<int> divisors ;
unsigned int maxdivisors = 0 ;
int corresponding_number = 0 ;
for ( int i = 1 ; i < 11 ; i++ ) {
divisors = properDivisors ( i ) ;
std::cout << "Proper divisors of " << i << ":\n" ;
for ( int number : divisors ) {
std::cout << number << " " ;
}
std::cout << std::endl ;
divisors.clear( ) ;
}
for ( int i = 11 ; i < 20001 ; i++ ) {
divisors = properDivisors ( i ) ;
if ( divisors.size( ) > maxdivisors ) {
maxdivisors = divisors.size( ) ;
corresponding_number = i ;
}
divisors.clear( ) ;
}
std::cout << "Most divisors has " << corresponding_number <<
" , it has " << maxdivisors << " divisors!\n" ;
return 0 ;
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import (
"encoding/xml"
"fmt"
)
func xRemarks(r CharacterRemarks) (string, error) {
b, err := xml.MarshalIndent(r, "", " ")
return string(b), err
}
type CharacterRemarks struct {
Character []crm
}
type crm struct {
Name string `xml:"name,attr"`
Remark string `xml:",chardata"`
}
func main() {
x, err := xRemarks(CharacterRemarks{[]crm{
{`April`, `Bubbly: I'm > Tam and <= Emily`},
{`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
{`Emily`, `Short & shrift`},
}})
if err != nil {
x = err.Error()
}
fmt.Println(x)
}
| #include <vector>
#include <utility>
#include <iostream>
#include <boost/algorithm/string.hpp>
std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;
int main( ) {
std::vector<std::string> names , remarks ;
names.push_back( "April" ) ;
names.push_back( "Tam O'Shantor" ) ;
names.push_back ( "Emily" ) ;
remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ;
remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ;
remarks.push_back( "Short & shrift" ) ;
std::cout << "This is in XML:\n" ;
std::cout << create_xml( names , remarks ) << std::endl ;
return 0 ;
}
std::string create_xml( std::vector<std::string> & names ,
std::vector<std::string> & remarks ) {
std::vector<std::pair<std::string , std::string> > entities ;
entities.push_back( std::make_pair( "&" , "&" ) ) ;
entities.push_back( std::make_pair( "<" , "<" ) ) ;
entities.push_back( std::make_pair( ">" , ">" ) ) ;
std::string xmlstring ( "<CharacterRemarks>\n" ) ;
std::vector<std::string>::iterator vsi = names.begin( ) ;
typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;
for ( ; vsi != names.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( int i = 0 ; i < names.size( ) ; i++ ) {
xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">")
.append( remarks[ i ] ).append( "</Character>\n" ) ;
}
xmlstring.append( "</CharacterRemarks>" ) ;
return xmlstring ;
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"encoding/xml"
"fmt"
)
func xRemarks(r CharacterRemarks) (string, error) {
b, err := xml.MarshalIndent(r, "", " ")
return string(b), err
}
type CharacterRemarks struct {
Character []crm
}
type crm struct {
Name string `xml:"name,attr"`
Remark string `xml:",chardata"`
}
func main() {
x, err := xRemarks(CharacterRemarks{[]crm{
{`April`, `Bubbly: I'm > Tam and <= Emily`},
{`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
{`Emily`, `Short & shrift`},
}})
if err != nil {
x = err.Error()
}
fmt.Println(x)
}
| #include <vector>
#include <utility>
#include <iostream>
#include <boost/algorithm/string.hpp>
std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;
int main( ) {
std::vector<std::string> names , remarks ;
names.push_back( "April" ) ;
names.push_back( "Tam O'Shantor" ) ;
names.push_back ( "Emily" ) ;
remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ;
remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ;
remarks.push_back( "Short & shrift" ) ;
std::cout << "This is in XML:\n" ;
std::cout << create_xml( names , remarks ) << std::endl ;
return 0 ;
}
std::string create_xml( std::vector<std::string> & names ,
std::vector<std::string> & remarks ) {
std::vector<std::pair<std::string , std::string> > entities ;
entities.push_back( std::make_pair( "&" , "&" ) ) ;
entities.push_back( std::make_pair( "<" , "<" ) ) ;
entities.push_back( std::make_pair( ">" , ">" ) ) ;
std::string xmlstring ( "<CharacterRemarks>\n" ) ;
std::vector<std::string>::iterator vsi = names.begin( ) ;
typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;
for ( ; vsi != names.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( int i = 0 ; i < names.size( ) ; i++ ) {
xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">")
.append( remarks[ i ] ).append( "</Character>\n" ) ;
}
xmlstring.append( "</CharacterRemarks>" ) ;
return xmlstring ;
}
|
Produce a functionally identical C++ code for the snippet given in Go. | package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| #include <windows.h>
#include <string>
#include <vector>
using namespace std;
const int HSTEP = 46, MWID = 40, MHEI = 471;
const float VSTEP = 2.3f;
class vector2
{
public:
vector2() { x = y = 0; }
vector2( float a, float b ) { x = a; y = b; }
void set( float a, float b ) { x = a; y = b; }
float x, y;
};
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class plot
{
public:
plot() { bmp.create( 512, 512 ); }
void draw( vector<vector2>* pairs )
{
bmp.clear( 0xff );
drawGraph( pairs );
plotIt( pairs );
HDC dc = GetDC( GetConsoleWindow() );
BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( GetConsoleWindow(), dc );
}
private:
void drawGraph( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
bmp.setPenColor( RGB( 240, 240, 240 ) );
DWORD b = 11, c = 40, x;
RECT rc; char txt[8];
for( x = 0; x < pairs->size(); x++ )
{
MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );
MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );
wsprintf( txt, "%d", ( pairs->size() - x ) * 20 );
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
wsprintf( txt, "%d", x );
SetRect( &rc, c - 8, 472, c + 8, 492 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
c += 46; b += 46;
}
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
bmp.setPenColor( 0 ); bmp.setPenWidth( 3 );
MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );
MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );
}
void plotIt( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
HBRUSH br = CreateSolidBrush( 255 );
RECT rc;
bmp.setPenColor( 255 ); bmp.setPenWidth( 2 );
vector<vector2>::iterator it = pairs->begin();
int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
MoveToEx( dc, a, b, NULL );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );
it++;
for( ; it < pairs->end(); it++ )
{
a = MWID + HSTEP * static_cast<int>( ( *it ).x );
b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );
FillRect( dc, &rc, br ); LineTo( dc, a, b );
}
DeleteObject( br );
}
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
plot pt;
vector<vector2> pairs;
pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );
pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );
pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );
pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );
pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );
pt.draw( &pairs );
system( "pause" );
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| #include <windows.h>
#include <string>
#include <vector>
using namespace std;
const int HSTEP = 46, MWID = 40, MHEI = 471;
const float VSTEP = 2.3f;
class vector2
{
public:
vector2() { x = y = 0; }
vector2( float a, float b ) { x = a; y = b; }
void set( float a, float b ) { x = a; y = b; }
float x, y;
};
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class plot
{
public:
plot() { bmp.create( 512, 512 ); }
void draw( vector<vector2>* pairs )
{
bmp.clear( 0xff );
drawGraph( pairs );
plotIt( pairs );
HDC dc = GetDC( GetConsoleWindow() );
BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( GetConsoleWindow(), dc );
}
private:
void drawGraph( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
bmp.setPenColor( RGB( 240, 240, 240 ) );
DWORD b = 11, c = 40, x;
RECT rc; char txt[8];
for( x = 0; x < pairs->size(); x++ )
{
MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );
MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );
wsprintf( txt, "%d", ( pairs->size() - x ) * 20 );
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
wsprintf( txt, "%d", x );
SetRect( &rc, c - 8, 472, c + 8, 492 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
c += 46; b += 46;
}
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
bmp.setPenColor( 0 ); bmp.setPenWidth( 3 );
MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );
MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );
}
void plotIt( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
HBRUSH br = CreateSolidBrush( 255 );
RECT rc;
bmp.setPenColor( 255 ); bmp.setPenWidth( 2 );
vector<vector2>::iterator it = pairs->begin();
int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
MoveToEx( dc, a, b, NULL );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );
it++;
for( ; it < pairs->end(); it++ )
{
a = MWID + HSTEP * static_cast<int>( ( *it ).x );
b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );
FillRect( dc, &rc, br ); LineTo( dc, a, b );
}
DeleteObject( br );
}
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
plot pt;
vector<vector2> pairs;
pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );
pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );
pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );
pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );
pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );
pt.draw( &pairs );
system( "pause" );
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
}
| #include <iostream>
#include <string>
#include <iterator>
#include <regex>
int main()
{
std::regex re(".* string$");
std::string s = "Hi, I am a string";
if (std::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
std::regex re2(" a.*a");
std::smatch match;
if (std::regex_search(s, match, re2))
{
std::cout << "Matched " << match.length()
<< " characters starting at " << match.position() << ".\n";
std::cout << "Matched character sequence: \""
<< match.str() << "\"\n";
}
else
{
std::cout << "Oops - not found?\n";
}
std::string dest_string;
std::regex_replace(std::back_inserter(dest_string),
s.begin(), s.end(),
re2,
"'m now a changed");
std::cout << dest_string << std::endl;
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
"sort"
)
func main() {
lower, upper := 0, 100
fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
answer := sort.Search(upper-lower, func (i int) bool {
fmt.Printf("Is your number less than or equal to %d? ", lower+i)
s := ""
fmt.Scanf("%s", &s)
return s != "" && s[0] == 'y'
})
fmt.Printf("Your number is %d.\n", lower+answer)
}
| #include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {
int i;
GuessNumberIterator() { }
GuessNumberIterator(int _i) : i(_i) { }
GuessNumberIterator& operator++() { ++i; return *this; }
GuessNumberIterator operator++(int) {
GuessNumberIterator tmp = *this; ++(*this); return tmp; }
bool operator==(const GuessNumberIterator& y) { return i == y.i; }
bool operator!=(const GuessNumberIterator& y) { return i != y.i; }
int operator*() {
std::cout << "Is your number less than or equal to " << i << "? ";
std::string s;
std::cin >> s;
return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;
}
GuessNumberIterator& operator--() { --i; return *this; }
GuessNumberIterator operator--(int) {
GuessNumberIterator tmp = *this; --(*this); return tmp; }
GuessNumberIterator& operator+=(int n) { i += n; return *this; }
GuessNumberIterator& operator-=(int n) { i -= n; return *this; }
GuessNumberIterator operator+(int n) {
GuessNumberIterator tmp = *this; return tmp += n; }
GuessNumberIterator operator-(int n) {
GuessNumberIterator tmp = *this; return tmp -= n; }
int operator-(const GuessNumberIterator &y) { return i - y.i; }
int operator[](int n) { return *(*this + n); }
bool operator<(const GuessNumberIterator &y) { return i < y.i; }
bool operator>(const GuessNumberIterator &y) { return i > y.i; }
bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }
bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }
};
inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }
const int lower = 0;
const int upper = 100;
int main() {
std::cout << "Instructions:\n"
<< "Think of integer number from " << lower << " (inclusive) to "
<< upper << " (exclusive) and\n"
<< "I will guess it. After each guess, I will ask you if it is less than\n"
<< "or equal to some number, and you will respond with \"yes\" or \"no\".\n";
int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;
std::cout << "Your number is " << answer << ".\n";
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}
| #include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "a", "b", "c" };
std::unordered_map<std::string, std::string> hash;
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
x2 := x + distance*math.Sin(direction*math.Pi/180)
y2 := y - distance*math.Cos(direction*math.Pi/180)
g.AaLine(x, y, x2, y2)
if depth > 0 {
ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
}
}
| #include <windows.h>
#include <string>
#include <math.h>
using namespace std;
const float PI = 3.1415926536f;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
void *pBits;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD* dwpBits;
DWORD wb;
HANDLE file;
GetObject( bmp, sizeof( bitmap ), &bitmap );
dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() { return hdc; }
int getWidth() { return width; }
int getHeight() { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
int width, height;
};
class vector2
{
public:
vector2() { x = y = 0; }
vector2( int a, int b ) { x = a; y = b; }
void set( int a, int b ) { x = a; y = b; }
void rotate( float angle_r )
{
float _x = static_cast<float>( x ),
_y = static_cast<float>( y ),
s = sinf( angle_r ),
c = cosf( angle_r ),
a = _x * c - _y * s,
b = _x * s + _y * c;
x = static_cast<int>( a );
y = static_cast<int>( b );
}
int x, y;
};
class fractalTree
{
public:
fractalTree() { _ang = DegToRadian( 24.0f ); }
float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }
void create( myBitmap* bmp )
{
_bmp = bmp;
float line_len = 130.0f;
vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );
MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );
sp.y -= static_cast<int>( line_len );
LineTo( _bmp->getDC(), sp.x, sp.y);
drawRL( &sp, line_len, 0, true );
drawRL( &sp, line_len, 0, false );
}
private:
void drawRL( vector2* sp, float line_len, float a, bool rg )
{
line_len *= .75f;
if( line_len < 2.0f ) return;
MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );
vector2 r( 0, static_cast<int>( line_len ) );
if( rg ) a -= _ang;
else a += _ang;
r.rotate( a );
r.x += sp->x; r.y = sp->y - r.y;
LineTo( _bmp->getDC(), r.x, r.y );
drawRL( &r, line_len, a, true );
drawRL( &r, line_len, a, false );
}
myBitmap* _bmp;
float _ang;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
myBitmap bmp;
bmp.create( 640, 512 );
bmp.setPenColor( RGB( 255, 255, 0 ) );
fractalTree tree;
tree.create( &bmp );
BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );
bmp.saveBitmap( "f:
system( "pause" );
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import "github.com/fogleman/gg"
var palette = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 4
for b := 1; b <= 4; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%8])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(900, 600)
pinstripe(dc)
dc.SavePNG("color_pinstripe.png")
}
| #include <windows.h>
class pinstripe
{
public:
pinstripe() { createColors(); }
void setDimensions( int x, int y ) { _mw = x; _mh = y; }
void createColors()
{
colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );
colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 );
colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 );
colors[7] = RGB( 255, 255, 255 );
}
void draw( HDC dc )
{
HPEN pen;
int lh = _mh / 4, row, cp;
for( int lw = 1; lw < 5; lw++ )
{
cp = 0;
row = ( lw - 1 ) * lh;
for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )
{
pen = CreatePen( PS_SOLID, lw, colors[cp] );
++cp %= 8;
SelectObject( dc, pen );
MoveToEx( dc, x, row, NULL );
LineTo( dc, x, row + lh );
DeleteObject( pen );
}
}
}
private:
int _mw, _mh;
DWORD colors[8];
};
pinstripe pin;
void PaintWnd( HWND hWnd )
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint( hWnd, &ps );
pin.draw( hdc );
EndPaint( hWnd, &ps );
}
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_PAINT: PaintWnd( hWnd ); break;
default:
return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_CLR_PS_";
RegisterClassEx( &wcex );
return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );
}
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
srand( GetTickCount() );
HWND hwnd = InitAll( hInstance );
if( !hwnd ) return -1;
int mw = GetSystemMetrics( SM_CXSCREEN ),
mh = GetSystemMetrics( SM_CYSCREEN );
pin.setDimensions( mw, mh );
RECT rc = { 0, 0, mw, mh };
AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );
int w = rc.right - rc.left,
h = rc.bottom - rc.top;
int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),
posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );
SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );
ShowWindow( hwnd, nCmdShow );
UpdateWindow( hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_CLR_PS_", hInstance );
}
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| #include <iostream>
#include <cstdint>
struct Date {
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
};
constexpr bool leap(int year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const std::string& weekday(const Date& date) {
static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const std::string days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"
};
unsigned const c = date.year/100, r = date.year%100;
unsigned const s = r/12, t = r%12;
unsigned const c_anchor = (5 * (c%4) + 2) % 7;
unsigned const doom = (s + t + t/4 + c_anchor) % 7;
unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const std::string months[] = {"",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
for (const Date& d : dates) {
std::cout << months[d.month] << " " << (int)d.day << ", " << d.year;
std::cout << (d.year > 2021 ? " will be " : " was ");
std::cout << "on a " << weekday(d) << std::endl;
}
return 0;
}
|
Write a version of this Go function in C++ with identical behavior. | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| #include <iostream>
#include <cstdint>
struct Date {
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
};
constexpr bool leap(int year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const std::string& weekday(const Date& date) {
static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const std::string days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"
};
unsigned const c = date.year/100, r = date.year%100;
unsigned const s = r/12, t = r%12;
unsigned const c_anchor = (5 * (c%4) + 2) % 7;
unsigned const doom = (s + t + t/4 + c_anchor) % 7;
unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const std::string months[] = {"",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
for (const Date& d : dates) {
std::cout << months[d.month] << " " << (int)d.day << ", " << d.year;
std::cout << (d.year > 2021 ? " will be " : " was ");
std::cout << "on a " << weekday(d) << std::endl;
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"fmt"
"math/rand"
"time"
)
func cocktailShakerSort(a []int) {
var begin = 0
var end = len(a) - 2
for begin <= end {
newBegin := end
newEnd := begin
for i := begin; i <= end; i++ {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newEnd = i
}
}
end = newEnd - 1
for i := end; i >= begin; i-- {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newBegin = i
}
}
begin = newBegin + 1
}
}
func cocktailSort(a []int) {
last := len(a) - 1
for {
swapped := false
for i := 0; i < last; i++ {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
swapped = false
for i := last - 1; i >= 0; i-- {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
}
}
func main() {
a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}
fmt.Println("Original array:", a)
b := make([]int, len(a))
copy(b, a)
cocktailSort(a)
fmt.Println("Cocktail sort :", a)
cocktailShakerSort(b)
fmt.Println("C/Shaker sort :", b)
rand.Seed(time.Now().UnixNano())
fmt.Println("\nRelative speed of the two sorts")
fmt.Println(" N x faster (CSS v CS)")
fmt.Println("----- -------------------")
const runs = 10
for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {
sum := 0.0
for i := 1; i <= runs; i++ {
nums := make([]int, n)
for i := 0; i < n; i++ {
rn := rand.Intn(100000)
if i%2 == 1 {
rn = -rn
}
nums[i] = rn
}
nums2 := make([]int, n)
copy(nums2, nums)
start := time.Now()
cocktailSort(nums)
elapsed := time.Since(start)
start2 := time.Now()
cocktailShakerSort(nums2)
elapsed2 := time.Since(start2)
sum += float64(elapsed) / float64(elapsed2)
}
fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs)
}
}
| #include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
template <typename iterator>
void cocktail_shaker_sort(iterator begin, iterator end) {
if (begin == end)
return;
for (--end; begin < end; ) {
iterator new_begin = end;
iterator new_end = begin;
for (iterator i = begin; i < end; ++i) {
iterator j = i + 1;
if (*j < *i) {
std::iter_swap(i, j);
new_end = i;
}
}
end = new_end;
for (iterator i = end; i > begin; --i) {
iterator j = i - 1;
if (*i < *j) {
std::iter_swap(i, j);
new_begin = i;
}
}
begin = new_begin;
}
}
template <typename iterator>
void print(iterator begin, iterator end) {
if (begin == end)
return;
std::cout << *begin++;
while (begin != end)
std::cout << ' ' << *begin++;
std::cout << '\n';
}
int main() {
std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};
std::cout << "before: ";
print(v.begin(), v.end());
cocktail_shaker_sort(v.begin(), v.end());
assert(std::is_sorted(v.begin(), v.end()));
std::cout << "after: ";
print(v.begin(), v.end());
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/math"
"github.com/google/gxui/themes/dark"
omath "math"
"time"
)
const (
ANIMATION_WIDTH int = 480
ANIMATION_HEIGHT int = 320
BALL_RADIUS float32 = 25.0
METER_PER_PIXEL float64 = 1.0 / 20.0
PHI_ZERO float64 = omath.Pi * 0.5
)
var (
l float64 = float64(ANIMATION_HEIGHT) * 0.5
freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))
)
type Pendulum interface {
GetPhi() float64
}
type mathematicalPendulum struct {
start time.Time
}
func (p *mathematicalPendulum) GetPhi() float64 {
if (p.start == time.Time{}) {
p.start = time.Now()
}
t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)
return PHI_ZERO * omath.Cos(t*freq)
}
type numericalPendulum struct {
currentPhi float64
angAcc float64
angVel float64
lastTime time.Time
}
func (p *numericalPendulum) GetPhi() float64 {
dt := 0.0
if (p.lastTime != time.Time{}) {
dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)
}
p.lastTime = time.Now()
p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)
p.angVel += p.angAcc * dt
p.currentPhi += p.angVel * dt
return p.currentPhi
}
func draw(p Pendulum, canvas gxui.Canvas, x, y int) {
attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}
phi := p.GetPhi()
ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}
line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}
canvas.DrawLines(line, gxui.DefaultPen)
m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}
rect := math.Rect{ball.Sub(m), ball.Add(m)}
canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))
}
func appMain(driver gxui.Driver) {
theme := dark.CreateTheme(driver)
window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum")
window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))
image := theme.CreateImage()
ticker := time.NewTicker(time.Millisecond * 15)
pendulum := &mathematicalPendulum{}
pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}
go func() {
for _ = range ticker.C {
canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})
canvas.Clear(gxui.White)
draw(pendulum, canvas, 0, 0)
draw(pendulum2, canvas, 0, ANIMATION_HEIGHT)
canvas.Complete()
driver.Call(func() {
image.SetCanvas(canvas)
})
}
}()
window.AddChild(image)
window.OnClose(ticker.Stop)
window.OnClose(driver.Terminate)
}
func main() {
gl.StartDriver(appMain)
}
| #ifndef __wxPendulumDlg_h__
#define __wxPendulumDlg_h__
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/dialog.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/timer.h>
#include <wx/dcbuffer.h>
#include <cmath>
class wxPendulumDlgApp : public wxApp
{
public:
bool OnInit();
int OnExit();
};
class wxPendulumDlg : public wxDialog
{
public:
wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);
virtual ~wxPendulumDlg();
void wxPendulumDlgPaint(wxPaintEvent& event);
void wxPendulumDlgSize(wxSizeEvent& event);
void OnTimer(wxTimerEvent& event);
private:
wxTimer *m_timer;
unsigned int m_uiLength;
double m_Angle;
double m_AngleVelocity;
enum wxIDs
{
ID_WXTIMER1 = 1001,
ID_DUMMY_VALUE_
};
void OnClose(wxCloseEvent& event);
void CreateGUIControls();
DECLARE_EVENT_TABLE()
};
#endif
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>
uint32_t gray_encode(uint32_t b)
{
return b ^ (b >> 1);
}
uint32_t gray_decode(uint32_t g)
{
for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
{
if (g & bit) g ^= bit >> 1;
}
return g;
}
std::string to_binary(int value)
{
const std::bitset<32> bs(value);
const std::string str(bs.to_string());
const size_t pos(str.find('1'));
return pos == std::string::npos ? "0" : str.substr(pos);
}
int main()
{
std::cout << "Number\tBinary\tGray\tDecoded\n";
for (uint32_t n = 0; n < 32; ++n)
{
uint32_t g = gray_encode(n);
assert(gray_decode(g) == n);
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
}
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>
uint32_t gray_encode(uint32_t b)
{
return b ^ (b >> 1);
}
uint32_t gray_decode(uint32_t g)
{
for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
{
if (g & bit) g ^= bit >> 1;
}
return g;
}
std::string to_binary(int value)
{
const std::bitset<32> bs(value);
const std::string str(bs.to_string());
const size_t pos(str.find('1'));
return pos == std::string::npos ? "0" : str.substr(pos);
}
int main()
{
std::cout << "Number\tBinary\tGray\tDecoded\n";
for (uint32_t n = 0; n < 32; ++n)
{
uint32_t g = gray_encode(n);
assert(gray_decode(g) == n);
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Go version. | package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
gzipFlag := flag.Bool("gzip", false, "use gzip compression")
flag.Parse()
var w io.Writer = os.Stdout
if *outfile != "" {
f, err := os.Create(*outfile)
if err != nil {
log.Fatalf("opening/creating %q: %v", *outfile, err)
}
defer f.Close()
w = f
}
if *gzipFlag {
zw := gzip.NewWriter(w)
defer zw.Close()
w = zw
}
tw := tar.NewWriter(w)
defer tw.Close()
w = tw
tw.WriteHeader(&tar.Header{
Name: *filename,
Mode: 0660,
Size: int64(len(*data)),
ModTime: time.Now(),
Typeflag: tar.TypeReg,
Uname: "guest",
Gname: "guest",
})
_, err := w.Write([]byte(*data))
if err != nil {
log.Fatal("writing data:", err)
}
}
| #include <iostream>
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif
int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return 0;
}
|
Generate an equivalent C++ version of this Go code. | package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
gzipFlag := flag.Bool("gzip", false, "use gzip compression")
flag.Parse()
var w io.Writer = os.Stdout
if *outfile != "" {
f, err := os.Create(*outfile)
if err != nil {
log.Fatalf("opening/creating %q: %v", *outfile, err)
}
defer f.Close()
w = f
}
if *gzipFlag {
zw := gzip.NewWriter(w)
defer zw.Close()
w = zw
}
tw := tar.NewWriter(w)
defer tw.Close()
w = tw
tw.WriteHeader(&tar.Header{
Name: *filename,
Mode: 0660,
Size: int64(len(*data)),
ModTime: time.Now(),
Typeflag: tar.TypeReg,
Uname: "guest",
Gname: "guest",
})
_, err := w.Write([]byte(*data))
if err != nil {
log.Fatal("writing data:", err)
}
}
| #include <iostream>
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif
int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"sort"
"container/heap"
"fmt"
)
type HeapHelper struct {
container sort.Interface
length int
}
func (self HeapHelper) Len() int { return self.length }
func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }
func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }
func (self *HeapHelper) Push(x interface{}) { panic("impossible") }
func (self *HeapHelper) Pop() interface{} {
self.length--
return nil
}
func heapSort(a sort.Interface) {
helper := HeapHelper{ a, a.Len() }
heap.Init(&helper)
for helper.length > 0 {
heap.Pop(&helper)
}
}
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
heapSort(sort.IntSlice(a))
fmt.Println("after: ", a)
}
| #include <algorithm>
#include <iterator>
#include <iostream>
template<typename RandomAccessIterator>
void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {
std::make_heap(begin, end);
std::sort_heap(begin, end);
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
heap_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Five Rank = 5
Six Rank = 6
Seven Rank = 7
Eight Rank = 8
Nine Rank = 9
Ten Rank = 10
Jack Rank = 11
Queen Rank = 12
King Rank = 13
)
func (r Rank) String() string {
const ranks = "A23456789TJQK"
return ranks[r-1 : r]
}
type Card uint8
func NewCard(r Rank, s Suit) Card {
return Card(13*uint8(s) + uint8(r-1))
}
func (c Card) RankSuit() (Rank, Suit) {
return Rank(c%13 + 1), Suit(c / 13)
}
func (c Card) Rank() Rank {
return Rank(c%13 + 1)
}
func (c Card) Suit() Suit {
return Suit(c / 13)
}
func (c Card) String() string {
return c.Rank().String() + c.Suit().String()
}
type Deck []Card
func NewDeck() Deck {
d := make(Deck, 52)
for i := range d {
d[i] = Card(i)
}
return d
}
func (d Deck) String() string {
s := ""
for i, c := range d {
switch {
case i == 0:
case i%13 == 0:
s += "\n"
default:
s += " "
}
s += c.String()
}
return s
}
func (d Deck) Shuffle() {
for i := range d {
j := rand.Intn(i + 1)
d[i], d[j] = d[j], d[i]
}
}
func (d Deck) Contains(tc Card) bool {
for _, c := range d {
if c == tc {
return true
}
}
return false
}
func (d *Deck) AddDeck(decks ...Deck) {
for _, o := range decks {
*d = append(*d, o...)
}
}
func (d *Deck) AddCard(c Card) {
*d = append(*d, c)
}
func (d *Deck) Draw(n int) Deck {
old := *d
*d = old[n:]
return old[:n:n]
}
func (d *Deck) DrawCard() (Card, bool) {
if len(*d) == 0 {
return 0, false
}
old := *d
*d = old[1:]
return old[0], true
}
func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {
for i := 0; i < cards; i++ {
for j := range hands {
if len(*d) == 0 {
return hands, false
}
hands[j] = append(hands[j], (*d)[0])
*d = (*d)[1:]
}
}
return hands, true
}
| #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
enum { unique_count = pip_count * suite_count };
card(suite_type s, pip_type p): value(s + suite_count * p) {}
explicit card(unsigned char v = 0): value(v) {}
pip_type pip() { return pip_type(value / suite_count); }
suite_type suite() { return suite_type(value % suite_count); }
private:
unsigned char value;
};
const char* const pip_names[] =
{ "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"jack", "queen", "king", "ace" };
std::ostream& operator<<(std::ostream& os, card::pip_type pip)
{
return os << pip_names[pip];
}
const char* const suite_names[] =
{ "hearts", "spades", "diamonds", "clubs" };
std::ostream& operator<<(std::ostream& os, card::suite_type suite)
{
return os << suite_names[suite];
}
std::ostream& operator<<(std::ostream& os, card c)
{
return os << c.pip() << " of " << c.suite();
}
class deck
{
public:
deck()
{
for (int i = 0; i < card::unique_count; ++i) {
cards.push_back(card(i));
}
}
void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }
card deal() { card c = cards.front(); cards.pop_front(); return c; }
typedef std::deque<card>::const_iterator const_iterator;
const_iterator begin() const { return cards.cbegin(); }
const_iterator end() const { return cards.cend(); }
private:
std::deque<card> cards;
};
inline std::ostream& operator<<(std::ostream& os, const deck& d)
{
std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n"));
return os;
}
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import (
"fmt"
)
func main() {
var a [5]int
fmt.Println("len(a) =", len(a))
fmt.Println("a =", a)
a[0] = 3
fmt.Println("a =", a)
fmt.Println("a[0] =", a[0])
s := a[:4]
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
s = s[:5]
fmt.Println("s =", s)
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
}
| #include <array>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
template <typename Array>
void demonstrate(Array& array)
{
array[2] = "Three";
array.at(1) = "Two";
std::reverse(begin(array), end(array));
std::for_each(begin(array), end(array),
[](typename Array::value_type const& element)
{
std::cout << element << ' ';
});
std::cout << '\n';
}
int main()
{
auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
auto dynamic_array = std::vector<std::string>{ "One", "Four" };
dynamic_array.push_back("Eight");
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
}
|
#include <cstdint>
#include <cstdlib>
#include <cstdio>
static constexpr int32_t bct_low_bits = 0x55555555;
static int32_t bct_decrement(int32_t v) {
--v;
return v ^ (v & (v>>1) & bct_low_bits);
}
int main (int argc, char *argv[])
{
const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;
if (n < 0 || 9 < n) {
std::printf("N out of range (use 0..9): %ld\n", long(n));
return 1;
}
const int32_t size_bct = 1<<(n*2);
int32_t y = size_bct;
do {
y = bct_decrement(y);
int32_t x = size_bct;
do {
x = bct_decrement(x);
std::putchar((x & y & bct_low_bits) ? ' ' : '#');
} while (0 < x);
std::putchar('\n');
} while (0 < y);
return 0;
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
rand.Seed(time.Now().UnixNano())
fmt.Println("unsorted:", list)
temp := make([]int, len(list))
copy(temp, list)
for !sort.IntsAreSorted(temp) {
for i, v := range rand.Perm(len(list)) {
temp[i] = list[v]
}
}
fmt.Println("sorted! ", temp)
}
| #include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
Predicate p) {
std::random_device rd;
std::mt19937 generator(rd());
while (!std::is_sorted(begin, end, p)) {
std::shuffle(begin, end, generator);
}
}
template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bogo_sort(
begin, end,
std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bogo_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
|
Write a version of this Go function in C++ with identical behavior. | package main
import (
"fmt"
"math"
"sort"
)
type Patient struct {
id int
lastName string
}
var patientDir = make(map[int]string)
var patientIds []int
func patientNew(id int, lastName string) Patient {
patientDir[id] = lastName
patientIds = append(patientIds, id)
sort.Ints(patientIds)
return Patient{id, lastName}
}
type DS struct {
dates []string
scores []float64
}
type Visit struct {
id int
date string
score float64
}
var visitDir = make(map[int]DS)
func visitNew(id int, date string, score float64) Visit {
if date == "" {
date = "0000-00-00"
}
v, ok := visitDir[id]
if ok {
v.dates = append(v.dates, date)
v.scores = append(v.scores, score)
visitDir[id] = DS{v.dates, v.scores}
} else {
visitDir[id] = DS{[]string{date}, []float64{score}}
}
return Visit{id, date, score}
}
type Merge struct{ id int }
func (m Merge) lastName() string { return patientDir[m.id] }
func (m Merge) dates() []string { return visitDir[m.id].dates }
func (m Merge) scores() []float64 { return visitDir[m.id].scores }
func (m Merge) lastVisit() string {
dates := m.dates()
dates2 := make([]string, len(dates))
copy(dates2, dates)
sort.Strings(dates2)
return dates2[len(dates2)-1]
}
func (m Merge) scoreSum() float64 {
sum := 0.0
for _, score := range m.scores() {
if score != -1 {
sum += score
}
}
return sum
}
func (m Merge) scoreAvg() float64 {
count := 0
for _, score := range m.scores() {
if score != -1 {
count++
}
}
return m.scoreSum() / float64(count)
}
func mergePrint(merges []Merge) {
fmt.Println("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |")
f := "| %d | %-7s | %s | %4s | %4s |\n"
for _, m := range merges {
_, ok := visitDir[m.id]
if ok {
lv := m.lastVisit()
if lv == "0000-00-00" {
lv = " "
}
scoreSum := m.scoreSum()
ss := fmt.Sprintf("%4.1f", scoreSum)
if scoreSum == 0 {
ss = " "
}
scoreAvg := m.scoreAvg()
sa := " "
if !math.IsNaN(scoreAvg) {
sa = fmt.Sprintf("%4.2f", scoreAvg)
}
fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)
} else {
fmt.Printf(f, m.id, m.lastName(), " ", " ", " ")
}
}
}
func main() {
patientNew(1001, "Hopper")
patientNew(4004, "Wirth")
patientNew(3003, "Kemeny")
patientNew(2002, "Gosling")
patientNew(5005, "Kurtz")
visitNew(2002, "2020-09-10", 6.8)
visitNew(1001, "2020-09-17", 5.5)
visitNew(4004, "2020-09-24", 8.4)
visitNew(2002, "2020-10-08", -1)
visitNew(1001, "", 6.6)
visitNew(3003, "2020-11-12", -1)
visitNew(4004, "2020-11-05", 7.0)
visitNew(1001, "2020-11-19", 5.3)
merges := make([]Merge, len(patientIds))
for i, id := range patientIds {
merges[i] = Merge{id}
}
mergePrint(merges)
}
| #include <iostream>
#include <optional>
#include <ranges>
#include <string>
#include <vector>
using namespace std;
struct Patient
{
string ID;
string LastName;
};
struct Visit
{
string PatientID;
string Date;
optional<float> Score;
};
int main(void)
{
auto patients = vector<Patient> {
{"1001", "Hopper"},
{"4004", "Wirth"},
{"3003", "Kemeny"},
{"2002", "Gosling"},
{"5005", "Kurtz"}};
auto visits = vector<Visit> {
{"2002", "2020-09-10", 6.8},
{"1001", "2020-09-17", 5.5},
{"4004", "2020-09-24", 8.4},
{"2002", "2020-10-08", },
{"1001", "" , 6.6},
{"3003", "2020-11-12", },
{"4004", "2020-11-05", 7.0},
{"1001", "2020-11-19", 5.3}};
sort(patients.begin(), patients.end(),
[](const auto& a, const auto&b){ return a.ID < b.ID;});
cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n";
for(const auto& patient : patients)
{
string lastVisit;
float sum = 0;
int numScores = 0;
auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};
for(const auto& visit : visits | views::filter( patientFilter ))
{
if(visit.Score)
{
sum += *visit.Score;
numScores++;
}
lastVisit = max(lastVisit, visit.Date);
}
cout << "| " << patient.ID << " | ";
cout.width(8); cout << patient.LastName << " | ";
cout.width(10); cout << lastVisit << " | ";
if(numScores > 0)
{
cout.width(9); cout << sum << " | ";
cout.width(9); cout << (sum / float(numScores));
}
else cout << " | ";
cout << " |\n";
}
}
|
Produce a functionally identical C++ code for the snippet given in Go. | package main
import (
"fmt"
"math"
)
type fdy func(float64, float64) float64
func eulerStep(f fdy, x, y, h float64) float64 {
return y + h*f(x, y)
}
func newCoolingRate(k float64) func(float64) float64 {
return func(deltaTemp float64) float64 {
return -k * deltaTemp
}
}
func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {
return func(time float64) float64 {
return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)
}
}
func newCoolingRateDy(k, ambientTemp float64) fdy {
crf := newCoolingRate(k)
return func(_, objectTemp float64) float64 {
return crf(objectTemp - ambientTemp)
}
}
func main() {
k := .07
tempRoom := 20.
tempObject := 100.
fcr := newCoolingRateDy(k, tempRoom)
analytic := newTempFunc(k, tempRoom, tempObject)
for _, deltaTime := range []float64{2, 5, 10} {
fmt.Printf("Step size = %.1f\n", deltaTime)
fmt.Println(" Time Euler's Analytic")
temp := tempObject
for time := 0.; time <= 100; time += deltaTime {
fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time))
temp = eulerStep(fcr, time, temp, deltaTime)
}
fmt.Println()
}
}
| #include <iomanip>
#include <iostream>
typedef double F(double,double);
void euler(F f, double y0, double a, double b, double h)
{
double y = y0;
for (double t = a; t < b; t += h)
{
std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n";
y += h * f(t, y);
}
std::cout << "done\n";
}
double newtonCoolingLaw(double, double t)
{
return -0.07 * (t - 20);
}
int main()
{
euler(newtonCoolingLaw, 100, 0, 100, 2);
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
| #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>
double nextNumber( double number ) {
return number + floor( 0.5 + sqrt( number ) ) ;
}
int main( ) {
std::vector<double> non_squares ;
typedef std::vector<double>::iterator SVI ;
non_squares.reserve( 1000000 ) ;
for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
non_squares.push_back( nextNumber( i ) ) ;
std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
std::ostream_iterator<double>(std::cout, " " ) ) ;
std::cout << '\n' ;
SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
if ( found != non_squares.end( ) ) {
std::cout << "Found a square number in the sequence!\n" ;
std::cout << "It is " << *found << " !\n" ;
}
else {
std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
}
return 0 ;
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
| #include <iostream>
#include <string>
int main()
{
std::string s = "0123456789";
int const n = 3;
int const m = 4;
char const c = '2';
std::string const sub = "456";
std::cout << s.substr(n, m)<< "\n";
std::cout << s.substr(n) << "\n";
std::cout << s.substr(0, s.size()-1) << "\n";
std::cout << s.substr(s.find(c), m) << "\n";
std::cout << s.substr(s.find(sub), m) << "\n";
}
|
Rewrite the snippet below in C++ so it works the same as the original Go code. | package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
| #include <iostream>
#include <string>
int main()
{
std::string s = "0123456789";
int const n = 3;
int const m = 4;
char const c = '2';
std::string const sub = "456";
std::cout << s.substr(n, m)<< "\n";
std::cout << s.substr(n) << "\n";
std::cout << s.substr(0, s.size()-1) << "\n";
std::cout << s.substr(s.find(c), m) << "\n";
std::cout << s.substr(s.find(sub), m) << "\n";
}
|
Produce a functionally identical C++ code for the snippet given in Go. | package main
import (
"log"
"sort"
)
func main() {
log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4}))
log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))
log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))
log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))
}
func jortSort(a []int) bool {
c := make([]int, len(a))
copy(c, a)
sort.Ints(a)
for k, v := range c {
if v == a[k] {
continue
} else {
return false
}
}
return true
}
| #include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
class jortSort {
public:
template<class T>
bool jort_sort( T* o, size_t s ) {
T* n = copy_array( o, s );
sort_array( n, s );
bool r = false;
if( n ) {
r = check( o, n, s );
delete [] n;
}
return r;
}
private:
template<class T>
T* copy_array( T* o, size_t s ) {
T* z = new T[s];
memcpy( z, o, s * sizeof( T ) );
return z;
}
template<class T>
void sort_array( T* n, size_t s ) {
std::sort( n, n + s );
}
template<class T>
bool check( T* n, T* o, size_t s ) {
for( size_t x = 0; x < s; x++ )
if( n[x] != o[x] ) return false;
return true;
}
};
jortSort js;
template<class T>
void displayTest( T* o, size_t s ) {
std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) );
std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n";
}
int main( int argc, char* argv[] ) {
const size_t s = 5;
std::string oStr[] = { "5", "A", "D", "R", "S" };
displayTest( oStr, s );
std::swap( oStr[0], oStr[1] );
displayTest( oStr, s );
int oInt[] = { 1, 2, 3, 4, 5 };
displayTest( oInt, s );
std::swap( oInt[0], oInt[1] );
displayTest( oInt, s );
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
}
| #include <iostream>
bool is_leap_year(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
int main() {
for (auto year : {1900, 1994, 1996, 1997, 2000}) {
std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n";
}
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import (
"fmt"
"math/big"
)
func main() {
var n, p int64
fmt.Printf("A sample of permutations from 1 to 12:\n")
for n = 1; n < 13; n++ {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 10 to 60:\n")
for n = 10; n < 61; n += 10 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of permutations from 5 to 15000:\n")
nArr := [...]int64{5, 50, 500, 1000, 5000, 15000}
for _, n = range nArr {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 100 to 1000:\n")
for n = 100; n < 1001; n += 100 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
}
func fact(n *big.Int) *big.Int {
if n.Sign() < 1 {
return big.NewInt(0)
}
r := big.NewInt(1)
i := big.NewInt(2)
for i.Cmp(n) < 1 {
r.Mul(r, i)
i.Add(i, big.NewInt(1))
}
return r
}
func perm(n, k *big.Int) *big.Int {
r := fact(n)
r.Div(r, fact(n.Sub(n, k)))
return r
}
func comb(n, r *big.Int) *big.Int {
if r.Cmp(n) == 1 {
return big.NewInt(0)
}
if r.Cmp(n) == 0 {
return big.NewInt(1)
}
c := fact(n)
den := fact(n.Sub(n, r))
den.Mul(den, fact(r))
c.Div(c, den)
return c
}
| #include <boost/multiprecision/gmp.hpp>
#include <iostream>
using namespace boost::multiprecision;
mpz_int p(uint n, uint p) {
mpz_int r = 1;
mpz_int k = n - p;
while (n > k)
r *= n--;
return r;
}
mpz_int c(uint n, uint k) {
mpz_int r = p(n, k);
while (k)
r /= k--;
return r;
}
int main() {
for (uint i = 1u; i < 12u; i++)
std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl;
for (uint i = 10u; i < 60u; i += 10u)
std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl;
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/big"
)
func main() {
var n, p int64
fmt.Printf("A sample of permutations from 1 to 12:\n")
for n = 1; n < 13; n++ {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 10 to 60:\n")
for n = 10; n < 61; n += 10 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of permutations from 5 to 15000:\n")
nArr := [...]int64{5, 50, 500, 1000, 5000, 15000}
for _, n = range nArr {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 100 to 1000:\n")
for n = 100; n < 1001; n += 100 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
}
func fact(n *big.Int) *big.Int {
if n.Sign() < 1 {
return big.NewInt(0)
}
r := big.NewInt(1)
i := big.NewInt(2)
for i.Cmp(n) < 1 {
r.Mul(r, i)
i.Add(i, big.NewInt(1))
}
return r
}
func perm(n, k *big.Int) *big.Int {
r := fact(n)
r.Div(r, fact(n.Sub(n, k)))
return r
}
func comb(n, r *big.Int) *big.Int {
if r.Cmp(n) == 1 {
return big.NewInt(0)
}
if r.Cmp(n) == 0 {
return big.NewInt(1)
}
c := fact(n)
den := fact(n.Sub(n, r))
den.Mul(den, fact(r))
c.Div(c, den)
return c
}
| #include <boost/multiprecision/gmp.hpp>
#include <iostream>
using namespace boost::multiprecision;
mpz_int p(uint n, uint p) {
mpz_int r = 1;
mpz_int k = n - p;
while (n > k)
r *= n--;
return r;
}
mpz_int c(uint n, uint k) {
mpz_int r = p(n, k);
while (k)
r /= k--;
return r;
}
int main() {
for (uint i = 1u; i < 12u; i++)
std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl;
for (uint i = 10u; i < 60u; i += 10u)
std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl;
return 0;
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import (
"fmt"
"sort"
"strconv"
)
func lexOrder(n int) []int {
first, last, k := 1, n, n
if n < 1 {
first, last, k = n, 1, 2-n
}
strs := make([]string, k)
for i := first; i <= last; i++ {
strs[i-first] = strconv.Itoa(i)
}
sort.Strings(strs)
ints := make([]int, k)
for i := 0; i < k; i++ {
ints[i], _ = strconv.Atoi(strs[i])
}
return ints
}
func main() {
fmt.Println("In lexicographical order:\n")
for _, n := range []int{0, 5, 13, 21, -22} {
fmt.Printf("%3d: %v\n", n, lexOrder(n))
}
}
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
void lexicographical_sort(std::vector<int>& numbers) {
std::vector<std::string> strings(numbers.size());
std::transform(numbers.begin(), numbers.end(), strings.begin(),
[](int i) { return std::to_string(i); });
std::sort(strings.begin(), strings.end());
std::transform(strings.begin(), strings.end(), numbers.begin(),
[](const std::string& s) { return std::stoi(s); });
}
std::vector<int> lexicographically_sorted_vector(int n) {
std::vector<int> numbers(n >= 1 ? n : 2 - n);
std::iota(numbers.begin(), numbers.end(), std::min(1, n));
lexicographical_sort(numbers);
return numbers;
}
template <typename T>
void print_vector(std::ostream& out, const std::vector<T>& v) {
out << '[';
if (!v.empty()) {
auto i = v.begin();
out << *i++;
for (; i != v.end(); ++i)
out << ',' << *i;
}
out << "]\n";
}
int main(int argc, char** argv) {
for (int i : { 0, 5, 13, 21, -22 }) {
std::cout << i << ": ";
print_vector(std::cout, lexicographically_sorted_vector(i));
}
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
| #include <string>
#include <iostream>
using std::string;
const char* smallNumbers[] = {
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
string spellHundreds(unsigned n) {
string res;
if (n > 99) {
res = smallNumbers[n/100];
res += " hundred";
n %= 100;
if (n) res += " and ";
}
if (n >= 20) {
static const char* Decades[] = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};
res += Decades[n/10];
n %= 10;
if (n) res += "-";
}
if (n < 20 && n > 0)
res += smallNumbers[n];
return res;
}
const char* thousandPowers[] = {
" billion", " million", " thousand", "" };
typedef unsigned long Spellable;
string spell(Spellable n) {
if (n < 20) return smallNumbers[n];
string res;
const char** pScaleName = thousandPowers;
Spellable scaleFactor = 1000000000;
while (scaleFactor > 0) {
if (n >= scaleFactor) {
Spellable h = n / scaleFactor;
res += spellHundreds(h) + *pScaleName;
n %= scaleFactor;
if (n) res += ", ";
}
scaleFactor /= 1000;
++pScaleName;
}
return res;
}
int main() {
#define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl;
SPELL_IT( 99);
SPELL_IT( 300);
SPELL_IT( 310);
SPELL_IT( 1501);
SPELL_IT( 12609);
SPELL_IT( 512609);
SPELL_IT(43112609);
SPELL_IT(1234567890);
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"fmt"
"os"
"sort"
)
func main() {
if len(os.Args) == 1 {
compareStrings("abcd", "123456789", "abcdef", "1234567")
} else {
strings := os.Args[1:]
compareStrings(strings...)
}
}
func compareStrings(strings ...string) {
sort.SliceStable(strings, func(i, j int) bool {
return len(strings[i]) > len(strings[j])
})
for _, s := range strings {
fmt.Printf("%d: %s\n", len(s), s)
}
}
| #include <iostream>
#include <algorithm>
#include <string>
#include <list>
using namespace std;
bool cmp(const string& a, const string& b)
{
return b.length() < a.length();
}
void compareAndReportStringsLength(list<string> listOfStrings)
{
if (!listOfStrings.empty())
{
char Q = '"';
string has_length(" has length ");
string predicate_max(" and is the longest string");
string predicate_min(" and is the shortest string");
string predicate_ave(" and is neither the longest nor the shortest string");
list<string> ls(listOfStrings);
ls.sort(cmp);
int max = ls.front().length();
int min = ls.back().length();
for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
{
int length = s->length();
string* predicate;
if (length == max)
predicate = &predicate_max;
else if (length == min)
predicate = &predicate_min;
else
predicate = &predicate_ave;
cout << Q << *s << Q << has_length << length << *predicate << endl;
}
}
}
int main(int argc, char* argv[])
{
list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(listOfStrings);
return EXIT_SUCCESS;
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {
for i := inc; i < len(a); i++ {
j, temp := i, a[i]
for ; j >= inc && a[j-inc] > temp; j -= inc {
a[j] = a[j-inc]
}
a[j] = temp
}
}
fmt.Println("after: ", a)
}
| #include <time.h>
#include <iostream>
using namespace std;
const int MAX = 126;
class shell
{
public:
shell()
{ _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }
void sort( int* a, int count )
{
_cnt = count;
for( int x = 0; x < 9; x++ )
if( count > _gap[x] )
{ _idx = x; break; }
sortIt( a );
}
private:
void sortIt( int* arr )
{
bool sorted = false;
while( true )
{
sorted = true;
int st = 0;
for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
{
if( arr[st] > arr[x] )
{ swap( arr[st], arr[x] ); sorted = false; }
st = x;
}
if( ++_idx >= 8 ) _idx = 8;
if( sorted && _idx == 8 ) break;
}
}
void swap( int& a, int& b ) { int t = a; a = b; b = t; }
int _gap[9], _idx, _cnt;
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];
for( int x = 0; x < MAX; x++ )
arr[x] = rand() % MAX - rand() % MAX;
cout << " Before: \n=========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl; shell s; s.sort( arr, MAX );
cout << " After: \n========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl << endl; return system( "pause" );
}
|
Write a version of this Go function in C++ with identical behavior. | type dlNode struct {
int
next, prev *dlNode
}
type dlList struct {
members map[*dlNode]int
head, tail **dlNode
}
| #include <iostream>
#include <list>
int main ()
{
std::list<int> numbers {1, 5, 7, 0, 3, 2};
numbers.insert(numbers.begin(), 9);
numbers.insert(numbers.end(), 4);
auto it = std::next(numbers.begin(), numbers.size() / 2);
numbers.insert(it, 6);
for(const auto& i: numbers)
std::cout << i << ' ';
std::cout << '\n';
}
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"io/ioutil"
"sort"
"unicode"
)
const file = "unixdict.txt"
func main() {
bs, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return
}
m := make(map[rune]int)
for _, r := range string(bs) {
m[r]++
}
lfs := make(lfList, 0, len(m))
for l, f := range m {
lfs = append(lfs, &letterFreq{l, f})
}
sort.Sort(lfs)
fmt.Println("file:", file)
fmt.Println("letter frequency")
for _, lf := range lfs {
if unicode.IsGraphic(lf.rune) {
fmt.Printf(" %c %7d\n", lf.rune, lf.freq)
} else {
fmt.Printf("%U %7d\n", lf.rune, lf.freq)
}
}
}
type letterFreq struct {
rune
freq int
}
type lfList []*letterFreq
func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
switch fd := lfs[i].freq - lfs[j].freq; {
case fd < 0:
return false
case fd > 0:
return true
}
return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
lfs[i], lfs[j] = lfs[j], lfs[i]
}
| #include <fstream>
#include <iostream>
int main()
{
std::ifstream input("filename.txt", std::ios_base::binary);
if (!input)
{
std::cerr << "error: can't open file\n";
return -1;
}
size_t count[256];
std::fill_n(count, 256, 0);
for (char c; input.get(c); ++count[uint8_t(c)])
;
for (size_t i = 0; i < 256; ++i)
{
if (count[i] && isgraph(i))
{
std::cout << char(i) << " = " << count[i] << '\n';
}
}
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import "fmt"
var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}
var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
func main() {
all := make([]int, len(tr)+len(ct))
copy(all, tr)
copy(all[len(tr):], ct)
var sumAll int
for _, r := range all {
sumAll += r
}
sd := func(trc []int) int {
var sumTr int
for _, x := range trc {
sumTr += all[x]
}
return sumTr*len(ct) - (sumAll-sumTr)*len(tr)
}
a := make([]int, len(tr))
for i, _ := range a {
a[i] = i
}
sdObs := sd(a)
var nLe, nGt int
comb(len(all), len(tr), func(c []int) {
if sd(c) > sdObs {
nGt++
} else {
nLe++
}
})
pc := 100 / float64(nLe+nGt)
fmt.Printf("differences <= observed: %f%%\n", float64(nLe)*pc)
fmt.Printf("differences > observed: %f%%\n", float64(nGt)*pc)
}
func comb(n, m int, emit func([]int)) {
s := make([]int, m)
last := m - 1
var rc func(int, int)
rc = func(i, next int) {
for j := next; j < n; j++ {
s[i] = j
if i == last {
emit(s)
} else {
rc(i+1, j+1)
}
}
return
}
rc(0, 0)
}
| #include<iostream>
#include<vector>
#include<numeric>
#include<functional>
class
{
public:
int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}
private:
int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }
int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}
}combinations;
int main()
{
static constexpr int treatment = 9;
const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);
std::function<int (int, int, int)> pick;
pick = [&](int n, int from, int accumulated)
{
if(n == 0)
return accumulated > treated ? 1 : 0;
else
return pick(n - 1, from - 1, accumulated + data[from - 1]) +
(from > n ? pick(n, from - 1, accumulated) : 0);
};
int total = combinations(data.size(), treatment);
int greater = pick(treatment, data.size(), 0);
int lesser = total - greater;
std::cout << "<= : " << 100.0 * lesser / total << "% " << lesser << std::endl
<< " > : " << 100.0 * greater / total << "% " << greater << std::endl;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | package main
import "fmt"
func möbius(to int) []int {
if to < 1 {
to = 1
}
mobs := make([]int, to+1)
primes := []int{2}
for i := 1; i <= to; i++ {
j := i
cp := 0
spf := false
for _, p := range primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes = append(primes, i)
}
if !spf {
if cp%2 == 0 {
mobs[i] = 1
} else {
mobs[i] = -1
}
}
}
return mobs
}
func main() {
mobs := möbius(199)
fmt.Println("Möbius sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
fmt.Print(" ")
continue
}
if i%20 == 0 {
fmt.Println()
}
fmt.Printf(" % d", mobs[i])
}
}
| #include <iomanip>
#include <iostream>
#include <vector>
constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;
int mobiusFunction(int n) {
if (!MU.empty()) {
return MU[n];
}
MU.resize(MU_MAX + 1, 1);
int root = sqrt(MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1) {
for (int j = i; j <= MU_MAX; j += i) {
MU[j] *= -i;
}
for (int j = i * i; j <= MU_MAX; j += i * i) {
MU[j] = 0;
}
}
}
for (int i = 2; i <= MU_MAX; i++) {
if (MU[i] == i) {
MU[i] = 1;
} else if (MU[i] == -i) {
MU[i] = -1;
} else if (MU[i] < 0) {
MU[i] = 1;
} else if (MU[i] > 0) {
MU[i] = -1;
}
}
return MU[n];
}
int main() {
std::cout << "First 199 terms of the möbius function are as follows:\n ";
for (int n = 1; n < 200; n++) {
std::cout << std::setw(2) << mobiusFunction(n) << " ";
if ((n + 1) % 20 == 0) {
std::cout << '\n';
}
}
return 0;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}
|
#include <cstdlib>
#include <string>
#include <sstream>
std::string s = "12345";
int i;
std::istringstream(s) >> i;
i++;
std::ostringstream oss;
if (oss << i) s = oss.str();
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}
| #include <algorithm>
#include <iostream>
#include <string>
std::string stripchars(std::string str, const std::string &chars)
{
str.erase(
std::remove_if(str.begin(), str.end(), [&](char c){
return chars.find(c) != std::string::npos;
}),
str.end()
);
return str;
}
int main()
{
std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n';
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
if len(a) > 1 && !recurse(len(a) - 1) {
panic("sorted permutation not found!")
}
fmt.Println("after: ", a)
}
func recurse(last int) bool {
if last <= 0 {
for i := len(a) - 1; a[i] >= a[i-1]; i-- {
if i == 1 {
return true
}
}
return false
}
for i := 0; i <= last; i++ {
a[i], a[last] = a[last], a[i]
if recurse(last - 1) {
return true
}
a[i], a[last] = a[last], a[i]
}
return false
}
| #include <algorithm>
template<typename ForwardIterator>
void permutation_sort(ForwardIterator begin, ForwardIterator end)
{
while (std::next_permutation(begin, end))
{
}
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{},
[]float64{math.Inf(1), math.Inf(1)},
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}
| #include <vector>
double mean(const std::vector<double>& numbers)
{
if (numbers.size() == 0)
return 0;
double sum = 0;
for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)
sum += *i;
return sum / numbers.size();
}
|
Convert the following code from Go to C++, ensuring the logic remains intact. | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
| #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
bool parse_integer(const std::string& word, int& value) {
try {
size_t pos;
int i = std::stoi(word, &pos, 10);
if (pos < word.length())
return false;
value = i;
return true;
} catch (const std::exception& ex) {
return false;
}
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::istringstream is(table);
std::string word;
std::vector<std::string> words;
while (is >> word) {
uppercase(word);
words.push_back(word);
}
for (size_t i = 0, n = words.size(); i < n; ++i) {
word = words[i];
int len = word.length();
if (i + 1 < n && parse_integer(words[i + 1], len))
++i;
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
| #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
bool parse_integer(const std::string& word, int& value) {
try {
size_t pos;
int i = std::stoi(word, &pos, 10);
if (pos < word.length())
return false;
value = i;
return true;
} catch (const std::exception& ex) {
return false;
}
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::istringstream is(table);
std::string word;
std::vector<std::string> words;
while (is >> word) {
uppercase(word);
words.push_back(word);
}
for (size_t i = 0, n = words.size(); i < n; ++i) {
word = words[i];
int len = word.length();
if (i + 1 < n && parse_integer(words[i + 1], len))
++i;
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
| #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
bool parse_integer(const std::string& word, int& value) {
try {
size_t pos;
int i = std::stoi(word, &pos, 10);
if (pos < word.length())
return false;
value = i;
return true;
} catch (const std::exception& ex) {
return false;
}
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::istringstream is(table);
std::string word;
std::vector<std::string> words;
while (is >> word) {
uppercase(word);
words.push_back(word);
}
for (size_t i = 0, n = words.size(); i < n; ++i) {
word = words[i];
int len = word.length();
if (i + 1 < n && parse_integer(words[i + 1], len))
++i;
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math"
"strings"
)
func main(){
fmt.Println(H("1223334444"))
}
func H(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
}
| #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
double log2( double number ) {
return log( number ) / log( 2 ) ;
}
int main( int argc , char *argv[ ] ) {
std::string teststring( argv[ 1 ] ) ;
std::map<char , int> frequencies ;
for ( char c : teststring )
frequencies[ c ] ++ ;
int numlen = teststring.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
infocontent -= freq * log2( freq ) ;
}
std::cout << "The information content of " << teststring
<< " is " << infocontent << std::endl ;
return 0 ;
}
|
Convert the following code from Go to C++, ensuring the logic remains intact. | package main
import (
"errors"
"fmt"
)
func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
for _, r := range s {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, r)
case r == escape:
inEscape = true
case r == sep:
tokens = append(tokens, string(runes))
runes = runes[:0]
}
}
tokens = append(tokens, string(runes))
if inEscape {
err = errors.New("invalid terminal escape")
}
return tokens, err
}
func main() {
const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
const separator = '|'
const escape = '^'
fmt.Printf("Input: %q\n", sample)
tokens, err := TokenizeString(sample, separator, escape)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Printf("Tokens: %q\n", tokens)
}
}
| #include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
vector<string> tokenize(const string& input, char seperator, char escape) {
vector<string> output;
string token;
bool inEsc = false;
for (char ch : input) {
if (inEsc) {
inEsc = false;
} else if (ch == escape) {
inEsc = true;
continue;
} else if (ch == seperator) {
output.push_back(token);
token = "";
continue;
}
token += ch;
}
if (inEsc)
throw new invalid_argument("Invalid terminal escape");
output.push_back(token);
return output;
}
int main() {
string sample = "one^|uno||three^^^^|four^^^|^cuatro|";
cout << sample << endl;
cout << '[';
for (auto t : tokenize(sample, '|', '^')) {
cout << '"' << t << "\", ";
}
cout << ']' << endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.