Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this Go snippet to C++ and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
#include <gmpxx.h> #include <iomanip> #include <iostream> using big_int = mpz_class; bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0; } big_int jacobsthal_number(unsigned int n) { return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3; } big_int jacobsthal_lucas_number(unsigned int n) { return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1); } big_int jacobsthal_oblong_number(unsigned int n) { return jacobsthal_number(n) * jacobsthal_number(n + 1); } int main() { std::cout << "First 30 Jacobsthal Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_lucas_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n"; for (unsigned int n = 0; n < 20; ++n) { std::cout << std::setw(11) << jacobsthal_oblong_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal primes:\n"; for (unsigned int n = 0, count = 0; count < 20; ++n) { auto jn = jacobsthal_number(n); if (is_probably_prime(jn)) { ++count; std::cout << jn << '\n'; } } }
Maintain the same structure and functionality when rewriting this code in C++.
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
#include <gmpxx.h> #include <iomanip> #include <iostream> using big_int = mpz_class; bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0; } big_int jacobsthal_number(unsigned int n) { return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3; } big_int jacobsthal_lucas_number(unsigned int n) { return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1); } big_int jacobsthal_oblong_number(unsigned int n) { return jacobsthal_number(n) * jacobsthal_number(n + 1); } int main() { std::cout << "First 30 Jacobsthal Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_lucas_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n"; for (unsigned int n = 0; n < 20; ++n) { std::cout << std::setw(11) << jacobsthal_oblong_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal primes:\n"; for (unsigned int n = 0, count = 0; count < 20; ++n) { auto jn = jacobsthal_number(n); if (is_probably_prime(jn)) { ++count; std::cout << jn << '\n'; } } }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
#include <gmpxx.h> #include <iomanip> #include <iostream> using big_int = mpz_class; bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0; } big_int jacobsthal_number(unsigned int n) { return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3; } big_int jacobsthal_lucas_number(unsigned int n) { return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1); } big_int jacobsthal_oblong_number(unsigned int n) { return jacobsthal_number(n) * jacobsthal_number(n + 1); } int main() { std::cout << "First 30 Jacobsthal Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_lucas_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n"; for (unsigned int n = 0; n < 20; ++n) { std::cout << std::setw(11) << jacobsthal_oblong_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal primes:\n"; for (unsigned int n = 0, count = 0; count < 20; ++n) { auto jn = jacobsthal_number(n); if (is_probably_prime(jn)) { ++count; std::cout << jn << '\n'; } } }
Change the programming language of this snippet from Go to C++ without modifying what it does.
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, aMax) for pole, space := 0, all; pole < aMax; pole++ { abacus[pole] = space[:len(a)] space = space[len(a):] } var wg sync.WaitGroup wg.Add(len(a)) for row, n := range a { go func(row, n int) { for pole := 0; pole < n; pole++ { abacus[pole][row] = bead } wg.Done() }(row, n) } wg.Wait() wg.Add(aMax) for _, pole := range abacus { go func(pole []byte) { top := 0 for row, space := range pole { if space == bead { pole[row] = 0 pole[top] = bead top++ } } wg.Done() }(pole) } wg.Wait() for row := range a { x := 0 for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ { x++ } a[len(a)-1-row] = x } }
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth (myints, myints + n); cout << "#1 Beads falling down: "; for (int i=0; i < fifth.size(); i++) distribute (fifth[i], list); cout << '\n'; cout << "\nBeads on their sides: "; for (int i=0; i < list.size(); i++) cout << " " << list[i]; cout << '\n'; cout << "#2 Beads right side up: "; for (int i=0; i < list.size(); i++) distribute (list[i], list2); cout << '\n'; return list2; } int main() { int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1}; vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int)); cout << "Sorted list/array: "; for(unsigned int i=0; i<sorted.size(); i++) cout << sorted[i] << ' '; }
Produce a functionally identical C++ code for the snippet given in Go.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
Keep all operations the same but rewrite the snippet in C++.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
Write the same code in C++ as shown below in Go.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
Port the following code from Go to C++ with equivalent syntax and logic.
package main import ( "fmt" "math/big" ) func main() { x := big.NewInt(2) x = x.Exp(big.NewInt(3), x, nil) x = x.Exp(big.NewInt(4), x, nil) x = x.Exp(big.NewInt(5), x, nil) str := x.String() fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n", len(str), str[:20], str[len(str)-20:], ) }
#include <iostream> #include <boost/multiprecision/gmp.hpp> #include <string> namespace mp = boost::multiprecision; int main(int argc, char const *argv[]) { uint64_t tmpres = mp::pow(mp::mpz_int(4) , mp::pow(mp::mpz_int(3) , 2).convert_to<uint64_t>() ).convert_to<uint64_t>(); mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres); std::string s = res.str(); std::cout << s.substr(0, 20) << "..." << s.substr(s.length() - 20, 20) << std::endl; return 0; }
Produce a language-to-language conversion: from Go to C++, same semantics.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.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 <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.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 <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.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 <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
Convert this Go block to C++, preserving its control flow and logic.
package main import ( "bufio" "bytes" "errors" "fmt" "io" "os" ) var index map[string][]int var indexed []doc type doc struct { file string title string } func main() { index = make(map[string][]int) if err := indexDir("docs"); err != nil { fmt.Println(err) return } ui() } func indexDir(dir string) error { df, err := os.Open(dir) if err != nil { return err } fis, err := df.Readdir(-1) if err != nil { return err } if len(fis) == 0 { return errors.New(fmt.Sprintf("no files in %s", dir)) } indexed := 0 for _, fi := range fis { if !fi.IsDir() { if indexFile(dir + "/" + fi.Name()) { indexed++ } } } return nil } func indexFile(fn string) bool { f, err := os.Open(fn) if err != nil { fmt.Println(err) return false } x := len(indexed) indexed = append(indexed, doc{fn, fn}) pdoc := &indexed[x] r := bufio.NewReader(f) lines := 0 for { b, isPrefix, err := r.ReadLine() switch { case err == io.EOF: return true case err != nil: fmt.Println(err) return true case isPrefix: fmt.Printf("%s: unexpected long line\n", fn) return true case lines < 20 && bytes.HasPrefix(b, []byte("Title:")): pdoc.title = string(b[7:]) } wordLoop: for _, bword := range bytes.Fields(b) { bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@") if len(bword) > 0 { word := string(bword) dl := index[word] for _, d := range dl { if d == x { continue wordLoop } } index[word] = append(dl, x) } } } return true } func ui() { fmt.Println(len(index), "words indexed in", len(indexed), "files") fmt.Println("enter single words to search for") fmt.Println("enter a blank line when done") var word string for { fmt.Print("search word: ") wc, _ := fmt.Scanln(&word) if wc == 0 { return } switch dl := index[word]; len(dl) { case 0: fmt.Println("no match") case 1: fmt.Println("one match:") fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title) default: fmt.Println(len(dl), "matches:") for _, d := range dl { fmt.Println(" ", indexed[d].file, indexed[d].title) } } } }
#include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <string> const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/"; const size_t MAX_NODES = 41; class node { public: node() { clear(); } node( char z ) { clear(); } ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; } void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; } bool isWord; std::vector<std::string> files; node* next[MAX_NODES]; }; class index { public: void add( std::string s, std::string fileName ) { std::transform( s.begin(), s.end(), s.begin(), tolower ); std::string h; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { if( *i == 32 ) { pushFileName( addWord( h ), fileName ); h.clear(); continue; } h.append( 1, *i ); } if( h.length() ) pushFileName( addWord( h ), fileName ); } void findWord( std::string s ) { std::vector<std::string> v = find( s ); if( !v.size() ) { std::cout << s + " was not found!\n"; return; } std::cout << s << " found in:\n"; for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) { std::cout << *i << "\n"; } std::cout << "\n"; } private: void pushFileName( node* n, std::string fn ) { std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn ); if( i == n->files.end() ) n->files.push_back( fn ); } const std::vector<std::string>& find( std::string s ) { size_t idx; std::transform( s.begin(), s.end(), s.begin(), tolower ); node* rt = &root; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { if( !rt->next[idx] ) return std::vector<std::string>(); rt = rt->next[idx]; } } if( rt->isWord ) return rt->files; return std::vector<std::string>(); } node* addWord( std::string s ) { size_t idx; node* rt = &root, *n; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { n = rt->next[idx]; if( n ){ rt = n; continue; } n = new node( *i ); rt->next[idx] = n; rt = n; } } rt->isWord = true; return rt; } node root; }; int main( int argc, char* argv[] ) { index t; std::string s; std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" }; for( int x = 0; x < 3; x++ ) { std::ifstream f; f.open( files[x].c_str(), std::ios::in ); if( f.good() ) { while( !f.eof() ) { f >> s; t.add( s, files[x] ); s.clear(); } f.close(); } } while( true ) { std::cout << "Enter one word to search for, return to exit: "; std::getline( std::cin, s ); if( !s.length() ) break; t.findWord( s ); } return 0; }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Generate an equivalent C++ version of this Go code.
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << 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" import "math/rand" import "time" func main() { rand.Seed(time.Now().UnixNano()) for { a := rand.Intn(20) fmt.Println(a) if a == 10 { break } b := rand.Intn(20) fmt.Println(b) } }
#include <iostream> #include <ctime> #include <cstdlib> int main(){ srand(time(NULL)); while(true){ const int a = rand() % 20; std::cout << a << std::endl; if(a == 10) break; const int b = rand() % 20; std::cout << b << std::endl; } return 0; }
Write the same code in C++ as shown below in Go.
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
Write a version of this Go function in C++ with identical behavior.
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
Port the following code from Go to C++ with equivalent syntax and logic.
package main import "fmt" func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func min(a,b []int) []int { res := make([]int,len(a)) for i := 0; i < len(a);i++{ if a[i] >= b[i]{ res[i] = b[i] }else { res[i] = a[i] } } return res } func diff(hm, min []int) []int { res := make([]int,len(hm)) for i := 0; i < len(hm);i++{ if min[i] > hm[i]{ res[i] = min[i] - hm[i] } } return res } func sum(a []int) int { res := 0 for i := 0; i < len(a);i++{ res += a[i] } return res } func waterCollected(hm []int) int { maxr := maxr(hm) maxl := maxl(hm) min := min(maxr,maxl) diff := diff(hm,min) sum := sum(diff) return sum } func main() { fmt.Println(waterCollected([]int{1, 5, 3, 7, 2})) fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2})) fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1})) fmt.Println(waterCollected([]int{5, 5, 5, 5})) fmt.Println(waterCollected([]int{5, 6, 7, 8})) fmt.Println(waterCollected([]int{8, 7, 7, 6})) fmt.Println(waterCollected([]int{6, 7, 10, 7, 6})) }
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically?
package main import "fmt" func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func min(a,b []int) []int { res := make([]int,len(a)) for i := 0; i < len(a);i++{ if a[i] >= b[i]{ res[i] = b[i] }else { res[i] = a[i] } } return res } func diff(hm, min []int) []int { res := make([]int,len(hm)) for i := 0; i < len(hm);i++{ if min[i] > hm[i]{ res[i] = min[i] - hm[i] } } return res } func sum(a []int) int { res := 0 for i := 0; i < len(a);i++{ res += a[i] } return res } func waterCollected(hm []int) int { maxr := maxr(hm) maxl := maxl(hm) min := min(maxr,maxl) diff := diff(hm,min) sum := sum(diff) return sum } func main() { fmt.Println(waterCollected([]int{1, 5, 3, 7, 2})) fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2})) fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1})) fmt.Println(waterCollected([]int{5, 5, 5, 5})) fmt.Println(waterCollected([]int{5, 6, 7, 8})) fmt.Println(waterCollected([]int{8, 7, 7, 6})) fmt.Println(waterCollected([]int{6, 7, 10, 7, 6})) }
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, len(c)) copy(t, c) combs = append(combs, t) return } for i := start; i <= end && end-i+1 >= k-index; i++ { c[index] = a[i] combine(i+1, end, index+1) } } combine(0, n-1, 0) return combs } func powerset(a []int) (res [][]int) { if len(a) == 0 { return } for i := 1; i <= len(a); i++ { res = append(res, combinations(a, i)...) } return } func main() { ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) var descPrimes []int for i := 1; i < len(ps); i++ { s := "" for _, e := range ps[i] { s += string(e + '0') } p, _ := strconv.Atoi(s) if rcu.IsPrime(p) { descPrimes = append(descPrimes, p) } } sort.Ints(descPrimes) fmt.Println("There are", len(descPrimes), "descending primes, namely:") for i := 0; i < len(descPrimes); i++ { fmt.Printf("%8d ", descPrimes[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
Convert this Go snippet to C++ and keep its semantics consistent.
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, len(c)) copy(t, c) combs = append(combs, t) return } for i := start; i <= end && end-i+1 >= k-index; i++ { c[index] = a[i] combine(i+1, end, index+1) } } combine(0, n-1, 0) return combs } func powerset(a []int) (res [][]int) { if len(a) == 0 { return } for i := 1; i <= len(a); i++ { res = append(res, combinations(a, i)...) } return } func main() { ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) var descPrimes []int for i := 1; i < len(ps); i++ { s := "" for _, e := range ps[i] { s += string(e + '0') } p, _ := strconv.Atoi(s) if rcu.IsPrime(p) { descPrimes = append(descPrimes, p) } } sort.Ints(descPrimes) fmt.Println("There are", len(descPrimes), "descending primes, namely:") for i := 0; i < len(descPrimes); i++ { fmt.Printf("%8d ", descPrimes[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
Produce a functionally identical C++ code for the snippet given in Go.
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } for i := uint64(3); i <= limit; i += 2 { if !c[i] { primes = append(primes, i) } } return primes } func squareFree(from, to uint64) (results []uint64) { limit := uint64(math.Sqrt(float64(to))) primes := sieve(limit) outer: for i := from; i <= to; i++ { for _, p := range primes { p2 := p * p if p2 > i { break } if i%p2 == 0 { continue outer } } results = append(results, i) } return } const trillion uint64 = 1000000000000 func main() { fmt.Println("Square-free integers from 1 to 145:") sf := squareFree(1, 145) for i := 0; i < len(sf); i++ { if i > 0 && i%20 == 0 { fmt.Println() } fmt.Printf("%4d", sf[i]) } fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145) sf = squareFree(trillion, trillion+145) for i := 0; i < len(sf); i++ { if i > 0 && i%5 == 0 { fmt.Println() } fmt.Printf("%14d", sf[i]) } fmt.Println("\n\nNumber of square-free integers:\n") a := [...]uint64{100, 1000, 10000, 100000, 1000000} for _, n := range a { fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n))) } }
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return false; } } return true; } void print_square_free_numbers(integer from, integer to) { std::cout << "Square-free numbers between " << from << " and " << to << ":\n"; std::string line; for (integer i = from; i <= to; ++i) { if (square_free(i)) { if (!line.empty()) line += ' '; line += std::to_string(i); if (line.size() >= 80) { std::cout << line << '\n'; line.clear(); } } } if (!line.empty()) std::cout << line << '\n'; } void print_square_free_count(integer from, integer to) { integer count = 0; for (integer i = from; i <= to; ++i) { if (square_free(i)) ++count; } std::cout << "Number of square-free numbers between " << from << " and " << to << ": " << count << '\n'; } int main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000LL, 1000000000145LL); print_square_free_count(1, 100); print_square_free_count(1, 1000); print_square_free_count(1, 10000); print_square_free_count(1, 100000); print_square_free_count(1, 1000000); return 0; }
Write the same code in C++ as shown below in Go.
package main import "fmt" func jaro(str1, str2 string) float64 { if len(str1) == 0 && len(str2) == 0 { return 1 } if len(str1) == 0 || len(str2) == 0 { return 0 } match_distance := len(str1) if len(str2) > match_distance { match_distance = len(str2) } match_distance = match_distance/2 - 1 str1_matches := make([]bool, len(str1)) str2_matches := make([]bool, len(str2)) matches := 0. transpositions := 0. for i := range str1 { start := i - match_distance if start < 0 { start = 0 } end := i + match_distance + 1 if end > len(str2) { end = len(str2) } for k := start; k < end; k++ { if str2_matches[k] { continue } if str1[i] != str2[k] { continue } str1_matches[i] = true str2_matches[k] = true matches++ break } } if matches == 0 { return 0 } k := 0 for i := range str1 { if !str1_matches[i] { continue } for !str2_matches[k] { k++ } if str1[i] != str2[k] { transpositions++ } k++ } transpositions /= 2 return (matches/float64(len(str1)) + matches/float64(len(str2)) + (matches-transpositions)/matches) / 3 } func main() { fmt.Printf("%f\n", jaro("MARTHA", "MARHTA")) fmt.Printf("%f\n", jaro("DIXON", "DICKSONX")) fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")) }
#include <algorithm> #include <iostream> #include <string> double jaro(const std::string s1, const std::string s2) { const uint l1 = s1.length(), l2 = s2.length(); if (l1 == 0) return l2 == 0 ? 1.0 : 0.0; const uint match_distance = std::max(l1, l2) / 2 - 1; bool s1_matches[l1]; bool s2_matches[l2]; std::fill(s1_matches, s1_matches + l1, false); std::fill(s2_matches, s2_matches + l2, false); uint matches = 0; for (uint i = 0; i < l1; i++) { const int end = std::min(i + match_distance + 1, l2); for (int k = std::max(0u, i - match_distance); k < end; k++) if (!s2_matches[k] && s1[i] == s2[k]) { s1_matches[i] = true; s2_matches[k] = true; matches++; break; } } if (matches == 0) return 0.0; double t = 0.0; uint k = 0; for (uint i = 0; i < l1; i++) if (s1_matches[i]) { while (!s2_matches[k]) k++; if (s1[i] != s2[k]) t += 0.5; k++; } const double m = matches; return (m / l1 + m / l2 + (m - t) / m) / 3.0; } int main() { using namespace std; cout << jaro("MARTHA", "MARHTA") << endl; cout << jaro("DIXON", "DICKSONX") << endl; cout << jaro("JELLYFISH", "SMELLYFISH") << endl; return 0; }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all) var sPairs []pair pairs: for _, p := range all { s := p.x + p.y for a := 2; a < s/2+s&1; a++ { b := s - a if products[a*b] == 1 { continue pairs } } sPairs = append(sPairs, p) } fmt.Println("S starts with", len(sPairs), "possible pairs.") sProducts := countProducts(sPairs) var pPairs []pair for _, p := range sPairs { if sProducts[p.x*p.y] == 1 { pPairs = append(pPairs, p) } } fmt.Println("P then has", len(pPairs), "possible pairs.") pSums := countSums(pPairs) var final []pair for _, p := range pPairs { if pSums[p.x+p.y] == 1 { final = append(final, p) } } switch len(final) { case 1: fmt.Println("Answer:", final[0].x, "and", final[0].y) case 0: fmt.Println("No possible answer.") default: fmt.Println(len(final), "possible answers:", final) } } func countProducts(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x*p.y]++ } return m } func countSums(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x+p.y]++ } return m } func decomposeSum(s int) []pair { pairs := make([]pair, 0, s/2) for a := 2; a < s/2+s&1; a++ { pairs = append(pairs, pair{a, s - a}) } return pairs }
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod; } return os << '\n'; } void print_count(const std::vector<std::pair<int, int>> &candidates) { auto c = candidates.size(); if (c == 0) { std::cout << "no candidates\n"; } else if (c == 1) { std::cout << "one candidate\n"; } else { std::cout << c << " candidates\n"; } } auto setup() { std::vector<std::pair<int, int>> candidates; for (int x = 2; x <= 98; x++) { for (int y = x + 1; y <= 98; y++) { if (x + y <= 100) { candidates.push_back(std::make_pair(x, y)); } } } return candidates; } void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [sum](const std::pair<int, int> &pair) { auto s = pair.first + pair.second; return s == sum; } ), candidates.end()); } void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [prod](const std::pair<int, int> &pair) { auto p = pair.first * pair.second; return p == prod; } ), candidates.end()); } void statement1(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] == 1) { auto sum = pair.first + pair.second; remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } void statement2(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] > 1) { remove_by_prod(candidates, prod); loop = true; break; } } } while (loop); } void statement3(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto sum = pair.first + pair.second; uniqueMap[sum]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto sum = pair.first + pair.second; if (uniqueMap[sum] > 1) { remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } int main() { auto candidates = setup(); print_count(candidates); statement1(candidates); print_count(candidates); statement2(candidates); print_count(candidates); statement3(candidates); print_count(candidates); std::cout << candidates; return 0; }
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically?
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all) var sPairs []pair pairs: for _, p := range all { s := p.x + p.y for a := 2; a < s/2+s&1; a++ { b := s - a if products[a*b] == 1 { continue pairs } } sPairs = append(sPairs, p) } fmt.Println("S starts with", len(sPairs), "possible pairs.") sProducts := countProducts(sPairs) var pPairs []pair for _, p := range sPairs { if sProducts[p.x*p.y] == 1 { pPairs = append(pPairs, p) } } fmt.Println("P then has", len(pPairs), "possible pairs.") pSums := countSums(pPairs) var final []pair for _, p := range pPairs { if pSums[p.x+p.y] == 1 { final = append(final, p) } } switch len(final) { case 1: fmt.Println("Answer:", final[0].x, "and", final[0].y) case 0: fmt.Println("No possible answer.") default: fmt.Println(len(final), "possible answers:", final) } } func countProducts(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x*p.y]++ } return m } func countSums(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x+p.y]++ } return m } func decomposeSum(s int) []pair { pairs := make([]pair, 0, s/2) for a := 2; a < s/2+s&1; a++ { pairs = append(pairs, pair{a, s - a}) } return pairs }
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod; } return os << '\n'; } void print_count(const std::vector<std::pair<int, int>> &candidates) { auto c = candidates.size(); if (c == 0) { std::cout << "no candidates\n"; } else if (c == 1) { std::cout << "one candidate\n"; } else { std::cout << c << " candidates\n"; } } auto setup() { std::vector<std::pair<int, int>> candidates; for (int x = 2; x <= 98; x++) { for (int y = x + 1; y <= 98; y++) { if (x + y <= 100) { candidates.push_back(std::make_pair(x, y)); } } } return candidates; } void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [sum](const std::pair<int, int> &pair) { auto s = pair.first + pair.second; return s == sum; } ), candidates.end()); } void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [prod](const std::pair<int, int> &pair) { auto p = pair.first * pair.second; return p == prod; } ), candidates.end()); } void statement1(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] == 1) { auto sum = pair.first + pair.second; remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } void statement2(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] > 1) { remove_by_prod(candidates, prod); loop = true; break; } } } while (loop); } void statement3(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto sum = pair.first + pair.second; uniqueMap[sum]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto sum = pair.first + pair.second; if (uniqueMap[sum] > 1) { remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } int main() { auto candidates = setup(); print_count(candidates); statement1(candidates); print_count(candidates); statement2(candidates); print_count(candidates); statement3(candidates); print_count(candidates); std::cout << candidates; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } return res } func turns(n int, fss []int) string { m := make(map[int]int) for _, fs := range fss { m[fs]++ } m2 := make(map[int]int) for _, v := range m { m2[v]++ } res := []int{} sum := 0 for k, v := range m2 { sum += v res = append(res, k) } if sum != n { return fmt.Sprintf("only %d have a turn", sum) } sort.Ints(res) res2 := make([]string, len(res)) for i := range res { res2[i] = strconv.Itoa(res[i]) } return strings.Join(res2, " or ") } func main() { for _, base := range []int{2, 3, 5, 11} { fmt.Printf("%2d : %2d\n", base, fairshare(25, base)) } fmt.Println("\nHow many times does each get a turn in 50000 iterations?") for _, base := range []int{191, 1377, 49999, 50000, 50001} { t := turns(base, fairshare(50000, base)) fmt.Printf(" With %d people: %s\n", base, t) } }
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { std::vector<int> cnt(base, 0); for (int i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } int minTurn = INT_MAX; int maxTurn = INT_MIN; int portion = 0; for (int i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
Write the same code in C++ as shown below in Go.
package main import ( "fmt" "math/rand" "strings" "time" ) var cylinder = [6]bool{} func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t } func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } func load() { for cylinder[0] { rshift() } cylinder[0] = true rshift() } func spin() { var lim = 1 + rand.Intn(6) for i := 1; i < lim; i++ { rshift() } } func fire() bool { shot := cylinder[0] rshift() return shot } func method(s string) int { unload() for _, c := range s { switch c { case 'L': load() case 'S': spin() case 'F': if fire() { return 1 } } } return 0 } func mstring(s string) string { var l []string for _, c := range s { switch c { case 'L': l = append(l, "load") case 'S': l = append(l, "spin") case 'F': l = append(l, "fire") } } return strings.Join(l, ", ") } func main() { rand.Seed(time.Now().UnixNano()) tests := 100000 for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} { sum := 0 for t := 1; t <= tests; t++ { sum += method(m) } pc := float64(sum) * 100 / float64(tests) fmt.Printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc) } }
#include <array> #include <iomanip> #include <iostream> #include <random> #include <sstream> class Roulette { private: std::array<bool, 6> cylinder; std::mt19937 gen; std::uniform_int_distribution<> distrib; int next_int() { return distrib(gen); } void rshift() { std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end()); } void unload() { std::fill(cylinder.begin(), cylinder.end(), false); } void load() { while (cylinder[0]) { rshift(); } cylinder[0] = true; rshift(); } void spin() { int lim = next_int(); for (int i = 1; i < lim; i++) { rshift(); } } bool fire() { auto shot = cylinder[0]; rshift(); return shot; } public: Roulette() { std::random_device rd; gen = std::mt19937(rd()); distrib = std::uniform_int_distribution<>(1, 6); unload(); } int method(const std::string &s) { unload(); for (auto c : s) { switch (c) { case 'L': load(); break; case 'S': spin(); break; case 'F': if (fire()) { return 1; } break; } } return 0; } }; std::string mstring(const std::string &s) { std::stringstream ss; bool first = true; auto append = [&ss, &first](const std::string s) { if (first) { first = false; } else { ss << ", "; } ss << s; }; for (auto c : s) { switch (c) { case 'L': append("load"); break; case 'S': append("spin"); break; case 'F': append("fire"); break; } } return ss.str(); } void test(const std::string &src) { const int tests = 100000; int sum = 0; Roulette r; for (int t = 0; t < tests; t++) { sum += r.method(src); } double pc = 100.0 * sum / tests; std::cout << std::left << std::setw(40) << mstring(src) << " produces " << pc << "% deaths.\n"; } int main() { test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF"); return 0; }
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) case ")": var op string for { op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break } rpn += " " + op } default: if o1, isOp := opa[tok]; isOp { for len(stack) > 0 { op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } stack = stack[:len(stack)-1] rpn += " " + op } stack = append(stack, tok) } else { if rpn > "" { rpn += " " } rpn += tok } } } for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return std::runtime_error( (std::ostringstream{} << ... << args).str() ); }; template <typename T> struct stack : public std::vector <T> { using base_type = std::vector <T> ; T push ( const T& x ) { base_type::push_back( x ); return x; } const T& top () { return base_type::back(); } T pop () { T x = std::move( top() ); base_type::pop_back(); return x; } bool empty() { return base_type::empty(); } }; using Number = double; using Operator_Name = string; using Precedence = int; enum class Associates { none, left_to_right, right_to_left }; struct Operator_Info { Precedence precedence; Associates associativity; }; std::unordered_map <Operator_Name, Operator_Info> Operators = { { "^", { 4, Associates::right_to_left } }, { "*", { 3, Associates::left_to_right } }, { "/", { 3, Associates::left_to_right } }, { "+", { 2, Associates::left_to_right } }, { "-", { 2, Associates::left_to_right } }, }; Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; } Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; } using Token = string; bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); } bool is_operator ( const Token& t ) { return Operators.count( t ); } bool is_open_parenthesis ( const Token& t ) { return t == "("; } bool is_close_parenthesis( const Token& t ) { return t == ")"; } bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); } template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs ) { std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs; } #include <iomanip> struct Progressive_Display { string token_name; string token_type; Progressive_Display() { std::cout << "\n" " INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n" "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n"; } Progressive_Display& operator () ( const Token& token ) { token_name = token; token_type = is_operator ( token ) ? "op" : is_parenthesis( token ) ? "()" : is_number ( token ) ? "num" : ""; return *this; } Progressive_Display& operator () ( const string & description, const stack <Token> & stack, const vector <Token> & output ) { std::cout << std::right << std::setw( 7 ) << token_name << " │ " << std::left << std::setw( 4 ) << token_type << " │ " << std::setw( 16 ) << description << " │ " << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ " << output << "\n"; return operator () ( "" ); } }; vector <Token> parse( const vector <Token> & tokens ) { vector <Token> output; stack <Token> stack; Progressive_Display display; for (auto token : tokens) if (is_number( token )) { output.push_back( token ); display( token )( "num --> output", stack, output ); } else if (is_operator( token ) or is_parenthesis( token )) { display( token ); if (!is_open_parenthesis( token )) { while (!stack.empty() and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() )) or (precedence( stack.top() ) > precedence( token )) or ( (precedence( stack.top() ) == precedence( token )) and (associativity( token ) == Associates::left_to_right)))) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } if (is_close_parenthesis( token )) { stack.pop(); display( "pop", stack, output ); } } if (!is_close_parenthesis( token )) { stack.push( token ); display( "push op", stack, output ); } } else throw error( "unexpected token: ", token ); display( "END" ); while (!stack.empty()) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } return output; } int main( int argc, char** argv ) try { auto tokens = vector <Token> ( argv+1, argv+argc ); auto rpn_expr = parse( tokens ); std::cout << "\nInfix = " << tokens << "\nRPN = " << rpn_expr << "\n"; } catch (std::exception e) { std::cerr << "error: " << e.what() << "\n"; return 1; }
Please provide an equivalent version of this Go code in C++.
package main import "fmt" var canFollow [][]bool var arrang []int var bFirst = true var pmap = make(map[int]bool) func init() { for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} { pmap[i] = true } } func ptrs(res, n, done int) int { ad := arrang[done-1] if n-done <= 1 { if canFollow[ad-1][n-1] { if bFirst { for _, e := range arrang { fmt.Printf("%2d ", e) } fmt.Println() bFirst = false } res++ } } else { done++ for i := done - 1; i <= n-2; i += 2 { ai := arrang[i] if canFollow[ad-1][ai-1] { arrang[i], arrang[done-1] = arrang[done-1], arrang[i] res = ptrs(res, n, done) arrang[i], arrang[done-1] = arrang[done-1], arrang[i] } } } return res } func primeTriangle(n int) int { canFollow = make([][]bool, n) for i := 0; i < n; i++ { canFollow[i] = make([]bool, n) for j := 0; j < n; j++ { _, ok := pmap[i+j+2] canFollow[i][j] = ok } } bFirst = true arrang = make([]int, n) for i := 0; i < n; i++ { arrang[i] = i + 1 } return ptrs(0, n, 1) } func main() { counts := make([]int, 19) for i := 2; i <= 20; i++ { counts[i-2] = primeTriangle(i) } fmt.Println() for i := 0; i < 19; i++ { fmt.Printf("%d ", counts[i]) } fmt.Println() }
#include <cassert> #include <chrono> #include <iomanip> #include <iostream> #include <numeric> #include <vector> bool is_prime(unsigned int n) { assert(n > 0 && n < 64); return (1ULL << n) & 0x28208a20a08a28ac; } template <typename Iterator> bool prime_triangle_row(Iterator begin, Iterator end) { if (std::distance(begin, end) == 2) return is_prime(*begin + *(begin + 1)); for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); if (prime_triangle_row(begin + 1, end)) return true; std::iter_swap(i, begin + 1); } } return false; } template <typename Iterator> void prime_triangle_count(Iterator begin, Iterator end, int& count) { if (std::distance(begin, end) == 2) { if (is_prime(*begin + *(begin + 1))) ++count; return; } for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); prime_triangle_count(begin + 1, end, count); std::iter_swap(i, begin + 1); } } } template <typename Iterator> void print(Iterator begin, Iterator end) { if (begin == end) return; auto i = begin; std::cout << std::setw(2) << *i++; for (; i != end; ++i) std::cout << ' ' << std::setw(2) << *i; std::cout << '\n'; } int main() { auto start = std::chrono::high_resolution_clock::now(); for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); if (prime_triangle_row(v.begin(), v.end())) print(v.begin(), v.end()); } std::cout << '\n'; for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); int count = 0; prime_triangle_count(v.begin(), v.end(), count); if (n > 2) std::cout << ' '; std::cout << count; } std::cout << '\n'; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Write a version of this Go function in C++ with identical behavior.
package main import ( "fmt" "log" "math" ) func main() { fmt.Print("Enter 11 numbers: ") var s [11]float64 for i := 0; i < 11; { if n, _ := fmt.Scan(&s[i]); n > 0 { i++ } } for i, item := range s[:5] { s[i], s[10-i] = s[10-i], item } for _, item := range s { if result, overflow := f(item); overflow { log.Printf("f(%g) overflow", item) } else { fmt.Printf("f(%g) = %g\n", item, result) } } } func f(x float64) (float64, bool) { result := math.Sqrt(math.Abs(x)) + 5*x*x*x return result, result > 400 }
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> int main( ) { std::vector<double> input( 11 ) , results( 11 ) ; std::cout << "Please enter 11 numbers!\n" ; for ( int i = 0 ; i < input.size( ) ; i++ ) std::cin >> input[i]; std::transform( input.begin( ) , input.end( ) , results.begin( ) , [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; for ( int i = 10 ; i > -1 ; i-- ) { std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; if ( results[ i ] > 400 ) std::cout << "too large!" ; else std::cout << results[ i ] << " !" ; std::cout << std::endl ; } return 0 ; }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package m3 import ( "errors" "strconv" ) var ( ErrorLT3 = errors.New("N of at least three digits required.") ErrorEven = errors.New("N with odd number of digits required.") ) func Digits(i int) (string, error) { if i < 0 { i = -i } if i < 100 { return "", ErrorLT3 } s := strconv.Itoa(i) if len(s)%2 == 0 { return "", ErrorEven } m := len(s) / 2 return s[m-1 : m+2], nil }
#include <iostream> std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size(); if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } } int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}; for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }
Write a version of this Go function in C++ with identical behavior.
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if isPrime(i) { primes[count] = i count++ } } return primes } func countDivisors(n int) int { count := 1 for n%2 == 0 { n >>= 1 count++ } for d := 3; d*d <= n; d += 2 { q, r := n/d, n%d if r == 0 { dc := 0 for r == 0 { dc += count n = q q, r = n/d, n%d } count += dc } } if n != 1 { count *= 2 } return count } func main() { const max = 33 primes := generateSmallPrimes(max) z := new(big.Int) p := new(big.Int) fmt.Println("The first", max, "terms in the sequence are:") for i := 1; i <= max; i++ { if isPrime(i) { z.SetUint64(uint64(primes[i-1])) p.SetUint64(uint64(i - 1)) z.Exp(z, p, nil) fmt.Printf("%2d : %d\n", i, z) } else { count := 0 for j := 1; ; j++ { if i%2 == 1 { sq := int(math.Sqrt(float64(j))) if sq*sq != j { continue } } if countDivisors(j) == i { count++ if count == i { fmt.Printf("%2d : %d\n", i, j) break } } } } } }
#include <iostream> #include <vector> std::vector<int> smallPrimes; bool is_prime(size_t test) { if (test < 2) { return false; } if (test % 2 == 0) { return test == 2; } for (size_t d = 3; d * d <= test; d += 2) { if (test % d == 0) { return false; } } return true; } void init_small_primes(size_t numPrimes) { smallPrimes.push_back(2); int count = 0; for (size_t n = 3; count < numPrimes; n += 2) { if (is_prime(n)) { smallPrimes.push_back(n); count++; } } } size_t divisor_count(size_t n) { size_t count = 1; while (n % 2 == 0) { n /= 2; count++; } for (size_t d = 3; d * d <= n; d += 2) { size_t q = n / d; size_t r = n % d; size_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { count *= 2; } return count; } uint64_t OEISA073916(size_t n) { if (is_prime(n)) { return (uint64_t) pow(smallPrimes[n - 1], n - 1); } size_t count = 0; uint64_t result = 0; for (size_t i = 1; count < n; i++) { if (n % 2 == 1) { size_t root = (size_t) sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { const int MAX = 15; init_small_primes(MAX); for (size_t n = 1; n <= MAX; n++) { if (n == 13) { std::cout << "A073916(" << n << ") = One more bit needed to represent result.\n"; } else { std::cout << "A073916(" << n << ") = " << OEISA073916(n) << '\n'; } } return 0; }
Translate this program into C++ but keep the logic exactly as in Go.
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 seq := make([]int, max) fmt.Println("The first", max, "terms of the sequence are:") for i, n := 1, 0; n < max; i++ { if k := countDivisors(i); k <= max && seq[k-1] == 0 { seq[k-1] = i n++ } } fmt.Println(seq) }
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; cout << "The first " << MAX << " terms of the sequence are:" << endl; for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) cout << seq[i] << " "; cout << endl; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) = %2d ", n, pancake(n)) } fmt.Println() } }
#include <iomanip> #include <iostream> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = i * 5 + j; std::cout << "p(" << std::setw(2) << n << ") = " << std::setw(2) << pancake(n) << " "; } std::cout << '\n'; } return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) placePieces("RNBQBNR", false) placePieces("rnbqbnr", false) return toFen() } func placeKings() { for { r1 := rand.Intn(8) c1 := rand.Intn(8) r2 := rand.Intn(8) c2 := rand.Intn(8) if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 { grid[r1][c1] = 'K' grid[r2][c2] = 'k' return } } } func placePieces(pieces string, isPawn bool) { numToPlace := rand.Intn(len(pieces)) for n := 0; n < numToPlace; n++ { var r, c int for { r = rand.Intn(8) c = rand.Intn(8) if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) { break } } grid[r][c] = pieces[n] } } func toFen() string { var fen strings.Builder countEmpty := 0 for r := 0; r < 8; r++ { for c := 0; c < 8; c++ { ch := grid[r][c] if ch == '\000' { ch = '.' } fmt.Printf("%2c ", ch) if ch == '.' { countEmpty++ } else { if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteByte(ch) } } if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteString("/") fmt.Println() } fen.WriteString(" w - - 0 1") return fen.String() } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(createFen()) }
#include <ctime> #include <iostream> #include <string> #include <algorithm> class chessBoard { public: void generateRNDBoard( int brds ) { int a, b, i; char c; for( int cc = 0; cc < brds; cc++ ) { memset( brd, 0, 64 ); std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk"; random_shuffle( pieces.begin(), pieces.end() ); while( pieces.length() ) { i = rand() % pieces.length(); c = pieces.at( i ); while( true ) { a = rand() % 8; b = rand() % 8; if( brd[a][b] == 0 ) { if( c == 'P' && !b || c == 'p' && b == 7 || ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue; break; } } brd[a][b] = c; pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 ); } print(); } } private: bool search( char c, int a, int b ) { for( int y = -1; y < 2; y++ ) { for( int x = -1; x < 2; x++ ) { if( !x && !y ) continue; if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) { if( brd[a + x][b + y] == c ) return true; } } } return false; } void print() { int e = 0; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) e++; else { if( e > 0 ) { std::cout << e; e = 0; } std::cout << brd[x][y]; } } if( e > 0 ) { std::cout << e; e = 0; } if( y < 7 ) std::cout << "/"; } std::cout << " w - - 0 1\n\n"; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) std::cout << "."; else std::cout << brd[x][y]; } std::cout << "\n"; } std::cout << "\n\n"; } char brd[8][8]; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); chessBoard c; c.generateRNDBoard( 2 ); return 0; }
Write a version of this Go function in C++ with identical behavior.
package main import ( "fmt" "strconv" ) func uabs(a, b uint64) uint64 { if a > b { return a - b } return b - a } func isEsthetic(n, b uint64) bool { if n == 0 { return false } i := n % b n /= b for n > 0 { j := n % b if uabs(i, j) != 1 { return false } n /= b i = j } return true } var esths []uint64 func dfs(n, m, i uint64) { if i >= n && i <= m { esths = append(esths, i) } if i == 0 || i > m { return } d := i % 10 i1 := i*10 + d - 1 i2 := i1 + 2 if d == 0 { dfs(n, m, i2) } else if d == 9 { dfs(n, m, i1) } else { dfs(n, m, i1) dfs(n, m, i2) } } func listEsths(n, n2, m, m2 uint64, perLine int, all bool) { esths = esths[:0] for i := uint64(0); i < 10; i++ { dfs(n2, m2, i) } le := len(esths) fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n", commatize(uint64(le)), commatize(n), commatize(m)) if all { for c, esth := range esths { fmt.Printf("%d ", esth) if (c+1)%perLine == 0 { fmt.Println() } } } else { for i := 0; i < perLine; i++ { fmt.Printf("%d ", esths[i]) } fmt.Println("\n............\n") for i := le - perLine; i < le; i++ { fmt.Printf("%d ", esths[i]) } } fmt.Println("\n") } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { for b := uint64(2); b <= 16; b++ { fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b) for n, c := uint64(1), uint64(0); c < 6*b; n++ { if isEsthetic(n, b) { c++ if c >= 4*b { fmt.Printf("%s ", strconv.FormatUint(n, int(b))) } } } fmt.Println("\n") } listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true) listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false) listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false) listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false) }
#include <functional> #include <iostream> #include <sstream> #include <vector> std::string to(int n, int b) { static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::stringstream ss; while (n > 0) { auto rem = n % b; n = n / b; ss << BASE[rem]; } auto fwd = ss.str(); return std::string(fwd.rbegin(), fwd.rend()); } uint64_t uabs(uint64_t a, uint64_t b) { if (a < b) { return b - a; } return a - b; } bool isEsthetic(uint64_t n, uint64_t b) { if (n == 0) { return false; } auto i = n % b; n /= b; while (n > 0) { auto j = n % b; if (uabs(i, j) != 1) { return false; } n /= b; i = j; } return true; } void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) { std::vector<uint64_t> esths; const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) { auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) { if (i >= n && i <= m) { esths.push_back(i); } if (i == 0 || i > m) { return; } auto d = i % 10; auto i1 = i * 10 + d - 1; auto i2 = i1 + 2; if (d == 0) { dfs_ref(n, m, i2, dfs_ref); } else if (d == 9) { dfs_ref(n, m, i1, dfs_ref); } else { dfs_ref(n, m, i1, dfs_ref); dfs_ref(n, m, i2, dfs_ref); } }; dfs_impl(n, m, i, dfs_impl); }; for (int i = 0; i < 10; i++) { dfs(n2, m2, i); } auto le = esths.size(); printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m); if (all) { for (size_t c = 0; c < esths.size(); c++) { auto esth = esths[c]; printf("%llu ", esth); if ((c + 1) % perLine == 0) { printf("\n"); } } printf("\n"); } else { for (int c = 0; c < perLine; c++) { auto esth = esths[c]; printf("%llu ", esth); } printf("\n............\n"); for (size_t i = le - perLine; i < le; i++) { auto esth = esths[i]; printf("%llu ", esth); } printf("\n"); } printf("\n"); } int main() { for (int b = 2; b <= 16; b++) { printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b); for (int n = 1, c = 0; c < 6 * b; n++) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { std::cout << to(n, b) << ' '; } } } printf("\n"); } printf("\n"); listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true); listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false); listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false); listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Go code.
package main import "fmt" const ( maxn = 10 maxl = 50 ) func main() { for i := 1; i <= maxn; i++ { fmt.Printf("%d: %d\n", i, steps(i)) } } func steps(n int) int { var a, b [maxl][maxn + 1]int var x [maxl]int a[0][0] = 1 var m int for l := 0; ; { x[l]++ k := int(x[l]) if k >= n { if l <= 0 { break } l-- continue } if a[l][k] == 0 { if b[l][k+1] != 0 { continue } } else if a[l][k] != k+1 { continue } a[l+1] = a[l] for j := 1; j <= k; j++ { a[l+1][j] = a[l][k-j] } b[l+1] = b[l] a[l+1][0] = k + 1 b[l+1][k+1] = 1 if l > m-1 { m = l + 1 } l++ x[l] = 0 } return m }
#include <iostream> #include <vector> #include <numeric> #include <algorithm> int topswops(int n) { std::vector<int> list(n); std::iota(std::begin(list), std::end(list), 1); int max_steps = 0; do { auto temp_list = list; for (int steps = 1; temp_list[0] != 1; ++steps) { std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]); if (steps > max_steps) max_steps = steps; } } while (std::next_permutation(std::begin(list), std::end(list))); return max_steps; } int main() { for (int i = 1; i <= 10; ++i) { std::cout << i << ": " << topswops(i) << std::endl; } return 0; }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000, } scanner := bufio.NewScanner(os.Stdin) for { for i, u := range units { fmt.Printf("%2d %s\n", i+1, u) } fmt.Println() var unit int var err error for { fmt.Print("Please choose a unit 1 to 13 : ") scanner.Scan() unit, err = strconv.Atoi(scanner.Text()) if err == nil && unit >= 1 && unit <= 13 { break } } unit-- var value float64 for { fmt.Print("Now enter a value in that unit : ") scanner.Scan() value, err = strconv.ParseFloat(scanner.Text(), 32) if err == nil && value >= 0 { break } } fmt.Println("\nThe equivalent in the remaining units is:\n") for i, u := range units { if i == unit { continue } fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i]) } fmt.Println() yn := "" for yn != "y" && yn != "n" { fmt.Print("Do another one y/n : ") scanner.Scan() yn = strings.ToLower(scanner.Text()) } if yn == "n" { return } } }
#include <iostream> #include <iomanip> using namespace std; class ormConverter { public: ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ), MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {} void convert( char c, float l ) { system( "cls" ); cout << endl << l; switch( c ) { case 'A': cout << " Arshin to:"; l *= AR; break; case 'C': cout << " Centimeter to:"; l *= CE; break; case 'D': cout << " Diuym to:"; l *= DI; break; case 'F': cout << " Fut to:"; l *= FU; break; case 'K': cout << " Kilometer to:"; l *= KI; break; case 'L': cout << " Liniya to:"; l *= LI; break; case 'M': cout << " Meter to:"; l *= ME; break; case 'I': cout << " Milia to:"; l *= MI; break; case 'P': cout << " Piad to:"; l *= PI; break; case 'S': cout << " Sazhen to:"; l *= SA; break; case 'T': cout << " Tochka to:"; l *= TO; break; case 'V': cout << " Vershok to:"; l *= VE; break; case 'E': cout << " Versta to:"; l *= VR; } float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME, mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR; cout << left << endl << "=================" << endl << setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl << setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl << setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl << setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl << setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl << setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl << setw( 12 ) << "Versta:" << vr << endl << endl << endl; } private: const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR; }; int _tmain(int argc, _TCHAR* argv[]) { ormConverter c; char s; float l; while( true ) { cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n"; cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0; cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0; c.convert( s, l ); system( "pause" ); system( "cls" ); } return 0; }
Produce a language-to-language conversion: from Go to C++, same semantics.
package main import ( "fmt" "math/rand" "time" ) type rateStateS struct { lastFlush time.Time period time.Duration tickCount int } func ticRate(pRate *rateStateS) { pRate.tickCount++ now := time.Now() if now.Sub(pRate.lastFlush) >= pRate.period { tps := 0. if pRate.tickCount > 0 { tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds() } fmt.Println(tps, "tics per second.") pRate.tickCount = 0 pRate.lastFlush = now } } func somethingWeDo() { time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) } func main() { start := time.Now() rateWatch := rateStateS{ lastFlush: start, period: 5 * time.Second, } latest := start for latest.Sub(start) < 20*time.Second { somethingWeDo() ticRate(&rateWatch) latest = time.Now() } }
#include <iostream> #include <ctime> class CRateState { protected: time_t m_lastFlush; time_t m_period; size_t m_tickCount; public: CRateState(time_t period); void Tick(); }; CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)), m_period(period), m_tickCount(0) { } void CRateState::Tick() { m_tickCount++; time_t now = std::time(NULL); if((now - m_lastFlush) >= m_period) { size_t tps = 0.0; if(m_tickCount > 0) tps = m_tickCount / (now - m_lastFlush); std::cout << tps << " tics per second" << std::endl; m_tickCount = 0; m_lastFlush = now; } } void something_we_do() { volatile size_t anchor = 0; for(size_t x = 0; x < 0xffff; ++x) { anchor = x; } } int main() { time_t start = std::time(NULL); CRateState rateWatch(5); for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL)) { something_we_do(); rateWatch.Tick(); } return 0; }
Translate this program into C++ but keep the logic exactly as in Go.
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 fmt.Println("The first", max, "terms of the sequence are:") for i, next := 1, 1; next <= max; i++ { if next == countDivisors(i) { fmt.Printf("%d ", i) next++ } } fmt.Println() }
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { cout << "The first " << MAX << " terms of the sequence are:" << endl; for (int i = 1, next = 1; next <= MAX; ++i) { if (next == count_divisors(i)) { cout << i << " "; next++; } } cout << 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" "math/big" "strings" ) func padovanRecur(n int) []int { p := make([]int, n) p[0], p[1], p[2] = 1, 1, 1 for i := 3; i < n; i++ { p[i] = p[i-2] + p[i-3] } return p } func padovanFloor(n int) []int { var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat) p, _ = p.SetString("1.324717957244746025960908854") s, _ = s.SetString("1.0453567932525329623") f := make([]int, n) pow := new(big.Rat).SetInt64(1) u = u.SetFrac64(1, 2) t.Quo(pow, p) t.Quo(t, s) t.Add(t, u) v, _ := t.Float64() f[0] = int(math.Floor(v)) for i := 1; i < n; i++ { t.Quo(pow, s) t.Add(t, u) v, _ = t.Float64() f[i] = int(math.Floor(v)) pow.Mul(pow, p) } return f } type LSystem struct { rules map[string]string init, current string } func step(lsys *LSystem) string { var sb strings.Builder if lsys.current == "" { lsys.current = lsys.init } else { for _, c := range lsys.current { sb.WriteString(lsys.rules[string(c)]) } lsys.current = sb.String() } return lsys.current } func padovanLSys(n int) []string { rules := map[string]string{"A": "B", "B": "C", "C": "AB"} lsys := &LSystem{rules, "A", ""} p := make([]string, n) for i := 0; i < n; i++ { p[i] = step(lsys) } return p } func areSame(l1, l2 []int) bool { for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { fmt.Println("First 20 members of the Padovan sequence:") fmt.Println(padovanRecur(20)) recur := padovanRecur(64) floor := padovanFloor(64) same := areSame(recur, floor) s := "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.") p := padovanLSys(32) lsyst := make([]int, 32) for i := 0; i < 32; i++ { lsyst[i] = len(p[i]) } fmt.Println("\nFirst 10 members of the Padovan L-System:") fmt.Println(p[:10]) fmt.Println("\nand their lengths:") fmt.Println(lsyst[:10]) same = areSame(recur[:32], lsyst) s = "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
#include <iostream> #include <map> #include <cmath> int pRec(int n) { static std::map<int,int> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n <= 2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); return memo[n]; } int pFloor(int n) { long const double p = 1.324717957244746025960908854; long const double s = 1.0453567932525329623; return std::pow(p, n-1)/s + 0.5; } std::string& lSystem(int n) { static std::map<int,std::string> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n == 0) memo[n] = "A"; else { memo[n] = ""; for (char ch : memo[n-1]) { switch(ch) { case 'A': memo[n].push_back('B'); break; case 'B': memo[n].push_back('C'); break; case 'C': memo[n].append("AB"); break; } } } return memo[n]; } using pFn = int(*)(int); void compare(pFn f1, pFn f2, const char* descr, int stop) { std::cout << "The " << descr << " functions "; int i; for (i=0; i<stop; i++) { int n1 = f1(i); int n2 = f2(i); if (n1 != n2) { std::cout << "do not match at " << i << ": " << n1 << " != " << n2 << ".\n"; break; } } if (i == stop) { std::cout << "match from P_0 to P_" << stop << ".\n"; } } int main() { std::cout << "P_0 .. P_19: "; for (int i=0; i<20; i++) std::cout << pRec(i) << " "; std::cout << "\n"; compare(pFloor, pRec, "floor- and recurrence-based", 64); std::cout << "\nThe first 10 L-system strings are:\n"; for (int i=0; i<10; i++) std::cout << lSystem(i) << "\n"; std::cout << "\n"; compare(pFloor, [](int n){return (int)lSystem(n).length();}, "floor- and L-system-based", 32); return 0; }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import ( "image" "image/color" "image/draw" "image/png" "log" "os" ) const ( width, height = 800, 600 maxDepth = 11 colFactor = uint8(255 / maxDepth) fileName = "pythagorasTree.png" ) func main() { img := image.NewNRGBA(image.Rect(0, 0, width, height)) bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) drawSquares(340, 550, 460, 550, img, 0) imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close() if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } } func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) { if depth > maxDepth { return } dx, dy := bx-ax, ay-by x3, y3 := bx-dy, by-dx x4, y4 := ax-dy, ay-dx x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2 col := color.RGBA{0, uint8(depth) * colFactor, 0, 255} drawLine(ax, ay, bx, by, img, col) drawLine(bx, by, x3, y3, img, col) drawLine(x3, y3, x4, y4, img, col) drawLine(x4, y4, ax, ay, img, col) drawSquares(x4, y4, x5, y5, img, depth+1) drawSquares(x5, y5, x3, y3, img, depth+1) } func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) { dx := abs(x1 - x0) dy := abs(y1 - y0) var sx, sy int = -1, -1 if x0 < x1 { sx = 1 } if y0 < y1 { sy = 1 } err := dx - dy for { img.Set(x0, y0, col) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 > -dy { err -= dy x0 += sx } if e2 < dx { err += dx y0 += sy } } } func abs(x int) int { if x < 0 { return -x } return x }
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } 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 tree { public: tree() { bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear(); clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 ); clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 ); clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 ); } void draw( int it, POINT a, POINT b ) { if( !it ) return; bmp.setPenColor( clr[it % 6] ); POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x }; POINT d = { a.x - df.y, a.y - df.x }; POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )}; drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c ); } void save( std::string p ) { bmp.saveBitmap( p ); } private: void drawSqr( POINT a, POINT b, POINT c, POINT d ) { HDC dc = bmp.getDC(); MoveToEx( dc, a.x, a.y, NULL ); LineTo( dc, b.x, b.y ); LineTo( dc, c.x, c.y ); LineTo( dc, d.x, d.y ); LineTo( dc, a.x, a.y ); } myBitmap bmp; DWORD clr[6]; }; int main( int argc, char* argv[] ) { POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER }, ptB = { ptA.x + LINE_LEN, ptA.y }; tree t; t.draw( 12, ptA, ptB ); t.save( "?:/pt.bmp" ); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
package main import ( "bytes" "fmt" "io" "os" "unicode" ) func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() } func owp(dst io.Writer, src io.Reader) { byte_in := func () byte { bs := make([]byte, 1) src.Read(bs) return bs[0] } byte_out := func (b byte) { dst.Write([]byte{b}) } var odd func() byte odd = func() byte { s := byte_in() if unicode.IsPunct(rune(s)) { return s } b := odd() byte_out(s) return b } for { for { b := byte_in() byte_out(b) if b == '.' { return } if unicode.IsPunct(rune(b)) { break } } b := odd() byte_out(b) if b == '.' { return } } }
#include <iostream> #include <cctype> #include <functional> using namespace std; bool odd() { function<void ()> prev = []{}; while(true) { int c = cin.get(); if (!isalpha(c)) { prev(); cout.put(c); return c != '.'; } prev = [=] { cout.put(c); prev(); }; } } bool even() { while(true) { int c; cout.put(c = cin.get()); if (!isalpha(c)) return c != '.'; } } int main() { bool e = false; while( e ? odd() : even() ) e = !e; return 0; }
Convert this Go block to C++, preserving its control flow and logic.
package main import ( "bytes" "fmt" "io" "os" "unicode" ) func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() } func owp(dst io.Writer, src io.Reader) { byte_in := func () byte { bs := make([]byte, 1) src.Read(bs) return bs[0] } byte_out := func (b byte) { dst.Write([]byte{b}) } var odd func() byte odd = func() byte { s := byte_in() if unicode.IsPunct(rune(s)) { return s } b := odd() byte_out(s) return b } for { for { b := byte_in() byte_out(b) if b == '.' { return } if unicode.IsPunct(rune(b)) { break } } b := odd() byte_out(b) if b == '.' { return } } }
#include <iostream> #include <cctype> #include <functional> using namespace std; bool odd() { function<void ()> prev = []{}; while(true) { int c = cin.get(); if (!isalpha(c)) { prev(); cout.put(c); return c != '.'; } prev = [=] { cout.put(c); prev(); }; } } bool even() { while(true) { int c; cout.put(c = cin.get()); if (!isalpha(c)) return c != '.'; } } int main() { bool e = false; while( e ? odd() : even() ) e = !e; return 0; }
Change the following Go code into C++ without altering its purpose.
package main import ( "fmt" "log" "math" ) var a1 = []int64{0, 1403580, -810728} var a2 = []int64{527612, 0, -1370589} const m1 = int64((1 << 32) - 209) const m2 = int64((1 << 32) - 22853) const d = m1 + 1 func mod(x, y int64) int64 { m := x % y if m < 0 { if y < 0 { return m - y } else { return m + y } } return m } type MRG32k3a struct{ x1, x2 [3]int64 } func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} } func (mrg *MRG32k3a) seed(seedState int64) { if seedState <= 0 || seedState >= d { log.Fatalf("Argument must be in the range [0, %d].\n", d) } mrg.x1 = [3]int64{seedState, 0, 0} mrg.x2 = [3]int64{seedState, 0, 0} } func (mrg *MRG32k3a) nextInt() int64 { x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1) x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2) mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} return mod(x1i-x2i, m1) + 1 } func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) } func main() { randomGen := MRG32k3aNew() randomGen.seed(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
#include <array> #include <iostream> int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } class RNG { private: const std::array<int64_t, 3> a1{ 0, 1403580, -810728 }; const int64_t m1 = (1LL << 32) - 209; std::array<int64_t, 3> x1; const std::array<int64_t, 3> a2{ 527612, 0, -1370589 }; const int64_t m2 = (1LL << 32) - 22853; std::array<int64_t, 3> x2; const int64_t d = (1LL << 32) - 209 + 1; public: void seed(int64_t state) { x1 = { state, 0, 0 }; x2 = { state, 0, 0 }; } int64_t next_int() { int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); int64_t z = mod(x1i - x2i, m1); x1 = { x1i, x1[0], x1[1] }; x2 = { x2i, x2[0], x2[1] }; return z + 1; } double next_float() { return static_cast<double>(next_int()) / d; } }; int main() { RNG rng; rng.seed(1234567); std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << '\n'; std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; rng.seed(987654321); for (size_t i = 0; i < 100000; i++) { auto value = floor(rng.next_float() * 5.0); counts[value]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; } return 0; }
Convert this Go block to C++, preserving its control flow and logic.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
import <iostream>;
Write the same algorithm in C++ as shown in this Go implementation.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
import <iostream>;
Translate the given Go code snippet into C++ without altering its behavior.
package main import ( "fmt" "sternbrocot" ) func main() { g := sb.Generator() fmt.Println("First 15:") for i := 1; i <= 15; i++ { fmt.Printf("%2d: %d\n", i, g()) } s := sb.New() fmt.Println("First 15:", s.FirstN(15)) for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} { fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x)) } fmt.Println("1-based indexes: gcd") for n, f := range s.FirstN(1000)[:999] { g := gcd(f, (*s)[n+1]) fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g) if g != 1 { panic("oh no!") return } } } func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x }
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
Generate an equivalent C++ version of this Go code.
package main import ( "fmt" "math" ) type unc struct { n float64 s float64 } func newUnc(n, s float64) *unc { return &unc{n, s * s} } func (z *unc) errorTerm() float64 { return math.Sqrt(z.s) } func (z *unc) addC(a *unc, c float64) *unc { *z = *a z.n += c return z } func (z *unc) subC(a *unc, c float64) *unc { *z = *a z.n -= c return z } func (z *unc) addU(a, b *unc) *unc { z.n = a.n + b.n z.s = a.s + b.s return z } func (z *unc) subU(a, b *unc) *unc { z.n = a.n - b.n z.s = a.s + b.s return z } func (z *unc) mulC(a *unc, c float64) *unc { z.n = a.n * c z.s = a.s * c * c return z } func (z *unc) divC(a *unc, c float64) *unc { z.n = a.n / c z.s = a.s / (c * c) return z } func (z *unc) mulU(a, b *unc) *unc { prod := a.n * b.n z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } func (z *unc) divU(a, b *unc) *unc { quot := a.n / b.n z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } func (z *unc) expC(a *unc, c float64) *unc { f := math.Pow(a.n, c) g := f * c / a.n z.n = f z.s = a.s * g * g return z } func main() { x1 := newUnc(100, 1.1) x2 := newUnc(200, 2.2) y1 := newUnc(50, 1.2) y2 := newUnc(100, 2.3) var d, d2 unc d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5) fmt.Println("d: ", d.n) fmt.Println("error:", d.errorTerm()) }
#pragma once #include <cmath> #include <string> #include <sstream> #include <iomanip> class Approx { public: Approx(double _v, double _s = 0.0) : v(_v), s(_s) {} operator std::string() const { std::ostringstream os(""); os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends; return os.str(); } Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); } Approx operator +(double d) const { return Approx(v + d, s); } Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); } Approx operator -(double d) const { return Approx(v - d, s); } Approx operator *(const Approx& a) const { const double t = v * a.v; return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); } Approx operator /(const Approx& a) const { const double t = v / a.v; return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); } Approx pow(double d) const { const double t = ::pow(v, d); return Approx(t, fabs(t * d * s / v)); } private: double v, s; };
Change the following Go code into C++ without altering its purpose.
package main import ( "fmt" "log" "os" "strconv" ) type tree uint64 var ( list []tree offset = [32]uint{1: 1} ) func add(t tree) { list = append(list, 1|t<<1) } func show(t tree, l uint) { for ; l > 0; t >>= 1 { l-- var paren byte if (t & 1) != 0 { paren = '(' } else { paren = ')' } fmt.Printf("%c", paren) } } func listTrees(n uint) { for i := offset[n]; i < offset[n+1]; i++ { show(list[i], n*2) fmt.Println() } } func assemble(n uint, t tree, sl, pos, rem uint) { if rem == 0 { add(t) return } if sl > rem { sl = rem pos = offset[sl] } else if pos >= offset[sl+1] { sl-- if sl == 0 { return } pos = offset[sl] } assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl) assemble(n, t, sl, pos+1, rem) } func mktrees(n uint) { if offset[n+1] > 0 { return } if n > 0 { mktrees(n - 1) } assemble(n, 0, n-1, offset[n-1], n-1) offset[n+1] = uint(len(list)) } func main() { if len(os.Args) != 2 { log.Fatal("There must be exactly 1 command line argument") } n, err := strconv.Atoi(os.Args[1]) if err != nil { log.Fatal("Argument is not a valid number") } if n <= 0 || n > 19 { n = 5 } add(0) mktrees(uint(n)) fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n]) listTrees(uint(n)) }
#include <iostream> #include <vector> std::vector<long> TREE_LIST; std::vector<int> OFFSET; void init() { for (size_t i = 0; i < 32; i++) { if (i == 1) { OFFSET.push_back(1); } else { OFFSET.push_back(0); } } } void append(long t) { TREE_LIST.push_back(1 | (t << 1)); } void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { std::cout << '('; } else { std::cout << ')'; } t = t >> 1; } } void listTrees(int n) { for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) { show(TREE_LIST[i], 2 * n); std::cout << '\n'; } } void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } auto pp = pos; auto ss = sl; if (sl > rem) { ss = rem; pp = OFFSET[ss]; } else if (pp >= OFFSET[ss + 1]) { ss--; if (ss == 0) { return; } pp = OFFSET[ss]; } assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } void makeTrees(int n) { if (OFFSET[n + 1] != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET[n - 1], n - 1); OFFSET[n + 1] = TREE_LIST.size(); } void test(int n) { if (n < 1 || n > 12) { throw std::runtime_error("Argument must be between 1 and 12"); } append(0); makeTrees(n); std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n'; listTrees(n); } int main() { init(); test(5); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Go code.
package main import ( "fmt" "strings" ) func lcs(a []string) string { le := len(a) if le == 0 { return "" } if le == 1 { return a[0] } le0 := len(a[0]) minLen := le0 for i := 1; i < le; i++ { if len(a[i]) < minLen { minLen = len(a[i]) } } if minLen == 0 { return "" } res := "" a1 := a[1:] for i := 1; i <= minLen; i++ { suffix := a[0][le0-i:] for _, e := range a1 { if !strings.HasSuffix(e, suffix) { return res } } res = suffix } return res } func main() { tests := [][]string{ {"baabababc", "baabc", "bbbabc"}, {"baabababc", "baabc", "bbbazc"}, {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, {"longest", "common", "suffix"}, {"suffix"}, {""}, } for _, test := range tests { fmt.Printf("%v -> \"%s\"\n", test, lcs(test)) } }
#include <iostream> #include <string> #include <vector> #include <algorithm> std::string lcs(const std::vector<std::string>& strs) { std::vector<std::string::const_reverse_iterator> backs; std::string s; if (strs.size() == 0) return ""; if (strs.size() == 1) return strs[0]; for (auto& str : strs) backs.push_back(str.crbegin()); while (backs[0] != strs[0].crend()) { char ch = *backs[0]++; for (std::size_t i = 1; i<strs.size(); i++) { if (backs[i] == strs[i].crend()) goto done; if (*backs[i] != ch) goto done; backs[i]++; } s.push_back(ch); } done: reverse(s.begin(), s.end()); return s; } void test(const std::vector<std::string>& strs) { std::cout << "["; for (std::size_t i = 0; i<strs.size(); i++) { std::cout << '"' << strs[i] << '"'; if (i != strs.size()-1) std::cout << ", "; } std::cout << "] -> `" << lcs(strs) << "`\n"; } int main() { std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"}; std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"}; std::vector<std::string> t3 = {"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"}; std::vector<std::string> t4 = {"longest", "common", "suffix"}; std::vector<std::string> t5 = {""}; std::vector<std::string> t6 = {}; std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"}; std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7}; for (auto t : tests) test(t); return 0; }
Port the following code from Go to C++ with equivalent syntax and logic.
package main import ( "fmt" "runtime" "sync" ) func main() { p := sync.Pool{New: func() interface{} { fmt.Println("pool empty") return new(int) }} i := new(int) j := new(int) *i = 1 *j = 2 fmt.Println(*i + *j) p.Put(i) p.Put(j) i = nil j = nil i = p.Get().(*int) j = p.Get().(*int) *i = 4 *j = 5 fmt.Println(*i + *j) p.Put(i) p.Put(j) i = nil j = nil runtime.GC() i = p.Get().(*int) j = p.Get().(*int) *i = 7 *j = 8 fmt.Println(*i + *j) }
T* foo = new(arena) T;
Produce a functionally identical C++ code for the snippet given in Go.
package main import ( "fmt" "runtime" "sync" ) func main() { p := sync.Pool{New: func() interface{} { fmt.Println("pool empty") return new(int) }} i := new(int) j := new(int) *i = 1 *j = 2 fmt.Println(*i + *j) p.Put(i) p.Put(j) i = nil j = nil i = p.Get().(*int) j = p.Get().(*int) *i = 4 *j = 5 fmt.Println(*i + *j) p.Put(i) p.Put(j) i = nil j = nil runtime.GC() i = p.Get().(*int) j = p.Get().(*int) *i = 7 *j = 8 fmt.Println(*i + *j) }
T* foo = new(arena) T;
Write the same code in C++ as shown below in Go.
package main import ( "fmt" "runtime" "sync" ) func main() { p := sync.Pool{New: func() interface{} { fmt.Println("pool empty") return new(int) }} i := new(int) j := new(int) *i = 1 *j = 2 fmt.Println(*i + *j) p.Put(i) p.Put(j) i = nil j = nil i = p.Get().(*int) j = p.Get().(*int) *i = 4 *j = 5 fmt.Println(*i + *j) p.Put(i) p.Put(j) i = nil j = nil runtime.GC() i = p.Get().(*int) j = p.Get().(*int) *i = 7 *j = 8 fmt.Println(*i + *j) }
T* foo = new(arena) T;
Please provide an equivalent version of this Go code in C++.
package main import ( "fmt" "log" ) func main() { m := [][]int{ {1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}, } if len(m) != len(m[0]) { log.Fatal("Matrix must be square.") } sum := 0 for i := 1; i < len(m); i++ { for j := 0; j < i; j++ { sum = sum + m[i][j] } } fmt.Println("Sum of elements below main diagonal is", sum) }
#include <iostream> #include <vector> template<typename T> T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) { T sum = 0; for (std::size_t y = 0; y < matrix.size(); y++) for (std::size_t x = 0; x < matrix[y].size() && x < y; x++) sum += matrix[y][x]; return sum; } int main() { std::vector<std::vector<int>> matrix = { {1,3,7,8,10}, {2,4,16,14,4}, {3,1,9,18,11}, {12,14,17,18,20}, {7,1,3,9,5} }; std::cout << sum_below_diagonal(matrix) << std::endl; return 0; }
Produce a language-to-language conversion: from Go to C++, same semantics.
package main import ( "bufio" "fmt" "os" ) func main() { f, err := os.Open("rc.fasta") if err != nil { fmt.Println(err) return } defer f.Close() s := bufio.NewScanner(f) headerFound := false for s.Scan() { line := s.Text() switch { case line == "": continue case line[0] != '>': if !headerFound { fmt.Println("missing header") return } fmt.Print(line) case headerFound: fmt.Println() fallthrough default: fmt.Printf("%s: ", line[1:]) headerFound = true } } if headerFound { fmt.Println() } if err := s.Err(); err != nil { fmt.Println(err) } }
#include <iostream> #include <fstream> int main( int argc, char **argv ){ if( argc <= 1 ){ std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl; return -1; } std::ifstream input(argv[1]); if(!input.good()){ std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl; return -1; } std::string line, name, content; while( std::getline( input, line ).good() ){ if( line.empty() || line[0] == '>' ){ if( !name.empty() ){ std::cout << name << " : " << content << std::endl; name.clear(); } if( !line.empty() ){ name = line.substr(1); } content.clear(); } else if( !name.empty() ){ if( line.find(' ') != std::string::npos ){ name.clear(); content.clear(); } else { content += line; } } } if( !name.empty() ){ std::cout << name << " : " << content << std::endl; } return 0; }
Preserve the algorithm and functionality while converting the code from Go to C++.
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 for i := uint(0); i < n; i++ { var t1, t2, t3 uint64 if i > 0 { t1 = st >> (i - 1) } else { t1 = st >> 63 } if i == 0 { t2 = st << 1 } else if i == 1 { t2 = st << 63 } else { t2 = st << (n + 1 - i) } t3 = 7 & (t1 | t2) if (uint64(rule) & pow2(uint(t3))) != 0 { state |= pow2(i) } } } fmt.Printf("%d ", b) } fmt.Println() } func main() { evolve(1, 30) }
#include <bitset> #include <stdio.h> #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x))) void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] ); for (i = 1; i < SIZE-1; i++) t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] ); for (i = 0; i < SIZE; i++) s[i] = t[i]; } void show(std::bitset<SIZE> s) { int i; for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' '); printf("|\n"); } unsigned char byte(std::bitset<SIZE> &s) { unsigned char b = 0; int i; for (i=8; i--; ) { b |= s[0] << i; evolve(s); } return b; } int main() { int i; std::bitset<SIZE> state(1); for (i=10; i--; ) printf("%u%c", byte(state), i ? ' ' : '\n'); return 0; }
Convert this Go block to C++, preserving its control flow and logic.
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 for i := uint(0); i < n; i++ { var t1, t2, t3 uint64 if i > 0 { t1 = st >> (i - 1) } else { t1 = st >> 63 } if i == 0 { t2 = st << 1 } else if i == 1 { t2 = st << 63 } else { t2 = st << (n + 1 - i) } t3 = 7 & (t1 | t2) if (uint64(rule) & pow2(uint(t3))) != 0 { state |= pow2(i) } } } fmt.Printf("%d ", b) } fmt.Println() } func main() { evolve(1, 30) }
#include <bitset> #include <stdio.h> #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x))) void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] ); for (i = 1; i < SIZE-1; i++) t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] ); for (i = 0; i < SIZE; i++) s[i] = t[i]; } void show(std::bitset<SIZE> s) { int i; for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' '); printf("|\n"); } unsigned char byte(std::bitset<SIZE> &s) { unsigned char b = 0; int i; for (i=8; i--; ) { b |= s[0] << i; evolve(s); } return b; } int main() { int i; std::bitset<SIZE> state(1); for (i=10; i--; ) printf("%u%c", byte(state), i ? ' ' : '\n'); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
package main import ( "fmt" "math" ) const CONST = 6364136223846793005 type Pcg32 struct{ state, inc uint64 } func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} } func (pcg *Pcg32) seed(seedState, seedSequence uint64) { pcg.state = 0 pcg.inc = (seedSequence << 1) | 1 pcg.nextInt() pcg.state = pcg.state + seedState pcg.nextInt() } func (pcg *Pcg32) nextInt() uint32 { old := pcg.state pcg.state = old*CONST + pcg.inc pcgshifted := uint32(((old >> 18) ^ old) >> 27) rot := uint32(old >> 59) return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31)) } func (pcg *Pcg32) nextFloat() float64 { return float64(pcg.nextInt()) / (1 << 32) } func main() { randomGen := Pcg32New() randomGen.seed(42, 54) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321, 1) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
#include <array> #include <iostream> class PCG32 { private: const uint64_t N = 6364136223846793005; uint64_t state = 0x853c49e6748fea9b; uint64_t inc = 0xda3e39cb94b95bdb; public: uint32_t nextInt() { uint64_t old = state; state = old * N + inc; uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27); uint32_t rot = old >> 59; return (shifted >> rot) | (shifted << ((~rot + 1) & 31)); } double nextFloat() { return ((double)nextInt()) / (1LL << 32); } void seed(uint64_t seed_state, uint64_t seed_sequence) { state = 0; inc = (seed_sequence << 1) | 1; nextInt(); state = state + seed_state; nextInt(); } }; int main() { auto r = new PCG32(); r->seed(42, 54); std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << '\n'; std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; r->seed(987654321, 1); for (size_t i = 0; i < 100000; i++) { int j = (int)floor(r->nextFloat() * 5.0); counts[j]++; } std::cout << "The counts for 100,000 repetitions are:\n"; for (size_t i = 0; i < counts.size(); i++) { std::cout << " " << i << " : " << counts[i] << '\n'; } return 0; }
Keep all operations the same but rewrite the snippet in C++.
package main import ( "github.com/fogleman/gg" "image/color" "math" ) var ( red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = color.RGBA{0, 255, 255, 255} ) var ( w, h = 640, 640 dc = gg.NewContext(w, h) deg72 = gg.Radians(72) scaleFactor = 1 / (2 + math.Cos(deg72)*2) palette = [5]color.Color{red, green, blue, magenta, cyan} colorIndex = 0 ) func drawPentagon(x, y, side float64, depth int) { angle := 3 * deg72 if depth == 0 { dc.MoveTo(x, y) for i := 0; i < 5; i++ { x += math.Cos(angle) * side y -= math.Sin(angle) * side dc.LineTo(x, y) angle += deg72 } dc.SetColor(palette[colorIndex]) dc.Fill() colorIndex = (colorIndex + 1) % 5 } else { side *= scaleFactor dist := side * (1 + math.Cos(deg72)*2) for i := 0; i < 5; i++ { x += math.Cos(angle) * dist y -= math.Sin(angle) * dist drawPentagon(x, y, side, depth-1) angle += deg72 } } } func main() { dc.SetRGB(1, 1, 1) dc.Clear() order := 5 hw := float64(w / 2) margin := 20.0 radius := hw - 2*margin side := radius * math.Sin(math.Pi/5) * 2 drawPentagon(hw, 3*margin, side, order-1) dc.SavePNG("sierpinski_pentagon.png") }
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } void right(double angle) { theta -= angle; } void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); sierpinski(order, spawn, new_size); } sierpinski(order, turtle, new_size); } else { pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" - std::cout << " \"http: std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http: size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
Write a version of this Go function in C++ with identical behavior.
package main import ( "fmt" "strings" ) func rep(s string) int { for x := len(s) / 2; x > 0; x-- { if strings.HasPrefix(s, s[x:]) { return x } } return 0 } const m = ` 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1` func main() { for _, s := range strings.Fields(m) { if n := rep(s); n > 0 { fmt.Printf("%q %d rep-string %q\n", s, n, s[:n]) } else { fmt.Printf("%q not a rep-string\n", s) } } }
#include <string> #include <vector> #include <boost/regex.hpp> bool is_repstring( const std::string & teststring , std::string & repunit ) { std::string regex( "^(.+)\\1+(.*)$" ) ; boost::regex e ( regex ) ; boost::smatch what ; if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { std::string firstbracket( what[1 ] ) ; std::string secondbracket( what[ 2 ] ) ; if ( firstbracket.length( ) >= secondbracket.length( ) && firstbracket.find( secondbracket ) != std::string::npos ) { repunit = firstbracket ; } } return !repunit.empty( ) ; } int main( ) { std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" , "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; std::string theRep ; for ( std::string myString : teststrings ) { if ( is_repstring( myString , theRep ) ) { std::cout << myString << " is a rep string! Here is a repeating string:\n" ; std::cout << theRep << " " ; } else { std::cout << myString << " is no rep string!" ; } theRep.clear( ) ; std::cout << std::endl ; } return 0 ; }
Write the same algorithm in C++ as shown in this Go implementation.
ch := 'z' ch = 122 ch = '\x7a' ch = '\u007a' ch = '\U0000007a' ch = '\172'
auto strA = R"(this is a newline-separated raw string)";
Rewrite this program in C++ while keeping its functionality equivalent to the Go version.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func hammingDist(s1, s2 string) int { r1 := []rune(s1) r2 := []rune(s2) if len(r1) != len(r2) { return 0 } count := 0 for i := 0; i < len(r1); i++ { if r1[i] != r2[i] { count++ if count == 2 { break } } } return count } func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 11 { words = append(words, s) } } count := 0 fmt.Println("Changeable words in", wordList, "\b:") for _, word1 := range words { for _, word2 := range words { if word1 != word2 && hammingDist(word1, word2) == 1 { count++ fmt.Printf("%2d: %-14s -> %s\n", count, word1, word2) } } } }
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int hamming_distance(const std::string& str1, const std::string& str2) { size_t len1 = str1.size(); size_t len2 = str2.size(); if (len1 != len2) return 0; int count = 0; for (size_t i = 0; i < len1; ++i) { if (str1[i] != str2[i]) ++count; if (count == 2) break; } return count; } int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::vector<std::string> dictionary; while (getline(in, line)) { if (line.size() > 11) dictionary.push_back(line); } std::cout << "Changeable words in " << filename << ":\n"; int n = 1; for (const std::string& word1 : dictionary) { for (const std::string& word2 : dictionary) { if (hamming_distance(word1, word2) == 1) std::cout << std::setw(2) << std::right << n++ << ": " << std::setw(14) << std::left << word1 << " -> " << word2 << '\n'; } } return EXIT_SUCCESS; }
Keep all operations the same but rewrite the snippet in C++.
package main import "fmt" type mlist struct{ value []int } func (m mlist) bind(f func(lst []int) mlist) mlist { return f(m.value) } func unit(lst []int) mlist { return mlist{lst} } func increment(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = v + 1 } return unit(lst2) } func double(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = 2 * v } return unit(lst2) } func main() { ml1 := unit([]int{3, 4, 5}) ml2 := ml1.bind(increment).bind(double) fmt.Printf("%v -> %v\n", ml1.value, ml2.value) }
#include <iostream> #include <vector> using namespace std; template <typename T> auto operator>>(const vector<T>& monad, auto f) { vector<remove_reference_t<decltype(f(monad.front()).front())>> result; for(auto& item : monad) { const auto r = f(item); result.insert(result.end(), begin(r), end(r)); } return result; } auto Pure(auto t) { return vector{t}; } auto Double(int i) { return Pure(2 * i); } auto Increment(int i) { return Pure(i + 1); } auto NiceNumber(int i) { return Pure(to_string(i) + " is a nice number\n"); } auto UpperSequence = [](auto startingVal) { const int MaxValue = 500; vector<decltype(startingVal)> sequence; while(startingVal <= MaxValue) sequence.push_back(startingVal++); return sequence; }; void PrintVector(const auto& vec) { cout << " "; for(auto value : vec) { cout << value << " "; } cout << "\n"; } void PrintTriples(const auto& vec) { cout << "Pythagorean triples:\n"; for(auto it = vec.begin(); it != vec.end();) { auto x = *it++; auto y = *it++; auto z = *it++; cout << x << ", " << y << ", " << z << "\n"; } cout << "\n"; } int main() { auto listMonad = vector<int> {2, 3, 4} >> Increment >> Double >> NiceNumber; PrintVector(listMonad); auto pythagoreanTriples = UpperSequence(1) >> [](int x){return UpperSequence(x) >> [x](int y){return UpperSequence(y) >> [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};}; PrintTriples(pythagoreanTriples); }
Convert this Go snippet to C++ and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func sf(n int) *big.Int { if n < 2 { return big.NewInt(1) } sfact := big.NewInt(1) fact := big.NewInt(1) for i := 2; i <= n; i++ { fact.Mul(fact, big.NewInt(int64(i))) sfact.Mul(sfact, fact) } return sfact } func H(n int) *big.Int { if n < 2 { return big.NewInt(1) } hfact := big.NewInt(1) for i := 2; i <= n; i++ { bi := big.NewInt(int64(i)) hfact.Mul(hfact, bi.Exp(bi, bi, nil)) } return hfact } func af(n int) *big.Int { if n < 1 { return new(big.Int) } afact := new(big.Int) fact := big.NewInt(1) sign := new(big.Int) if n%2 == 0 { sign.SetInt64(-1) } else { sign.SetInt64(1) } t := new(big.Int) for i := 1; i <= n; i++ { fact.Mul(fact, big.NewInt(int64(i))) afact.Add(afact, t.Mul(fact, sign)) sign.Neg(sign) } return afact } func ef(n int) *big.Int { if n < 1 { return big.NewInt(1) } t := big.NewInt(int64(n)) return t.Exp(t, ef(n-1), nil) } func rf(n *big.Int) int { i := 0 fact := big.NewInt(1) for { if fact.Cmp(n) == 0 { return i } if fact.Cmp(n) > 0 { return -1 } i++ fact.Mul(fact, big.NewInt(int64(i))) } } func main() { fmt.Println("First 10 superfactorials:") for i := 0; i < 10; i++ { fmt.Println(sf(i)) } fmt.Println("\nFirst 10 hyperfactorials:") for i := 0; i < 10; i++ { fmt.Println(H(i)) } fmt.Println("\nFirst 10 alternating factorials:") for i := 0; i < 10; i++ { fmt.Print(af(i), " ") } fmt.Println("\n\nFirst 5 exponential factorials:") for i := 0; i <= 4; i++ { fmt.Print(ef(i), " ") } fmt.Println("\n\nThe number of digits in 5$ is", len(ef(5).String())) fmt.Println("\nReverse factorials:") facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119} for _, fact := range facts { bfact := big.NewInt(fact) rfact := rf(bfact) srfact := fmt.Sprintf("%d", rfact) if rfact == -1 { srfact = "none" } fmt.Printf("%4s <- rf(%d)\n", srfact, fact) } }
#include <cmath> #include <cstdint> #include <iostream> #include <functional> uint64_t factorial(int n) { uint64_t result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } int inverse_factorial(uint64_t f) { int p = 1; int i = 1; if (f == 1) { return 0; } while (p < f) { p *= i; i++; } if (p == f) { return i - 1; } return -1; } uint64_t super_factorial(int n) { uint64_t result = 1; for (int i = 1; i <= n; i++) { result *= factorial(i); } return result; } uint64_t hyper_factorial(int n) { uint64_t result = 1; for (int i = 1; i <= n; i++) { result *= (uint64_t)powl(i, i); } return result; } uint64_t alternating_factorial(int n) { uint64_t result = 0; for (int i = 1; i <= n; i++) { if ((n - i) % 2 == 0) { result += factorial(i); } else { result -= factorial(i); } } return result; } uint64_t exponential_factorial(int n) { uint64_t result = 0; for (int i = 1; i <= n; i++) { result = (uint64_t)powl(i, (long double)result); } return result; } void test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) { std::cout << "First " << count << ' ' << name << '\n'; for (int i = 0; i < count; i++) { std::cout << func(i) << ' '; } std::cout << '\n'; } void test_inverse(uint64_t f) { int n = inverse_factorial(f); if (n < 0) { std::cout << "rf(" << f << ") = No Solution\n"; } else { std::cout << "rf(" << f << ") = " << n << '\n'; } } int main() { test_factorial(9, super_factorial, "super factorials"); std::cout << '\n'; test_factorial(8, hyper_factorial, "hyper factorials"); std::cout << '\n'; test_factorial(10, alternating_factorial, "alternating factorials"); std::cout << '\n'; test_factorial(5, exponential_factorial, "exponential factorials"); std::cout << '\n'; test_inverse(1); test_inverse(2); test_inverse(6); test_inverse(24); test_inverse(120); test_inverse(720); test_inverse(5040); test_inverse(40320); test_inverse(362880); test_inverse(3628800); test_inverse(119); return 0; }
Preserve the algorithm and functionality while converting the code from Go to C++.
package main import ( "fmt" "math" "strings" ) func main() { for _, n := range [...]int64{ 0, 4, 6, 11, 13, 75, 100, 337, -164, math.MaxInt64, } { fmt.Println(fourIsMagic(n)) } } func fourIsMagic(n int64) string { s := say(n) s = strings.ToUpper(s[:1]) + s[1:] t := s for n != 4 { n = int64(len(s)) s = say(n) t += " is " + s + ", " + s } t += " is magic." return t } 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 <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char* tens[] = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; struct named_number { const char* name_; integer number_; }; const named_number named_numbers[] = { { "hundred", 100 }, { "thousand", 1000 }, { "million", 1000000 }, { "billion", 1000000000 }, { "trillion", 1000000000000 }, { "quadrillion", 1000000000000000ULL }, { "quintillion", 1000000000000000000ULL } }; const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number_) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string cardinal(integer n) { std::string result; if (n < 20) result = small[n]; else if (n < 100) { result = tens[n/10 - 2]; if (n % 10 != 0) { result += "-"; result += small[n % 10]; } } else { const named_number& num = get_named_number(n); integer p = num.number_; result = cardinal(n/p); result += " "; result += num.name_; if (n % p != 0) { result += " "; result += cardinal(n % p); } } return result; } inline char uppercase(char ch) { return static_cast<char>(std::toupper(static_cast<unsigned char>(ch))); } std::string magic(integer n) { std::string result; for (unsigned int i = 0; ; ++i) { std::string text(cardinal(n)); if (i == 0) text[0] = uppercase(text[0]); result += text; if (n == 4) { result += " is magic."; break; } integer len = text.length(); result += " is "; result += cardinal(len); result += ", "; n = len; } return result; } void test_magic(integer n) { std::cout << magic(n) << '\n'; } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
Change the following Go code into C++ without altering its purpose.
package main import ( "fmt" "log" "math" "strings" ) var error = "Argument must be a numeric literal or a decimal numeric string." func getNumDecimals(n interface{}) int { switch v := n.(type) { case int: return 0 case float64: if v == math.Trunc(v) { return 0 } s := fmt.Sprintf("%g", v) return len(strings.Split(s, ".")[1]) case string: if v == "" { log.Fatal(error) } if v[0] == '+' || v[0] == '-' { v = v[1:] } for _, c := range v { if strings.IndexRune("0123456789.", c) == -1 { log.Fatal(error) } } s := strings.Split(v, ".") ls := len(s) if ls == 1 { return 0 } else if ls == 2 { return len(s[1]) } else { log.Fatal("Too many decimal points") } default: log.Fatal(error) } return 0 } func main() { var a = []interface{}{12, 12.345, 12.345555555555, "12.3450", "12.34555555555555555555", 12.345e53} for _, n := range a { d := getNumDecimals(n) switch v := n.(type) { case string: fmt.Printf("%q has %d decimals\n", v, d) case float32, float64: fmt.Printf("%g has %d decimals\n", v, d) default: fmt.Printf("%d has %d decimals\n", v, d) } } }
#include <iomanip> #include <iostream> #include <sstream> int findNumOfDec(double x) { std::stringstream ss; ss << std::fixed << std::setprecision(14) << x; auto s = ss.str(); auto pos = s.find('.'); if (pos == std::string::npos) { return 0; } auto tail = s.find_last_not_of('0'); return tail - pos; } void test(double x) { std::cout << x << " has " << findNumOfDec(x) << " decimals\n"; } int main() { test(12.0); test(12.345); test(12.345555555555); test(12.3450); test(12.34555555555555555555); test(1.2345e+54); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Go code.
const ( apple = iota banana cherry )
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Rewrite this program in C++ while keeping its functionality equivalent to the Go version.
package main import ( "encoding/hex" "fmt" "io" "net" "os" "strconv" "strings" "text/tabwriter" ) func parseIPPort(address string) (net.IP, *uint64, error) { ip := net.ParseIP(address) if ip != nil { return ip, nil, nil } host, portStr, err := net.SplitHostPort(address) if err != nil { return nil, nil, fmt.Errorf("splithostport failed: %w", err) } port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, nil, fmt.Errorf("failed to parse port: %w", err) } ip = net.ParseIP(host) if ip == nil { return nil, nil, fmt.Errorf("failed to parse ip address") } return ip, &port, nil } func ipVersion(ip net.IP) int { if ip.To4() == nil { return 6 } return 4 } func main() { testCases := []string{ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:443", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) writeTSV := func(w io.Writer, args ...interface{}) { fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...) fmt.Fprintf(w, "\n") } writeTSV(w, "Input", "Address", "Space", "Port") for _, addr := range testCases { ip, port, err := parseIPPort(addr) if err != nil { panic(err) } portStr := "n/a" if port != nil { portStr = fmt.Sprint(*port) } ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip)) writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr) } w.Flush() }
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boost::asio::ip::make_address_v6; template<typename uint> bool parse_int(const std::string& str, int base, uint& n) { try { size_t pos = 0; unsigned long u = stoul(str, &pos, base); if (pos != str.length() || u > std::numeric_limits<uint>::max()) return false; n = static_cast<uint>(u); return true; } catch (const std::exception& ex) { return false; } } void parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) { size_t pos = input.rfind(':'); if (pos != std::string::npos && pos > 1 && pos + 1 < input.length() && parse_int(input.substr(pos + 1), 10, port) && port > 0) { if (input[0] == '[' && input[pos - 1] == ']') { addr = make_address_v6(input.substr(1, pos - 2)); return; } else { try { addr = make_address_v4(input.substr(0, pos)); return; } catch (const std::exception& ex) { } } } port = 0; addr = make_address(input); } void print_address_and_port(const address& addr, uint16_t port) { std::cout << std::hex << std::uppercase << std::setfill('0'); if (addr.is_v4()) { address_v4 addr4 = addr.to_v4(); std::cout << "address family: IPv4\n"; std::cout << "address number: " << std::setw(8) << addr4.to_uint() << '\n'; } else if (addr.is_v6()) { address_v6 addr6 = addr.to_v6(); address_v6::bytes_type bytes(addr6.to_bytes()); std::cout << "address family: IPv6\n"; std::cout << "address number: "; for (unsigned char byte : bytes) std::cout << std::setw(2) << static_cast<unsigned int>(byte); std::cout << '\n'; } if (port != 0) std::cout << "port: " << std::dec << port << '\n'; else std::cout << "port not specified\n"; } void test(const std::string& input) { std::cout << "input: " << input << '\n'; try { address addr; uint16_t port = 0; parse_ip_address_and_port(input, addr, port); print_address_and_port(addr, port); } catch (const std::exception& ex) { std::cout << "parsing failed\n"; } std::cout << '\n'; } int main(int argc, char** argv) { test("127.0.0.1"); test("127.0.0.1:80"); test("::ffff:127.0.0.1"); test("::1"); test("[::1]:80"); test("1::80"); test("2605:2700:0:3::4713:93e3"); test("[2605:2700:0:3::4713:93e3]:80"); return 0; }
Change the following Go code into C++ without altering its purpose.
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t := NewTextonym(phoneMap) _, err := ReadFromFile(t, *wordlist) if err != nil { log.Fatal(err) } t.Report(os.Stdout, *wordlist) } var phoneMap = map[byte][]rune{ '2': []rune("ABC"), '3': []rune("DEF"), '4': []rune("GHI"), '5': []rune("JKL"), '6': []rune("MNO"), '7': []rune("PQRS"), '8': []rune("TUV"), '9': []rune("WXYZ"), } func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) { f, err := os.Open(filename) if err != nil { return 0, err } n, err := r.ReadFrom(f) if cerr := f.Close(); err == nil && cerr != nil { err = cerr } return n, err } type Textonym struct { numberMap map[string][]string letterMap map[rune]byte count int textonyms int } func NewTextonym(dm map[byte][]rune) *Textonym { lm := make(map[rune]byte, 26) for d, ll := range dm { for _, l := range ll { lm[l] = d } } return &Textonym{letterMap: lm} } func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) { t.numberMap = make(map[string][]string) buf := make([]byte, 0, 32) sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) scan: for sc.Scan() { buf = buf[:0] word := sc.Text() n += int64(len(word)) + 1 for _, r := range word { d, ok := t.letterMap[unicode.ToUpper(r)] if !ok { continue scan } buf = append(buf, d) } num := string(buf) t.numberMap[num] = append(t.numberMap[num], word) t.count++ if len(t.numberMap[num]) == 2 { t.textonyms++ } } return n, sc.Err() } func (t *Textonym) Most() (most int, subset map[string][]string) { for k, v := range t.numberMap { switch { case len(v) > most: subset = make(map[string][]string) most = len(v) fallthrough case len(v) == most: subset[k] = v } } return most, subset } func (t *Textonym) Report(w io.Writer, name string) { fmt.Fprintf(w, ` There are %v words in %q which can be represented by the digit key mapping. They require %v digit combinations to represent them. %v digit combinations represent Textonyms. `, t.count, name, len(t.numberMap), t.textonyms) n, sub := t.Most() fmt.Fprintln(w, "\nThe numbers mapping to the most words map to", n, "words each:") for k, v := range sub { fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", ")) } }
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mapping(std::string &result, const std::string &input) { static std::unordered_map<char, char> mapping = { {'A', '2'}, {'B', '2'}, {'C', '2'}, {'D', '3'}, {'E', '3'}, {'F', '3'}, {'G', '4'}, {'H', '4'}, {'I', '4'}, {'J', '5'}, {'K', '5'}, {'L', '5'}, {'M', '6'}, {'N', '6'}, {'O', '6'}, {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'}, {'T', '8'}, {'U', '8'}, {'V', '8'}, {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'} }; result = input; for (char &c : result) { if (!isalnum(c)) return 0; if (isalpha(c)) c = mapping[toupper(c)]; } return 1; } public: Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { } ~Textonym_Checker() { } void add(const std::string &str) { std::string mapping; total++; if (!get_mapping(mapping, str)) return; const int num_strings = values[mapping].size(); if (num_strings == 1) textonyms++; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.push_back(mapping); max_found = num_strings; } else if (num_strings == max_found) max_strings.push_back(mapping); values[mapping].push_back(str); } void results(const std::string &filename) { std::cout << "Read " << total << " words from " << filename << "\n\n"; std::cout << "There are " << elements << " words in " << filename; std::cout << " which can be represented by the digit key mapping.\n"; std::cout << "They require " << values.size() << " digit combinations to represent them.\n"; std::cout << textonyms << " digit combinations represent Textonyms.\n\n"; std::cout << "The numbers mapping to the most words map to "; std::cout << max_found + 1 << " words each:\n"; for (auto it1 : max_strings) { std::cout << '\t' << it1 << " maps to: "; for (auto it2 : values[it1]) std::cout << it2 << " "; std::cout << '\n'; } std::cout << '\n'; } void match(const std::string &str) { auto match = values.find(str); if (match == values.end()) { std::cout << "Key '" << str << "' not found\n"; } else { std::cout << "Key '" << str << "' matches: "; for (auto it : values[str]) std::cout << it << " "; std::cout << '\n'; } } }; int main() { auto filename = "unixdict.txt"; std::ifstream input(filename); Textonym_Checker tc; if (input.is_open()) { std::string line; while (getline(input, line)) tc.add(line); } input.close(); tc.results(filename); tc.match("001"); tc.match("228"); tc.match("27484247"); tc.match("7244967473642"); }
Change the following Go code into C++ without altering its purpose.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: map() { char t[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; w = h = 8; for( int r = 0; r < h; r++ ) for( int s = 0; s < w; s++ ) m[s][r] = t[r][s]; } int operator() ( int x, int y ) { return m[x][y]; } char m[8][8]; int w, h; }; class node { public: bool operator == (const node& o ) { return pos == o.pos; } bool operator == (const point& o ) { return pos == o; } bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; } point pos, parent; int dist, cost; }; class aStar { public: aStar() { neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 ); neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 ); neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 ); neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 ); } int calcDist( point& p ){ int x = end.x - p.x, y = end.y - p.y; return( x * x + y * y ); } bool isValid( point& p ) { return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h ); } bool existPoint( point& p, int cost ) { std::list<node>::iterator i; i = std::find( closed.begin(), closed.end(), p ); if( i != closed.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { closed.erase( i ); return false; } } i = std::find( open.begin(), open.end(), p ); if( i != open.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { open.erase( i ); return false; } } return false; } bool fillOpen( node& n ) { int stepCost, nc, dist; point neighbour; for( int x = 0; x < 8; x++ ) { stepCost = x < 4 ? 1 : 1; neighbour = n.pos + neighbours[x]; if( neighbour == end ) return true; if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) { nc = stepCost + n.cost; dist = calcDist( neighbour ); if( !existPoint( neighbour, nc + dist ) ) { node m; m.cost = nc; m.dist = dist; m.pos = neighbour; m.parent = n.pos; open.push_back( m ); } } } return false; } bool search( point& s, point& e, map& mp ) { node n; end = e; start = s; m = mp; n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s ); open.push_back( n ); while( !open.empty() ) { node n = open.front(); open.pop_front(); closed.push_back( n ); if( fillOpen( n ) ) return true; } return false; } int path( std::list<point>& path ) { path.push_front( end ); int cost = 1 + closed.back().cost; path.push_front( closed.back().pos ); point parent = closed.back().parent; for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) { if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) { path.push_front( ( *i ).pos ); parent = ( *i ).parent; } } path.push_front( start ); return cost; } map m; point end, start; point neighbours[8]; std::list<node> open; std::list<node> closed; }; int main( int argc, char* argv[] ) { map m; point s, e( 7, 7 ); aStar as; if( as.search( s, e, m ) ) { std::list<point> path; int c = as.path( path ); for( int y = -1; y < 9; y++ ) { for( int x = -1; x < 9; x++ ) { if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 ) std::cout << char(0xdb); else { if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() ) std::cout << "x"; else std::cout << "."; } } std::cout << "\n"; } std::cout << "\nPath cost " << c << ": "; for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) { std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") "; } } std::cout << "\n\n"; return 0; }
Port the provided Go code into C++ while preserving the original functionality.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: map() { char t[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; w = h = 8; for( int r = 0; r < h; r++ ) for( int s = 0; s < w; s++ ) m[s][r] = t[r][s]; } int operator() ( int x, int y ) { return m[x][y]; } char m[8][8]; int w, h; }; class node { public: bool operator == (const node& o ) { return pos == o.pos; } bool operator == (const point& o ) { return pos == o; } bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; } point pos, parent; int dist, cost; }; class aStar { public: aStar() { neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 ); neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 ); neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 ); neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 ); } int calcDist( point& p ){ int x = end.x - p.x, y = end.y - p.y; return( x * x + y * y ); } bool isValid( point& p ) { return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h ); } bool existPoint( point& p, int cost ) { std::list<node>::iterator i; i = std::find( closed.begin(), closed.end(), p ); if( i != closed.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { closed.erase( i ); return false; } } i = std::find( open.begin(), open.end(), p ); if( i != open.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { open.erase( i ); return false; } } return false; } bool fillOpen( node& n ) { int stepCost, nc, dist; point neighbour; for( int x = 0; x < 8; x++ ) { stepCost = x < 4 ? 1 : 1; neighbour = n.pos + neighbours[x]; if( neighbour == end ) return true; if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) { nc = stepCost + n.cost; dist = calcDist( neighbour ); if( !existPoint( neighbour, nc + dist ) ) { node m; m.cost = nc; m.dist = dist; m.pos = neighbour; m.parent = n.pos; open.push_back( m ); } } } return false; } bool search( point& s, point& e, map& mp ) { node n; end = e; start = s; m = mp; n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s ); open.push_back( n ); while( !open.empty() ) { node n = open.front(); open.pop_front(); closed.push_back( n ); if( fillOpen( n ) ) return true; } return false; } int path( std::list<point>& path ) { path.push_front( end ); int cost = 1 + closed.back().cost; path.push_front( closed.back().pos ); point parent = closed.back().parent; for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) { if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) { path.push_front( ( *i ).pos ); parent = ( *i ).parent; } } path.push_front( start ); return cost; } map m; point end, start; point neighbours[8]; std::list<node> open; std::list<node> closed; }; int main( int argc, char* argv[] ) { map m; point s, e( 7, 7 ); aStar as; if( as.search( s, e, m ) ) { std::list<point> path; int c = as.path( path ); for( int y = -1; y < 9; y++ ) { for( int x = -1; x < 9; x++ ) { if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 ) std::cout << char(0xdb); else { if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() ) std::cout << "x"; else std::cout << "."; } } std::cout << "\n"; } std::cout << "\nPath cost " << c << ": "; for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) { std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") "; } } std::cout << "\n\n"; return 0; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import ( "bufio" "fmt" "log" "os" "sort" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if len(word) >= 3 { words = append(words, word) } } check(scanner.Err()) return words } func rotate(runes []rune) { first := runes[0] copy(runes, runes[1:]) runes[len(runes)-1] = first } func main() { dicts := []string{"mit_10000.txt", "unixdict.txt"} for _, dict := range dicts { fmt.Printf("Using %s:\n\n", dict) words := readWords(dict) n := len(words) used := make(map[string]bool) outer: for _, word := range words { runes := []rune(word) variants := []string{word} for i := 0; i < len(runes)-1; i++ { rotate(runes) word2 := string(runes) if word == word2 || used[word2] { continue outer } ix := sort.SearchStrings(words, word2) if ix == n || words[ix] != word2 { continue outer } variants = append(variants, word2) } for _, variant := range variants { used[variant] = true } fmt.Println(variants) } fmt.Println() } }
#include <algorithm> #include <fstream> #include <iostream> #include <set> #include <string> #include <vector> std::set<std::string> load_dictionary(const std::string& filename) { std::ifstream in(filename); if (!in) throw std::runtime_error("Cannot open file " + filename); std::set<std::string> words; std::string word; while (getline(in, word)) words.insert(word); return words; } void find_teacup_words(const std::set<std::string>& words) { std::vector<std::string> teacup_words; std::set<std::string> found; for (auto w = words.begin(); w != words.end(); ++w) { std::string word = *w; size_t len = word.size(); if (len < 3 || found.find(word) != found.end()) continue; teacup_words.clear(); teacup_words.push_back(word); for (size_t i = 0; i + 1 < len; ++i) { std::rotate(word.begin(), word.begin() + 1, word.end()); if (word == *w || words.find(word) == words.end()) break; teacup_words.push_back(word); } if (teacup_words.size() == len) { found.insert(teacup_words.begin(), teacup_words.end()); std::cout << teacup_words[0]; for (size_t i = 1; i < len; ++i) std::cout << ' ' << teacup_words[i]; std::cout << '\n'; } } } int main(int argc, char** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " dictionary\n"; return EXIT_FAILURE; } try { find_teacup_words(load_dictionary(argv[1])); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Produce a language-to-language conversion: from Go to C++, same semantics.
package main import "fmt" type is func() uint64 func newSum() is { var ms is ms = func() uint64 { ms = newSum() return ms() } var msd, d uint64 return func() uint64 { if d < 9 { d++ } else { d = 0 msd = ms() } return msd + d } } func newHarshard() is { i := uint64(0) sum := newSum() return func() uint64 { for i++; i%sum() != 0; i++ { } return i } } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { fmt.Println("Gap Index of gap Starting Niven") fmt.Println("=== ============= ==============") h := newHarshard() pg := uint64(0) pn := h() for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() { g := n - pn if g > pg { fmt.Printf("%3d %13s %14s\n", g, commatize(i), commatize(pn)) pg = g } pn = n } }
#include <cstdint> #include <iomanip> #include <iostream> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false; return n % d == 0; } int main() { std::cout.imbue(std::locale("")); uint64_t previous = 1, gap = 0, sum = 0; int niven_index = 0, gap_index = 1; std::cout << "Gap index Gap Niven index Niven number\n"; for (uint64_t niven = 1; gap_index <= 32; ++niven) { sum = digit_sum(niven, sum); if (divisible(niven, sum)) { if (niven > previous + gap) { gap = niven - previous; std::cout << std::setw(9) << gap_index++ << std::setw(5) << gap << std::setw(15) << niven_index << std::setw(16) << previous << '\n'; } previous = niven; ++niven_index; } } return 0; }
Write a version of this Go function in C++ with identical behavior.
package main import ( "fmt" "runtime" ) type point struct { x, y float64 } func add(x, y int) int { result := x + y debug("x", x) debug("y", y) debug("result", result) debug("result+1", result+1) return result } func debug(s string, x interface{}) { _, _, lineNo, _ := runtime.Caller(1) fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x) } func main() { add(2, 7) b := true debug("b", b) s := "Hello" debug("s", s) p := point{2, 3} debug("p", p) q := &p debug("q", q) }
#include <iostream> #define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__) int main() { DEBUG("Hello world"); DEBUG("Some %d Things", 42); return 0; }
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically?
package main import ( "errors" "fmt" "strconv" "strings" ) func main() { rf, err := rangeFormat([]int{ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, }) if err != nil { fmt.Println(err) return } fmt.Println("range format:", rf) } func rangeFormat(a []int) (string, error) { if len(a) == 0 { return "", nil } var parts []string for n1 := 0; ; { n2 := n1 + 1 for n2 < len(a) && a[n2] == a[n2-1]+1 { n2++ } s := strconv.Itoa(a[n1]) if n2 == n1+2 { s += "," + strconv.Itoa(a[n2-1]) } else if n2 > n1+2 { s += "-" + strconv.Itoa(a[n2-1]) } parts = append(parts, s) if n2 == len(a) { break } if a[n2] == a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence repeats value %d", a[n2])) } if a[n2] < a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence not ordered: %d < %d", a[n2], a[n2-1])) } n1 = n2 } return strings.Join(parts, ","), nil }
#include <iostream> #include <iterator> #include <cstddef> template<typename InIter> void extract_ranges(InIter begin, InIter end, std::ostream& os) { if (begin == end) return; int current = *begin++; os << current; int count = 1; while (begin != end) { int next = *begin++; if (next == current+1) ++count; else { if (count > 2) os << '-'; else os << ','; if (count > 1) os << current << ','; os << next; count = 1; } current = next; } if (count > 1) os << (count > 2? '-' : ',') << current; } template<typename T, std::size_t n> T* end(T (&array)[n]) { return array+n; } int main() { int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; extract_ranges(data, end(data), std::cout); std::cout << std::endl; }
Please provide an equivalent version of this Go code in C++.
package main import "fmt" type any = interface{} func showType(a any) { switch a.(type) { case rune: fmt.Printf("The type of '%c' is %T\n", a, a) default: fmt.Printf("The type of '%v' is %T\n", a, a) } } func main() { values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"} for _, value := range values { showType(value) } }
#include <iostream> template <typename T> auto typeString(const T&) { return typeid(T).name(); } class C {}; struct S {}; int main() { std::cout << typeString(1) << '\n'; std::cout << typeString(1L) << '\n'; std::cout << typeString(1.0f) << '\n'; std::cout << typeString(1.0) << '\n'; std::cout << typeString('c') << '\n'; std::cout << typeString("string") << '\n'; std::cout << typeString(C{}) << '\n'; std::cout << typeString(S{}) << '\n'; std::cout << typeString(nullptr) << '\n'; }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
#include <iostream> int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); for (int n = tn - 1; n > 0; --n) for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; }
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically?
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
#include <iostream> int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); for (int n = tn - 1; n > 0; --n) for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import "fmt" func main() { s := []int{1, 2, 2, 3, 4, 4, 5} for i := 0; i < len(s); i++ { curr := s[i] var prev int if i > 0 && curr == prev { fmt.Println(i) } prev = curr } var prev int for i := 0; i < len(s); i++ { curr := s[i] if i > 0 && curr == prev { fmt.Println(i) } prev = curr } }
#include <array> #include <iostream> int main() { constexpr std::array s {1,2,2,3,4,4,5}; if(!s.empty()) { int previousValue = s[0]; for(size_t i = 1; i < s.size(); ++i) { const int currentValue = s[i]; if(i > 0 && previousValue == currentValue) { std::cout << i << "\n"; } previousValue = currentValue; } } }
Write a version of this Go function in C++ with identical behavior.
package main import "fmt" func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { falls = falls + 1 } } prev = d n /= 10 } return rises == falls } func main() { fmt.Println("The first 200 numbers in the sequence are:") count := 0 n := 1 for { if risesEqualsFalls(n) { count++ if count <= 200 { fmt.Printf("%3d ", n) if count%20 == 0 { fmt.Println() } } if count == 1e7 { fmt.Println("\nThe 10 millionth number in the sequence is ", n) break } } n++ } }
#include <iomanip> #include <iostream> bool equal_rises_and_falls(int n) { int total = 0; for (int previous_digit = -1; n > 0; n /= 10) { int digit = n % 10; if (previous_digit > digit) ++total; else if (previous_digit >= 0 && previous_digit < digit) --total; previous_digit = digit; } return total == 0; } int main() { const int limit1 = 200; const int limit2 = 10000000; int n = 0; std::cout << "The first " << limit1 << " numbers in the sequence are:\n"; for (int count = 0; count < limit2; ) { if (equal_rises_and_falls(++n)) { ++count; if (count <= limit1) std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' '); } } std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n"; }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import ( "github.com/fogleman/gg" "math" ) var dc = gg.NewContext(512, 512) func koch(x1, y1, x2, y2 float64, iter int) { angle := math.Pi / 3 x3 := (x1*2 + x2) / 3 y3 := (y1*2 + y2) / 3 x4 := (x1 + x2*2) / 3 y4 := (y1 + y2*2) / 3 x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle) y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle) if iter > 0 { iter-- koch(x1, y1, x3, y3, iter) koch(x3, y3, x5, y5, iter) koch(x5, y5, x4, y4, iter) koch(x4, y4, x2, y2, iter) } else { dc.LineTo(x1, y1) dc.LineTo(x3, y3) dc.LineTo(x5, y5) dc.LineTo(x4, y4) dc.LineTo(x2, y2) } } func main() { dc.SetRGB(1, 1, 1) dc.Clear() koch(100, 100, 400, 400, 4) dc.SetRGB(0, 0, 1) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("koch.png") }
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dy = y1 - y0; double dx = x1 - x0; output[j++] = {x0, y0}; output[j++] = {x0 + dx/3, y0 + dy/3}; output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3}; output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3}; } output[j] = {x1, y1}; return output; } std::vector<point> koch_points(int size, int iterations) { double length = size * sqrt3_2 * 0.95; double x = (size - length)/2; double y = size/2 - length * sqrt3_2/3; std::vector<point> points{ {x, y}, {x + length/2, y + length * sqrt3_2}, {x + length, y}, {x, y} }; for (int i = 0; i < iterations; ++i) points = koch_next(points); return points; } void koch_curve_svg(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << "<path stroke-width='1' stroke='white' fill='none' d='"; auto points(koch_points(size, iterations)); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "z'/>\n</svg>\n"; } int main() { std::ofstream out("koch_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } koch_curve_svg(out, 600, 5); return EXIT_SUCCESS; }
Translate the given Go code snippet into C++ without altering its behavior.
package main import ( "github.com/fogleman/gg" "math" ) var dc = gg.NewContext(512, 512) func koch(x1, y1, x2, y2 float64, iter int) { angle := math.Pi / 3 x3 := (x1*2 + x2) / 3 y3 := (y1*2 + y2) / 3 x4 := (x1 + x2*2) / 3 y4 := (y1 + y2*2) / 3 x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle) y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle) if iter > 0 { iter-- koch(x1, y1, x3, y3, iter) koch(x3, y3, x5, y5, iter) koch(x5, y5, x4, y4, iter) koch(x4, y4, x2, y2, iter) } else { dc.LineTo(x1, y1) dc.LineTo(x3, y3) dc.LineTo(x5, y5) dc.LineTo(x4, y4) dc.LineTo(x2, y2) } } func main() { dc.SetRGB(1, 1, 1) dc.Clear() koch(100, 100, 400, 400, 4) dc.SetRGB(0, 0, 1) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("koch.png") }
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dy = y1 - y0; double dx = x1 - x0; output[j++] = {x0, y0}; output[j++] = {x0 + dx/3, y0 + dy/3}; output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3}; output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3}; } output[j] = {x1, y1}; return output; } std::vector<point> koch_points(int size, int iterations) { double length = size * sqrt3_2 * 0.95; double x = (size - length)/2; double y = size/2 - length * sqrt3_2/3; std::vector<point> points{ {x, y}, {x + length/2, y + length * sqrt3_2}, {x + length, y}, {x, y} }; for (int i = 0; i < iterations; ++i) points = koch_next(points); return points; } void koch_curve_svg(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << "<path stroke-width='1' stroke='white' fill='none' d='"; auto points(koch_points(size, iterations)); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "z'/>\n</svg>\n"; } int main() { std::ofstream out("koch_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } koch_curve_svg(out, 600, 5); return EXIT_SUCCESS; }
Change the programming language of this snippet from Go to C++ without modifying what it does.
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) >= 9 { words = append(words, s) } } count := 0 var alreadyFound []string le := len(words) var sb strings.Builder for i := 0; i < le-9; i++ { sb.Reset() for j := i; j < i+9; j++ { sb.WriteByte(words[j][j-i]) } word := sb.String() ix := sort.SearchStrings(words, word) if ix < le && word == words[ix] { ix2 := sort.SearchStrings(alreadyFound, word) if ix2 == len(alreadyFound) { count++ fmt.Printf("%2d: %s\n", count, word) alreadyFound = append(alreadyFound, word) } } } }
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main(int argc, char** argv) { const int min_length = 9; const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::vector<std::string> words; while (getline(in, line)) { if (line.size() >= min_length) words.push_back(line); } std::sort(words.begin(), words.end()); std::string previous_word; int count = 0; for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) { std::string word; word.reserve(min_length); for (size_t j = 0; j < min_length; ++j) word += words[i + j][j]; if (previous_word == word) continue; auto w = std::lower_bound(words.begin(), words.end(), word); if (w != words.end() && *w == word) std::cout << std::setw(2) << ++count << ". " << word << '\n'; previous_word = word; } return EXIT_SUCCESS; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for value <= gridSize { result[r][c] = value if r == 0 { if c == n-1 { r++ } else { r = n - 1 c++ } } else if c == n-1 { r-- c = 0 } else if result[r-1][c+1] == 0 { r-- c++ } else { r++ } value++ } return result, nil } func magicSquareSinglyEven(n int) ([][]int, error) { if n < 6 || (n-2)%4 != 0 { return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2") } size := n * n halfN := n / 2 subSquareSize := size / 4 subSquare, err := magicSquareOdd(halfN) if err != nil { return nil, err } quadrantFactors := [4]int{0, 2, 3, 1} result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for r := 0; r < n; r++ { for c := 0; c < n; c++ { quadrant := r/halfN*2 + c/halfN result[r][c] = subSquare[r%halfN][c%halfN] result[r][c] += quadrantFactors[quadrant] * subSquareSize } } nColsLeft := halfN / 2 nColsRight := nColsLeft - 1 for r := 0; r < halfN; r++ { for c := 0; c < n; c++ { if c < nColsLeft || c >= n-nColsRight || (c == nColsLeft && r == nColsLeft) { if c == 0 && r == nColsLeft { continue } tmp := result[r][c] result[r][c] = result[r+halfN][c] result[r+halfN][c] = tmp } } } return result, nil } func main() { const n = 6 msse, err := magicSquareSinglyEven(n) if err != nil { log.Fatal(err) } for _, row := range msse { for _, x := range row { fmt.Printf("%2d ", x) } fmt.Println() } fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2) }
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr() { sqr = 0; } ~magicSqr() { if( sqr ) delete [] sqr; } void create( int d ) { if( sqr ) delete [] sqr; if( d & 1 ) d++; while( d % 4 == 0 ) { d += 2; } sz = d; sqr = new int[sz * sz]; memset( sqr, 0, sz * sz * sizeof( int ) ); fillSqr(); } void display() { cout << "Singly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void siamese( int from, int to ) { int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1; while( count > 0 ) { bool done = false; while ( false == done ) { if( curCol >= oneSide ) curCol = 0; if( curRow < 0 ) curRow = oneSide - 1; done = true; if( sqr[curCol + sz * curRow] != 0 ) { curCol -= 1; curRow += 2; if( curCol < 0 ) curCol = oneSide - 1; if( curRow >= oneSide ) curRow -= oneSide; done = false; } } sqr[curCol + sz * curRow] = s; s++; count--; curCol++; curRow--; } } void fillSqr() { int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3; siamese( 0, n ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = n; c < sz; c++ ) { int m = sqr[c - n + row]; sqr[c + row] = m + add1; sqr[c + row + ns] = m + add3; sqr[c - n + row + ns] = m + add2; } } int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = co; c < sz; c++ ) { sqr[c + row] -= add3; sqr[c + row + ns] += add3; } } for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = 0; c < lc; c++ ) { int cc = c; if( r == lc ) cc++; sqr[cc + row] += add2; sqr[cc + row + ns] -= add2; } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s; s.create( 6 ); s.display(); return 0; }
Port the following code from Go to C++ with equivalent syntax and logic.
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for value <= gridSize { result[r][c] = value if r == 0 { if c == n-1 { r++ } else { r = n - 1 c++ } } else if c == n-1 { r-- c = 0 } else if result[r-1][c+1] == 0 { r-- c++ } else { r++ } value++ } return result, nil } func magicSquareSinglyEven(n int) ([][]int, error) { if n < 6 || (n-2)%4 != 0 { return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2") } size := n * n halfN := n / 2 subSquareSize := size / 4 subSquare, err := magicSquareOdd(halfN) if err != nil { return nil, err } quadrantFactors := [4]int{0, 2, 3, 1} result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for r := 0; r < n; r++ { for c := 0; c < n; c++ { quadrant := r/halfN*2 + c/halfN result[r][c] = subSquare[r%halfN][c%halfN] result[r][c] += quadrantFactors[quadrant] * subSquareSize } } nColsLeft := halfN / 2 nColsRight := nColsLeft - 1 for r := 0; r < halfN; r++ { for c := 0; c < n; c++ { if c < nColsLeft || c >= n-nColsRight || (c == nColsLeft && r == nColsLeft) { if c == 0 && r == nColsLeft { continue } tmp := result[r][c] result[r][c] = result[r+halfN][c] result[r+halfN][c] = tmp } } } return result, nil } func main() { const n = 6 msse, err := magicSquareSinglyEven(n) if err != nil { log.Fatal(err) } for _, row := range msse { for _, x := range row { fmt.Printf("%2d ", x) } fmt.Println() } fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2) }
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr() { sqr = 0; } ~magicSqr() { if( sqr ) delete [] sqr; } void create( int d ) { if( sqr ) delete [] sqr; if( d & 1 ) d++; while( d % 4 == 0 ) { d += 2; } sz = d; sqr = new int[sz * sz]; memset( sqr, 0, sz * sz * sizeof( int ) ); fillSqr(); } void display() { cout << "Singly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void siamese( int from, int to ) { int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1; while( count > 0 ) { bool done = false; while ( false == done ) { if( curCol >= oneSide ) curCol = 0; if( curRow < 0 ) curRow = oneSide - 1; done = true; if( sqr[curCol + sz * curRow] != 0 ) { curCol -= 1; curRow += 2; if( curCol < 0 ) curCol = oneSide - 1; if( curRow >= oneSide ) curRow -= oneSide; done = false; } } sqr[curCol + sz * curRow] = s; s++; count--; curCol++; curRow--; } } void fillSqr() { int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3; siamese( 0, n ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = n; c < sz; c++ ) { int m = sqr[c - n + row]; sqr[c + row] = m + add1; sqr[c + row + ns] = m + add3; sqr[c - n + row + ns] = m + add2; } } int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = co; c < sz; c++ ) { sqr[c + row] -= add3; sqr[c + row + ns] += add3; } } for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = 0; c < lc; c++ ) { int cc = c; if( r == lc ) cc++; sqr[cc + row] += add2; sqr[cc + row + ns] -= add2; } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s; s.create( 6 ); s.display(); return 0; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn"} func (sym symbols) chess960(id int) string { var pos [8]rune q, r := id/4, id%4 pos[r*2+1] = sym.b q, r = q/4, q%4 pos[r*2] = sym.b q, r = q/6, q%6 for i := 0; ; i++ { if pos[i] != 0 { continue } if r == 0 { pos[i] = sym.q break } r-- } i := 0 for _, f := range krn[q] { for pos[i] != 0 { i++ } switch f { case 'k': pos[i] = sym.k case 'r': pos[i] = sym.r case 'n': pos[i] = sym.n } } return string(pos[:]) } func main() { fmt.Println(" ID Start position") for _, id := range []int{0, 518, 959} { fmt.Printf("%3d %s\n", id, A.chess960(id)) } fmt.Println("\nRandom") for i := 0; i < 5; i++ { fmt.Println(W.chess960(rand.Intn(960))) } }
#include <iostream> #include <string> #include <time.h> using namespace std; namespace { void placeRandomly(char* p, char c) { int loc = rand() % 8; if (!p[loc]) p[loc] = c; else placeRandomly(p, c); } int placeFirst(char* p, char c, int loc = 0) { while (p[loc]) ++loc; p[loc] = c; return loc; } string startPos() { char p[8]; memset( p, 0, 8 ); p[2 * (rand() % 4)] = 'B'; p[2 * (rand() % 4) + 1] = 'B'; for (char c : "QNN") placeRandomly(p, c); placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R'))); return string(p, 8); } } namespace chess960 { void generate( int c ) { for( int x = 0; x < c; x++ ) cout << startPos() << "\n"; } } int main( int argc, char* argv[] ) { srand( time( NULL ) ); chess960::generate( 10 ); cout << "\n\n"; return system( "pause" ); }
Generate an equivalent C++ version of this Go code.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
int meaning_of_life();
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
int meaning_of_life();
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "log" "math" "os" "path/filepath" ) func commatize(n int64) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func fileSizeDistribution(root string) { var sizes [12]int files := 0 directories := 0 totalSize := int64(0) walkFunc := func(path string, info os.FileInfo, err error) error { if err != nil { return err } files++ if info.IsDir() { directories++ } size := info.Size() if size == 0 { sizes[0]++ return nil } totalSize += size logSize := math.Log10(float64(size)) index := int(math.Floor(logSize)) sizes[index+1]++ return nil } err := filepath.Walk(root, walkFunc) if err != nil { log.Fatal(err) } fmt.Printf("File size distribution for '%s' :-\n\n", root) for i := 0; i < len(sizes); i++ { if i == 0 { fmt.Print(" ") } else { fmt.Print("+ ") } fmt.Printf("Files less than 10 ^ %-2d bytes : %5d\n", i, sizes[i]) } fmt.Println(" -----") fmt.Printf("= Total number of files  : %5d\n", files) fmt.Printf(" including directories  : %5d\n", directories) c := commatize(totalSize) fmt.Println("\n Total size of files  :", c, "bytes") } func main() { fileSizeDistribution("./") }
#include <algorithm> #include <array> #include <filesystem> #include <iomanip> #include <iostream> void file_size_distribution(const std::filesystem::path& directory) { constexpr size_t n = 9; constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 }; std::array<size_t, n + 1> count = { 0 }; size_t files = 0; std::uintmax_t total_size = 0; std::filesystem::recursive_directory_iterator iter(directory); for (const auto& dir_entry : iter) { if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) { std::uintmax_t file_size = dir_entry.file_size(); total_size += file_size; auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size); size_t index = std::distance(sizes.begin(), i); ++count[index]; ++files; } } std::cout << "File size distribution for " << directory << ":\n"; for (size_t i = 0; i <= n; ++i) { if (i == n) std::cout << "> " << sizes[i - 1]; else std::cout << std::setw(16) << sizes[i]; std::cout << " bytes: " << count[i] << '\n'; } std::cout << "Number of files: " << files << '\n'; std::cout << "Total file size: " << total_size << " bytes\n"; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); try { const char* directory(argc > 1 ? argv[1] : "."); std::filesystem::path path(directory); if (!is_directory(path)) { std::cerr << directory << " is not a directory.\n"; return EXIT_FAILURE; } file_size_distribution(path); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "log" "os" "sort" ) func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
#include <iostream> #include <set> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; int main(void) { fs::path p(fs::current_path()); std::set<std::string> tree; for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it) tree.insert(it->path().filename().native()); for (auto entry : tree) std::cout << entry << '\n'; }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; int i = 0; for( int curRow = 0; curRow < sz; curRow++ ) { for( int curCol = 0; curCol < sz; curCol++ ) { sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; i++; } } } int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s( 8 ); s.display(); return 0; }
Produce a functionally identical C++ code for the snippet given in Go.
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; int i = 0; for( int curRow = 0; curRow < sz; curRow++ ) { for( int curCol = 0; curCol < sz; curCol++ ) { sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; i++; } } } int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s( 8 ); s.display(); return 0; }
Write a version of this Go function in C++ with identical behavior.
package main import ( "fmt" "math" ) const CONST = 0x2545F4914F6CDD1D type XorshiftStar struct{ state uint64 } func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} } func (xor *XorshiftStar) seed(state uint64) { xor.state = state } func (xor *XorshiftStar) nextInt() uint32 { x := xor.state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) xor.state = x return uint32((x * CONST) >> 32) } func (xor *XorshiftStar) nextFloat() float64 { return float64(xor.nextInt()) / (1 << 32) } func main() { randomGen := XorshiftStarNew(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
#include <array> #include <cstdint> #include <iostream> class XorShiftStar { private: const uint64_t MAGIC = 0x2545F4914F6CDD1D; uint64_t state; public: void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x >> 27); state = x; answer = ((x * MAGIC) >> 32); return answer; } float next_float() { return (float)next_int() / (1LL << 32); } }; int main() { auto rng = new XorShiftStar(); rng->seed(1234567); std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << '\n'; std::array<int, 5> counts = { 0, 0, 0, 0, 0 }; rng->seed(987654321); for (int i = 0; i < 100000; i++) { int j = (int)floor(rng->next_float() * 5.0); counts[j]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; } return 0; }
Convert this Go snippet to C++ and keep its semantics consistent.
package main import ( "fmt" "strings" "unicode" ) func main() { f := NewFourIsSeq() fmt.Print("The lengths of the first 201 words are:") for i := 1; i <= 201; i++ { if i%25 == 1 { fmt.Printf("\n%3d: ", i) } _, n := f.WordLen(i) fmt.Printf(" %2d", n) } fmt.Println() fmt.Println("Length of sentence so far:", f.TotalLength()) for i := 1000; i <= 1e7; i *= 10 { w, n := f.WordLen(i) fmt.Printf("Word %8d is %q, with %d letters.", i, w, n) fmt.Println(" Length of sentence so far:", f.TotalLength()) } } type FourIsSeq struct { i int words []string } func NewFourIsSeq() *FourIsSeq { return &FourIsSeq{ words: []string{ "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,", }, } } func (f *FourIsSeq) WordLen(w int) (string, int) { for len(f.words) < w { f.i++ n := countLetters(f.words[f.i]) ns := say(int64(n)) os := sayOrdinal(int64(f.i+1)) + "," f.words = append(f.words, strings.Fields(ns)...) f.words = append(f.words, "in", "the") f.words = append(f.words, strings.Fields(os)...) } word := f.words[w-1] return word, countLetters(word) } func (f FourIsSeq) TotalLength() int { cnt := 0 for _, w := range f.words { cnt += len(w) + 1 } return cnt - 1 } func countLetters(s string) int { cnt := 0 for _, r := range s { if unicode.IsLetter(r) { cnt++ } } return cnt }
#include <cctype> #include <cstdint> #include <iomanip> #include <iostream> #include <string> #include <vector> struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; uint64_t number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "biliionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(uint64_t n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } size_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) { size_t count = 0; if (n < 20) { result.push_back(get_name(small[n], ordinal)); count = 1; } else if (n < 100) { if (n % 10 == 0) { result.push_back(get_name(tens[n/10 - 2], ordinal)); } else { std::string name(get_name(tens[n/10 - 2], false)); name += "-"; name += get_name(small[n % 10], ordinal); result.push_back(name); } count = 1; } else { const named_number& num = get_named_number(n); uint64_t p = num.number; count += append_number_name(result, n/p, false); if (n % p == 0) { result.push_back(get_name(num, ordinal)); ++count; } else { result.push_back(get_name(num, false)); ++count; count += append_number_name(result, n % p, ordinal); } } return count; } size_t count_letters(const std::string& str) { size_t letters = 0; for (size_t i = 0, n = str.size(); i < n; ++i) { if (isalpha(static_cast<unsigned char>(str[i]))) ++letters; } return letters; } std::vector<std::string> sentence(size_t count) { static const char* words[] = { "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence," }; std::vector<std::string> result; result.reserve(count + 10); size_t n = std::size(words); for (size_t i = 0; i < n && i < count; ++i) { result.push_back(words[i]); } for (size_t i = 1; count > n; ++i) { n += append_number_name(result, count_letters(result[i]), false); result.push_back("in"); result.push_back("the"); n += 2; n += append_number_name(result, i + 1, true); result.back() += ','; } return result; } size_t sentence_length(const std::vector<std::string>& words) { size_t n = words.size(); if (n == 0) return 0; size_t length = n - 1; for (size_t i = 0; i < n; ++i) length += words[i].size(); return length; } int main() { std::cout.imbue(std::locale("")); size_t n = 201; auto result = sentence(n); std::cout << "Number of letters in first " << n << " words in the sequence:\n"; for (size_t i = 0; i < n; ++i) { if (i != 0) std::cout << (i % 25 == 0 ? '\n' : ' '); std::cout << std::setw(2) << count_letters(result[i]); } std::cout << '\n'; std::cout << "Sentence length: " << sentence_length(result) << '\n'; for (n = 1000; n <= 10000000; n *= 10) { result = sentence(n); const std::string& word = result[n - 1]; std::cout << "The " << n << "th word is '" << word << "' and has " << count_letters(word) << " letters. "; std::cout << "Sentence length: " << sentence_length(result) << '\n'; } return 0; }
Write the same algorithm in C++ as shown in this Go implementation.
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { var lines []string for _, line := range strings.Split(diagram, "\n") { line = strings.Trim(line, " \t") if line != "" { lines = append(lines, line) } } if len(lines) == 0 { log.Fatal("diagram has no non-empty lines!") } width := len(lines[0]) cols := (width - 1) / 3 if cols != 8 && cols != 16 && cols != 32 && cols != 64 { log.Fatal("number of columns should be 8, 16, 32 or 64") } if len(lines)%2 == 0 { log.Fatal("number of non-empty lines should be odd") } if lines[0] != strings.Repeat("+--", cols)+"+" { log.Fatal("incorrect header line") } for i, line := range lines { if i == 0 { continue } else if i%2 == 0 { if line != lines[0] { log.Fatal("incorrect separator line") } } else if len(line) != width { log.Fatal("inconsistent line widths") } else if line[0] != '|' || line[width-1] != '|' { log.Fatal("non-separator lines must begin and end with '|'") } } return lines } func decode(lines []string) []result { fmt.Println("Name Bits Start End") fmt.Println("======= ==== ===== ===") start := 0 width := len(lines[0]) var results []result for i, line := range lines { if i%2 == 0 { continue } line := line[1 : width-1] for _, name := range strings.Split(line, "|") { size := (len(name) + 1) / 3 name = strings.TrimSpace(name) res := result{name, size, start, start + size - 1} results = append(results, res) fmt.Println(res) start += size } } return results } func unpack(results []result, hex string) { fmt.Println("\nTest string in hex:") fmt.Println(hex) fmt.Println("\nTest string in binary:") bin := hex2bin(hex) fmt.Println(bin) fmt.Println("\nUnpacked:\n") fmt.Println("Name Size Bit pattern") fmt.Println("======= ==== ================") for _, res := range results { fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1]) } } func hex2bin(hex string) string { z := new(big.Int) z.SetString(hex, 16) return fmt.Sprintf("%0*b", 4*len(hex), z) } func main() { const diagram = ` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ` lines := validate(diagram) fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n") for _, line := range lines { fmt.Println(line) } fmt.Println("\nDecoded:\n") results := decode(lines) hex := "78477bbf5496e12e1bf169a4" unpack(results, hex) }
#include <array> #include <bitset> #include <iostream> using namespace std; struct FieldDetails {string_view Name; int NumBits;}; template <const char *T> consteval auto ParseDiagram() { constexpr string_view rawArt(T); constexpr auto firstBar = rawArt.find("|"); constexpr auto lastBar = rawArt.find_last_of("|"); constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar); static_assert(firstBar < lastBar, "ASCII Table has no fields"); constexpr auto numFields = count(rawArt.begin(), rawArt.end(), '|') - count(rawArt.begin(), rawArt.end(), '\n') / 2; array<FieldDetails, numFields> fields; bool isValidDiagram = true; int startDiagramIndex = 0; int totalBits = 0; for(int i = 0; i < numFields; ) { auto beginningBar = art.find("|", startDiagramIndex); auto endingBar = art.find("|", beginningBar + 1); auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1); if(field.find("-") == field.npos) { int numBits = (field.size() + 1) / 3; auto nameStart = field.find_first_not_of(" "); auto nameEnd = field.find_last_not_of(" "); if (nameStart > nameEnd || nameStart == string_view::npos) { isValidDiagram = false; field = ""sv; } else { field = field.substr(nameStart, 1 + nameEnd - nameStart); } fields[i++] = FieldDetails {field, numBits}; totalBits += numBits; } startDiagramIndex = endingBar; } int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0; return make_pair(fields, numRawBytes); } template <const char *T> auto Encode(auto inputValues) { constexpr auto parsedDiagram = ParseDiagram<T>(); static_assert(parsedDiagram.second > 0, "Invalid ASCII talble"); array<unsigned char, parsedDiagram.second> data; int startBit = 0; int i = 0; for(auto value : inputValues) { const auto &field = parsedDiagram.first[i++]; int remainingValueBits = field.NumBits; while(remainingValueBits > 0) { auto [fieldStartByte, fieldStartBit] = div(startBit, 8); int unusedBits = 8 - fieldStartBit; int numBitsToEncode = min({unusedBits, 8, field.NumBits}); int divisor = 1 << (remainingValueBits - numBitsToEncode); unsigned char bitsToEncode = value / divisor; data[fieldStartByte] <<= numBitsToEncode; data[fieldStartByte] |= bitsToEncode; value %= divisor; startBit += numBitsToEncode; remainingValueBits -= numBitsToEncode; } } return data; } template <const char *T> void Decode(auto data) { cout << "Name Bit Pattern\n"; cout << "======= ================\n"; constexpr auto parsedDiagram = ParseDiagram<T>(); static_assert(parsedDiagram.second > 0, "Invalid ASCII talble"); int startBit = 0; for(const auto& field : parsedDiagram.first) { auto [fieldStartByte, fieldStartBit] = div(startBit, 8); unsigned char firstByte = data[fieldStartByte]; firstByte <<= fieldStartBit; firstByte >>= fieldStartBit; int64_t value = firstByte; auto endBit = startBit + field.NumBits; auto [fieldEndByte, fieldEndBit] = div(endBit, 8); fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1)); for(int index = fieldStartByte + 1; index <= fieldEndByte; index++) { value <<= 8; value += data[index]; } value >>= fieldEndBit; startBit = endBit; cout << field.Name << string_view(" ", (7 - field.Name.size())) << " " << string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) << "\n"; } } int main(void) { static constexpr char art[] = R"( +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)"; auto rawData = Encode<art> (initializer_list<int64_t> { 30791, 0, 15, 0, 1, 1, 1, 3, 15, 21654, 57646, 7153, 27044 }); cout << "Raw encoded data in hex:\n"; for (auto v : rawData) printf("%.2X", v); cout << "\n\n"; cout << "Decoded raw data:\n"; Decode<art>(rawData); }
Convert this Go block to C++, preserving its control flow and logic.
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
#include <algorithm> #include <coroutine> #include <iostream> #include <memory> #include <tuple> #include <variant> using namespace std; class BinaryTree { using Node = tuple<BinaryTree, int, BinaryTree>; unique_ptr<Node> m_tree; public: BinaryTree() = default; BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild) : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {} BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){} BinaryTree(BinaryTree&& leftChild, int value) : BinaryTree(move(leftChild), value, BinaryTree{}){} BinaryTree(int value, BinaryTree&& rightChild) : BinaryTree(BinaryTree{}, value, move(rightChild)){} explicit operator bool() const { return (bool)m_tree; } int Value() const { return get<1>(*m_tree); } const BinaryTree& LeftChild() const { return get<0>(*m_tree); } const BinaryTree& RightChild() const { return get<2>(*m_tree); } }; struct TreeWalker { struct promise_type { int val; suspend_never initial_suspend() noexcept {return {};} suspend_never return_void() noexcept {return {};} suspend_always final_suspend() noexcept {return {};} void unhandled_exception() noexcept { } TreeWalker get_return_object() { return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)}; } suspend_always yield_value(int x) noexcept { val=x; return {}; } }; coroutine_handle<promise_type> coro; TreeWalker(coroutine_handle<promise_type> h): coro(h) {} ~TreeWalker() { if(coro) coro.destroy(); } class Iterator { const coroutine_handle<promise_type>* m_h = nullptr; public: Iterator() = default; constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){} Iterator& operator++() { m_h->resume(); return *this; } Iterator operator++(int) { auto old(*this); m_h->resume(); return old; } int operator*() const { return m_h->promise().val; } bool operator!=(monostate) const noexcept { return !m_h->done(); return m_h && !m_h->done(); } bool operator==(monostate) const noexcept { return !operator!=(monostate{}); } }; constexpr Iterator begin() const noexcept { return Iterator(&coro); } constexpr monostate end() const noexcept { return monostate{}; } }; namespace std { template<> class iterator_traits<TreeWalker::Iterator> { public: using difference_type = std::ptrdiff_t; using size_type = std::size_t; using value_type = int; using pointer = int*; using reference = int&; using iterator_category = std::input_iterator_tag; }; } TreeWalker WalkFringe(const BinaryTree& tree) { if(tree) { auto& left = tree.LeftChild(); auto& right = tree.RightChild(); if(!left && !right) { co_yield tree.Value(); } for(auto v : WalkFringe(left)) { co_yield v; } for(auto v : WalkFringe(right)) { co_yield v; } } co_return; } void PrintTree(const BinaryTree& tree) { if(tree) { cout << "("; PrintTree(tree.LeftChild()); cout << tree.Value(); PrintTree(tree.RightChild()); cout <<")"; } } void Compare(const BinaryTree& tree1, const BinaryTree& tree2) { auto walker1 = WalkFringe(tree1); auto walker2 = WalkFringe(tree2); bool sameFringe = ranges::equal(walker1.begin(), walker1.end(), walker2.begin(), walker2.end()); PrintTree(tree1); cout << (sameFringe ? " has same fringe as " : " has different fringe than "); PrintTree(tree2); cout << "\n"; } int main() { BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77, BinaryTree{77, BinaryTree{9}}}); BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{ BinaryTree{3}, 77, BinaryTree{9}}}); BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}}); Compare(tree1, tree2); Compare(tree1, tree3); }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false } func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false } func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white } for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") } func main() { nms := [][2]int{ {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, } for _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.Println("No solution exists.\n") } } }
#include <iostream> #include <vector> enum class Piece { empty, black, white }; typedef std::pair<int, int> position; bool isAttacking(const position &queen, const position &pos) { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second); } bool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { auto pos = std::make_pair(i, j); for (auto queen : pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { goto inner; } } for (auto queen : pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.push_back(pos); placingBlack = false; } else { pWhiteQueens.push_back(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.pop_back(); pWhiteQueens.pop_back(); placingBlack = true; } inner: {} } } if (!placingBlack) { pBlackQueens.pop_back(); } return false; } void printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) { std::vector<Piece> board(n * n); std::fill(board.begin(), board.end(), Piece::empty); for (auto &queen : blackQueens) { board[queen.first * n + queen.second] = Piece::black; } for (auto &queen : whiteQueens) { board[queen.first * n + queen.second] = Piece::white; } for (size_t i = 0; i < board.size(); ++i) { if (i != 0 && i % n == 0) { std::cout << '\n'; } switch (board[i]) { case Piece::black: std::cout << "B "; break; case Piece::white: std::cout << "W "; break; case Piece::empty: default: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { std::cout << "x "; } else { std::cout << "* "; } break; } } std::cout << "\n\n"; } int main() { std::vector<position> nms = { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (auto nm : nms) { std::cout << nm.second << " black and " << nm.second << " white queens on a " << nm.first << " x " << nm.first << " board:\n"; std::vector<position> blackQueens, whiteQueens; if (place(nm.second, nm.first, blackQueens, whiteQueens)) { printBoard(nm.first, blackQueens, whiteQueens); } else { std::cout << "No solution exists.\n\n"; } } return 0; }
Rewrite the snippet below in C++ so it works the same as the original Go code.
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
while (true) std::cout << "SPAM\n";
Convert this Go block to C++, preserving its control flow and logic.
package main import ( "fmt" "rcu" "strconv" ) func equalSets(s1, s2 map[rune]bool) bool { if len(s1) != len(s2) { return false } for k, _ := range s1 { _, ok := s2[k] if !ok { return false } } return true } func main() { const limit = 100_000 count := 0 fmt.Println("Numbers under 100,000 which use the same digits in decimal or hex:") for n := 0; n < limit; n++ { h := strconv.FormatInt(int64(n), 16) hs := make(map[rune]bool) for _, c := range h { hs[c] = true } ns := make(map[rune]bool) for _, c := range strconv.Itoa(n) { ns[c] = true } if equalSets(hs, ns) { count++ fmt.Printf("%6s ", rcu.Commatize(n)) if count%10 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", count) }
#include <iostream> #include <iomanip> #include <bitset> const int LIMIT = 100000; std::bitset<16> digitset(int num, int base) { std::bitset<16> set; for (; num; num /= base) set.set(num % base); return set; } int main() { int c = 0; for (int i=0; i<LIMIT; i++) { if (digitset(i,10) == digitset(i,16)) { std::cout << std::setw(7) << i; if (++c % 10 == 0) std::cout << std::endl; } } std::cout << std::endl; return 0; }