Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this C++ function in Go with identical behavior.
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; ...
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } fun...
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c,...
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c,...
Can you help me rewrite this code in Go instead of C++, keeping it the same logically?
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c,...
Change the following C++ code into Go without altering its purpose.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if ...
Convert this C++ block to Go, preserving its control flow and logic.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if ...
Convert this C++ block to Go, preserving its control flow and logic.
#include <iomanip> #include <ctime> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25; class Cell { public: Cell() : val( 0 ), cntOverlap( 0 ) {} char val; int cntOverlap; }; class Word { public: ...
package main import ( "bufio" "fmt" "log" "math/rand" "os" "regexp" "strings" "time" ) var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}} const ( nRows = 10 nCols = nRows gridSize = nRows * nCols minWords = 25 ) var ( re...
Can you help me rewrite this code in Go instead of C++, keeping it the same logically?
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); pub...
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v...
Convert the following code from C++ to Go, ensuring the logic remains intact.
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); pub...
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v...
Please provide an equivalent version of this C++ code in Go.
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); pub...
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int unexported int } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } func examineAndModify(any interface{}) { v...
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#include <string> #include <fstream> #include <boost/serialization/string.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/base_object.hpp> #include <iostream> class Employee { public : Employee( ) { } Employee ( const std::string &dep ,...
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() { animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Colli...
Can you help me rewrite this code in Go instead of C++, keeping it the same logically?
#include <string> #include <fstream> #include <boost/serialization/string.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/base_object.hpp> #include <iostream> class Employee { public : Employee( ) { } Employee ( const std::string &dep ,...
package main import ( "encoding/gob" "fmt" "os" ) type printable interface { print() } func main() { animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Colli...
Translate this program into Go but keep the logic exactly as in C++.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; co...
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {le...
Convert the following code from C++ to Go, ensuring the logic remains intact.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; co...
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {le...
Port the following code from C++ to Go with equivalent syntax and logic.
#include <stdio.h> #include <math.h> int p(int year) { return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7; } int is_long_year(int year) { return p(year) == 4 || p(year - 1) == 3; } void print_long_years(int from, int to) { for (int year = from; year <= to; ++year) { if (is_long...
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j ...
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <iostream"> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> #include <numeric> using namespace std; const uint* binary(uint n, uint length); uint sum_subset_unrank_bin(const vector<uint>& d, uint r); vector<uint> factors(uint x); bool isPrime(uint number); bool isZum(uint n)...
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(div...
Produce a functionally identical Go code for the snippet given in C++.
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; ...
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates"...
Generate an equivalent Go version of this C++ code.
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; ...
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates"...
Please provide an equivalent version of this C++ code in Go.
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; ...
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates"...
Port the provided C++ code into Go while preserving the original functionality.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b...
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var ...
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b...
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var ...
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdexcept> int main() { throw std::runtime_error("boom"); }
package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
Please provide an equivalent version of this C++ code in Go.
#include <stdexcept> int main() { throw std::runtime_error("boom"); }
package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
Translate this program into Go but keep the logic exactly as in C++.
template<typename T> struct can_eat { private: template<typename U, void (U::*)()> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::eat>*); template<typename U> static int Test(...); public: static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char); }; struct pot...
type eatable interface { eat() }
Ensure the translated Go code behaves exactly like the original C++ snippet.
template<typename T> struct can_eat { private: template<typename U, void (U::*)()> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::eat>*); template<typename U> static int Test(...); public: static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char); }; struct pot...
type eatable interface { eat() }
Generate a Go translation of this C++ snippet without changing its computational steps.
#include <ctime> #include <iostream> #include <algorithm> #include <fstream> #include <string> #include <vector> #include <map> class markov { public: void create( std::string& file, unsigned int keyLen, unsigned int words ) { std::ifstream f( file.c_str(), std::ios_base::in ); fileBuffer = std::str...
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int...
Write the same code in Go as shown below in C++.
#include <iostream> #include <vector> #include <string> #include <list> #include <limits> #include <set> #include <utility> #include <algorithm> #include <iterator> typedef int vertex_t; typedef double weight_t; const weight_t max_weight = std::numeric_limits<double>::infinity(); struct neighbor { vertex_t ...
package main import ( "container/heap" "fmt" ) type PriorityQueue struct { items []Vertex m map[Vertex]int pr map[Vertex]int } func (pq *PriorityQueue) Len() int { return len(pq.items) } func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] } func (pq ...
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <algorithm> #include <iostream> #include <random> #include <vector> double uniform01() { static std::default_random_engine generator; static std::uniform_real_distribution<double> distribution(0.0, 1.0); return distribution(generator); } int bitCount(int i) { i -= ((i >> 1) & 0x55555555); ...
package main import ( "fmt" "math/rand" "time" ) type vector []float64 func e(n uint) vector { if n > 4 { panic("n must be less than 5") } result := make(vector, 32) result[1<<n] = 1.0 return result } func cdot(a, b vector) vector { return mul(vector{0.5}, add(mul(a, b), ...
Translate this program into Go but keep the logic exactly as in C++.
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { s...
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree {...
Generate a Go translation of this C++ snippet without changing its computational steps.
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { s...
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree {...
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> dict { {"One", 1}, {"Two", 2}, {"Three", 7} }; dict["Three"] = 3; std::cout << "One: " << dict["One"] << std::endl; std::cout << "Key/Value pairs: " << std::endl; for(auto& kv: dict) { std::cout <...
myMap := map[string]int { "hello": 13, "world": 31, "!" : 71 } for key, value := range myMap { fmt.Printf("key = %s, value = %d\n", key, value) } for key := range myMap { fmt.Printf("key = %s\n", key) } for _, value := range myMap { fmt.Printf("value = %d\n", value) }
Convert this C++ block to Go, preserving its control flow and logic.
#include <stdexcept> class tiny_int { public: tiny_int(int i): value(i) { if (value < 1) throw std::out_of_range("tiny_int: value smaller than 1"); if (value > 10) throw std::out_of_range("tiny_int: value larger than 10"); } operator int() const { return value; } tiny_int& ope...
package main import "fmt" type TinyInt int func NewTinyInt(i int) TinyInt { if i < 1 { i = 1 } else if i > 10 { i = 10 } return TinyInt(i) } func (t1 TinyInt) Add(t2 TinyInt) TinyInt { return NewTinyInt(int(t1) + int(t2)) } func (t1 TinyInt) Sub(t2 TinyInt) TinyInt { return ...
Translate the given C++ code snippet into Go without altering its behavior.
#include <algorithm> #include <iostream> template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; delete ri...
package avl type Key interface { Less(Key) bool Eq(Key) bool } type Node struct { Data Key Balance int Link [2]*Node } func opp(dir int) int { return 1 - dir } func single(root *Node, dir int) *Node { save := root.Link[opp(dir)] root.Link[opp(dir)] = save...
Maintain the same structure and functionality when rewriting this code in Go.
#include <algorithm> #include <iostream> template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; delete ri...
package avl type Key interface { Less(Key) bool Eq(Key) bool } type Node struct { Data Key Balance int Link [2]*Node } func opp(dir int) int { return 1 - dir } func single(root *Node, dir int) *Node { save := root.Link[opp(dir)] root.Link[opp(dir)] = save...
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <iomanip> #include <iostream> #include <boost/multiprecision/cpp_int.hpp> template <typename IntegerType> IntegerType arithmetic_derivative(IntegerType n) { bool negative = n < 0; if (negative) n = -n; if (n < 2) return 0; IntegerType sum = 0, count = 0, m = n; while ((m &...
package main import ( "fmt" "rcu" ) func D(n float64) float64 { if n < 0 { return -D(-n) } if n < 2 { return 0 } var f []int if n < 1e19 { f = rcu.PrimeFactors(int(n)) } else { g := int(n / 100) f = rcu.PrimeFactors(g) f = append(f, [...
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iostream> int main() { std::string str("AABBBC"); int count = 0; do { std::cout << str << (++count % 10 == 0 ? '\n' : ' '); } while (std::next_permutation(str.begin(), str.end())); }
package main import "fmt" func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) ...
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#include <cmath> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <sstream> #include <stack> #include <string> #include <tuple> int main() { std::ofstream out("penrose_tiling.svg"); if (!out) { std::cerr << "Cannot open output file.\n"; return...
package main import ( "github.com/fogleman/gg" "math" ) type tiletype int const ( kite tiletype = iota dart ) type tile struct { tt tiletype x, y float64 angle, size float64 } var gr = (1 + math.Sqrt(5)) / 2 const theta = math.Pi / 5 func setupPrototiles(w, h int) []...
Generate a Go translation of this C++ snippet without changing its computational steps.
#include <windows.h> #include <iostream> #include <ctime> const int WID = 79, HEI = 22; const float NCOUNT = ( float )( WID * HEI ); class coord : public COORD { public: coord( short x = 0, short y = 0 ) { set( x, y ); } void set( short x, short y ) { X = x; Y = y; } }; class winConsole { public: static w...
package main import ( "fmt" "github.com/nsf/termbox-go" "log" "math/rand" "strconv" "time" ) type coord struct{ x, y int } const ( width = 79 height = 22 nCount = float64(width * height) ) var ( board [width * height]int score = 0 bold = termbox.AttrBold curs...
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <windows.h> #include <iostream> #include <ctime> const int WID = 79, HEI = 22; const float NCOUNT = ( float )( WID * HEI ); class coord : public COORD { public: coord( short x = 0, short y = 0 ) { set( x, y ); } void set( short x, short y ) { X = x; Y = y; } }; class winConsole { public: static w...
package main import ( "fmt" "github.com/nsf/termbox-go" "log" "math/rand" "strconv" "time" ) type coord struct{ x, y int } const ( width = 79 height = 22 nCount = float64(width * height) ) var ( board [width * height]int score = 0 bold = termbox.AttrBold curs...
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <iomanip> #include <iostream> int prime_factor_sum(int n) { int sum = 0; for (; (n & 1) == 0; n >>= 1) sum += 2; for (int p = 3, sq = 9; sq <= n; p += 2) { for (; n % p == 0; n /= p) sum += p; sq += (p + 1) << 2; } if (n > 1) sum += n; return...
package main import ( "fmt" "rcu" ) func prune(a []int) []int { prev := a[0] b := []int{prev} for i := 1; i < len(a); i++ { if a[i] != prev { b = append(b, a[i]) prev = a[i] } } return b } func main() { var resF, resD, resT, factors1 []int f...
Generate a Go translation of this C++ snippet without changing its computational steps.
#include <iomanip> #include <iostream> #include <numeric> #include <sstream> bool duffinian(int n) { if (n == 2) return false; int total = 1, power = 2, m = n; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (int p = 3; p * p <= n; p += 2) { int sum = 1; f...
package main import ( "fmt" "math" "rcu" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { limit := 200000 d := rcu.PrimeSieve(limit-1, true) d[1] = false for i := 2; i < limit; i++ { if !d[i] { continue } ...
Convert this C++ block to Go, preserving its control flow and logic.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(int limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) ...
package main import ( "fmt" "math" "rcu" "sort" ) func main() { const limit = 1000000 limit2 := int(math.Cbrt(limit)) primes := rcu.Primes(limit / 6) pc := len(primes) var sphenic []int fmt.Println("Sphenic numbers less than 1,000:") for i := 0; i < pc-2; i++ { if ...
Keep all operations the same but rewrite the snippet in Go.
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { ...
package main import "fmt" type any = interface{} func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, inn...
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <any> #include <iostream> #include <iterator> #include <vector> using namespace std; vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1) { vector<any> tree; while (first < last && depth <= *first) { if(*first == depth) { ...
package main import "fmt" type any = interface{} func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, inn...
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <map> #include <set> #include <regex> using namespace std; map<string, string> terminals; map<string, vector<vector<string>>> nonterminalRules; map<string, set<string>> nonterminalFirst; map<string, vector<string>> nonterminalCode; i...
package main import ( "fmt" "go/ast" "go/parser" "log" ) func labelStr(label int) string { return fmt.Sprintf("_%04d", label) } type binexp struct { op, left, right string kind, index int } func main() { x := "(one + two) * three - four * five" fmt.Println("Expression to pars...
Port the provided C++ code into Go while preserving the original functionality.
#include<iostream> #include<string> #include<boost/filesystem.hpp> #include<boost/format.hpp> #include<boost/iostreams/device/mapped_file.hpp> #include<optional> #include<algorithm> #include<iterator> #include<execution> #include"dependencies/xxhash.hpp" template<typename T, typename V, typename F> size_t for_each_...
package main import ( "fmt" "crypto/md5" "io/ioutil" "log" "os" "path/filepath" "sort" "time" ) type fileData struct { filePath string info os.FileInfo } type hash [16]byte func check(err error) { if err != nil { log.Fatal(err) } } func checksum(filePath ...
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t p = 3; ; p += 2) { ...
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(499) var sprimes []int for _, p := range primes { digits := rcu.Digits(p, 10) var b1 = true for _, d := range digits { if !rcu.IsPrime(d) { b1 = false break ...
Translate this program into Go but keep the logic exactly as in C++.
#include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t p = 3; ; p += 2) { ...
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(499) var sprimes []int for _, p := range primes { digits := rcu.Digits(p, 10) var b1 = true for _, d := range digits { if !rcu.IsPrime(d) { b1 = false break ...
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> using integer = boost::multiprecision::cpp_int; using rational = boost::rational<integer>; integer sylvester_next(const integer& n) { return n * n - n + 1; } int main() { std::cout << "First 10 el...
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) two := big.NewInt(2) next := new(big.Int) sylvester := []*big.Int{two} prod := new(big.Int).Set(two) count := 1 for count < 10 { next.Add(prod, one) sylvester = append(sylvester, new(big.Int...
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx...
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x......
Port the provided C++ code into Go while preserving the original functionality.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx...
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x......
Please provide an equivalent version of this C++ code in Go.
#include <iostream> #include <vector> #include <algorithm> #include <string> template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; } template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::vector...
package main import ( "fmt" "sort" "strings" ) type indexSort struct { val sort.Interface ind []int } func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], ...
Convert this C++ block to Go, preserving its control flow and logic.
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either op...
var m = ` leading spaces and blank lines`
Generate an equivalent Go version of this C++ code.
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either op...
var m = ` leading spaces and blank lines`
Produce a functionally identical Go code for the snippet given in C++.
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"...
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah"...
Change the following C++ code into Go without altering its purpose.
#include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <numeric> #include <vector> class prime_counter { public: explicit prime_counter(int limit); int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); } private: std::vector<int> count_; }; prime_counter::prime_count...
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < l...
Generate an equivalent Go version of this C++ code.
#include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <numeric> #include <vector> class prime_counter { public: explicit prime_counter(int limit); int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); } private: std::vector<int> count_; }; prime_counter::prime_count...
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < l...
Convert this C++ block to Go, preserving its control flow and logic.
#include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <numeric> #include <vector> class prime_counter { public: explicit prime_counter(int limit); int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); } private: std::vector<int> count_; }; prime_counter::prime_count...
package main import ( "fmt" "math" "rcu" "time" ) var count []int func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < l...
Produce a functionally identical Go code for the snippet given in C++.
#include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::uint128_t; template <typename T> void unique_sort(std::vector<T>& vector) { std::sort(vector.begin(), vector...
package main import ( "fmt" "math" "sort" ) func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } ...
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::uint128_t; template <typename T> void unique_sort(std::vector<T>& vector) { std::sort(vector.begin(), vector...
package main import ( "fmt" "math" "sort" ) func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } ...
Convert the following code from C++ to Go, ensuring the logic remains intact.
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; ...
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } ...
Convert this C++ snippet to Go and keep its semantics consistent.
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; ...
package main import ( "fmt" "rcu" "sort" ) func main() { primes := rcu.Primes(333) var oss []int for i := 1; i < len(primes)-1; i++ { for j := i + 1; j < len(primes); j++ { n := primes[i] * primes[j] if n >= 1000 { break } ...
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std:...
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
Translate the given C++ code snippet into Go without altering its behavior.
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std:...
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
Produce a functionally identical Go code for the snippet given in C++.
#include <string> #include <vector> #include <map> #include <iostream> #include <algorithm> #include <utility> #include <sstream> std::string mostFreqKHashing ( const std::string & input , int k ) { std::ostringstream oss ; std::map<char, int> frequencies ; for ( char c : input ) { frequencies[ c ] = st...
package main import ( "fmt" "sort" ) type cf struct { c rune f int } func reverseStr(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func indexOfCf(cfs []cf, r rune) i...
Translate the given C++ code snippet into Go without altering its behavior.
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit pal...
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
Maintain the same structure and functionality when rewriting this code in Go.
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit pal...
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <bitset> #include <cctype> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> bool contains_all_vowels_once(const std::string& word) { std::bitset<5> vowels; for (char ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); size_t bit = 0; swit...
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := ran...
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <algorithm> #include <fstream> #include <iostream> #include <numeric> #include <string> #include <vector> int levenshtein_distance(const std::string& str1, const std::string& str2) { size_t m = str1.size(), n = str2.size(); std::vector<int> cost(n + 1); std::iota(cost.begin(), cost.end(), 0); ...
package main import ( "bytes" "fmt" "io/ioutil" "log" ) func levenshtein(s, t string) int { d := make([][]int, len(s)+1) for i := range d { d[i] = make([]int, len(t)+1) } for i := range d { d[i][0] = i } for j := range d[0] { d[0][j] = j } for j ...
Port the provided C++ code into Go while preserving the original functionality.
#include <array> #include <iostream> #include <map> #include <vector> #include <primesieve.hpp> using digit_set = std::array<int, 10>; digit_set get_digits(uint64_t n) { digit_set result = {}; for (; n > 0; n /= 10) ++result[n % 10]; return result; } int main() { std::cout.imbue(std::locale(...
package main import ( "fmt" "rcu" "sort" ) func main() { const limit = int(1e10) const maxIndex = 9 primes := rcu.Primes(limit) anaprimes := make(map[int][]int) for _, p := range primes { digs := rcu.Digits(p, 10) key := 1 for _, dig := range digs { ...
Keep all operations the same but rewrite the snippet in Go.
#include <iostream> #include <optional> using namespace std; class TropicalAlgebra { optional<double> m_value; public: friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&); friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept; Tr...
package main import ( "fmt" "log" "math" ) var MinusInf = math.Inf(-1) type MaxTropical struct{ r float64 } func newMaxTropical(r float64) MaxTropical { if math.IsInf(r, 1) || math.IsNaN(r) { log.Fatal("Argument must be a real number or negative infinity.") } return MaxTropical{r} } ...
Generate a Go translation of this C++ snippet without changing its computational steps.
#include <windows.h> #include <iostream> #include <string> using namespace std; const int PLAYERS = 4, MAX_POINTS = 100; enum Moves { ROLL, HOLD }; class player { public: player() { current_score = round_score = 0; } void addCurrScore() { current_score += round_score; } ...
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
Write a version of this C++ function in Go with identical behavior.
#include <windows.h> #include <iostream> #include <string> using namespace std; const int PLAYERS = 4, MAX_POINTS = 100; enum Moves { ROLL, HOLD }; class player { public: player() { current_score = round_score = 0; } void addCurrScore() { current_score += round_score; } ...
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( gameOver = iota pigged...
Write a version of this C++ function in Go with identical behavior.
class NG_8 : public matrixNG { private: int a12, a1, a2, a, b12, b1, b2, b, t; double ab, a1b1, a2b2, a12b12; const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;} const bool needTerm() { if (b1==0 and b==0 and b2==0 and b12==0) return false; if (b==0){cfn = b2==0? 0:1; return tr...
package cf import "math" type NG8 struct { A12, A1, A2, A int64 B12, B1, B2, B int64 } var ( NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1} NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1} NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1} NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0} ) func (ng *NG8) needsIngest() bool { if ng.B12 ...
Port the provided C++ code into Go while preserving the original functionality.
class NG_8 : public matrixNG { private: int a12, a1, a2, a, b12, b1, b2, b, t; double ab, a1b1, a2b2, a12b12; const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;} const bool needTerm() { if (b1==0 and b==0 and b2==0 and b12==0) return false; if (b==0){cfn = b2==0? 0:1; return tr...
package cf import "math" type NG8 struct { A12, A1, A2, A int64 B12, B1, B2, B int64 } var ( NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1} NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1} NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1} NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0} ) func (ng *NG8) needsIngest() bool { if ng.B12 ...
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <iomanip> #include <iostream> bool nondecimal(unsigned int n) { for (; n > 0; n >>= 4) { if ((n & 0xF) > 9) return true; } return false; } int main() { unsigned int count = 0; for (unsigned int n = 0; n < 501; ++n) { if (nondecimal(n)) { ++count; ...
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 ...
Produce a functionally identical Go code for the snippet given in C++.
#include <iomanip> #include <iostream> bool nondecimal(unsigned int n) { for (; n > 0; n >>= 4) { if ((n & 0xF) > 9) return true; } return false; } int main() { unsigned int count = 0; for (unsigned int n = 0; n < 501; ++n) { if (nondecimal(n)) { ++count; ...
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 ...
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <map> #include <vector> #include <primesieve.hpp> class erdos_selfridge { public: explicit erdos_selfridge(int limit); uint64_t get_prime(int index) const { return primes_[index].first; } int get_category(int index); ...
package main import ( "fmt" "math" "rcu" ) var limit = int(math.Log(1e6) * 1e6 * 1.2) var primes = rcu.Primes(limit) var prevCats = make(map[int]int) func cat(p int) int { if v, ok := prevCats[p]; ok { return v } pf := rcu.PrimeFactors(p + 1) all := true for _, f := range pf...
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <algorithm> #include <iomanip> #include <iostream> #include <list> struct range { range(int lo, int hi) : low(lo), high(hi) {} int low; int high; }; std::ostream& operator<<(std::ostream& out, const range& r) { return out << r.low << '-' << r.high; } class ranges { public: ranges() {} ...
package main import ( "fmt" "strings" ) type rng struct{ from, to int } type fn func(rngs *[]rng, n int) func (r rng) String() string { return fmt.Sprintf("%d-%d", r.from, r.to) } func rangesAdd(rngs []rng, n int) []rng { if len(rngs) == 0 { rngs = append(rngs, rng{n, n}) return rngs ...
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <cassert> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> using big_int = mpz_class; auto juggler(int n) { assert(n >= 1); int count = 0, max_count = 0; big_int a = n, max = n; while (a != 1) { if (a % 2 == 0) a = sqrt(a); else ...
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 max...
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <cassert> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> using big_int = mpz_class; auto juggler(int n) { assert(n >= 1); int count = 0, max_count = 0; big_int a = n, max = n; while (a != 1) { if (a % 2 == 0) a = sqrt(a); else ...
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 max...
Write the same algorithm in Go as shown in this C++ implementation.
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_square { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std...
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.C...
Change the programming language of this snippet from C++ to Go without modifying what it does.
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t primes[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; for (au...
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x ui...
Write the same code in Go as shown below in C++.
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t primes[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; for (au...
package main import ( "fmt" "math" "sort" ) const adj = 0.0001 var primes = []uint64{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } func isSquareFree(x ui...
Translate this program into Go but keep the logic exactly as in C++.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> void reverse(std::istream& in, std::ostream& out) { constexpr size_t record_length = 80; char record[record_length]; while (in.read(record, record_length)) { std::reverse(std::begin(record), std::end(record)); ou...
package main import ( "fmt" "log" "os" "os/exec" ) func reverseBytes(bytes []byte) { for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { bytes[i], bytes[j] = bytes[j], bytes[i] } } func check(err error) { if err != nil { log.Fatal(err) } } func main() { in, err ...
Translate the given C++ code snippet into Go without altering its behavior.
#include <cstdlib> #include <fstream> #include <iostream> int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string w...
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) count := 0 for _, bword := range bword...
Change the following C++ code into Go without altering its purpose.
#include <iostream> bool is_giuga(unsigned int n) { unsigned int m = n / 2; auto test_factor = [&m, n](unsigned int p) -> bool { if (m % p != 0) return true; m /= p; return m % p != 0 && (n / p - 1) % p == 0; }; if (!test_factor(3) || !test_factor(5)) return...
package main import "fmt" var factors []int var inc = []int{4, 2, 4, 2, 4, 6, 2, 6} func primeFactors(n int) { factors = factors[:0] factors = append(factors, 2) last := 2 n /= 2 for n%3 == 0 { if last == 3 { factors = factors[:0] return } last = ...
Convert this C++ block to Go, preserving its control flow and logic.
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int deg...
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
Write a version of this C++ function in Go with identical behavior.
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int deg...
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
Write the same algorithm in Go as shown in this C++ implementation.
#include <cmath> #include <cstdlib> #include <iomanip> #include <iostream> int divisor_count(int n) { int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (int p = 3; p * p <= n; p += 2) { int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; ...
package main import ( "fmt" "rcu" ) func countDivisors(n int) int { count := 0 i := 1 k := 1 if n%2 == 1 { k = 2 } for ; i*i <= n; i += k { if n%i == 0 { count++ j := n / i if j != i { count++ } } ...
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include <cmath> #include <cstdlib> #include <iomanip> #include <iostream> int divisor_count(int n) { int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (int p = 3; p * p <= n; p += 2) { int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; ...
package main import ( "fmt" "rcu" ) func countDivisors(n int) int { count := 0 i := 1 k := 1 if n%2 == 1 { k = 2 } for ; i*i <= n; i += k { if n%i == 0 { count++ j := n / i if j != i { count++ } } ...
Change the programming language of this snippet from C++ to Go without modifying what it does.
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <string> #include <utility> #include <vector> using word_list = std::vector<std::pair<std::string, std::string>>; void print_words(std::ostream& out, const word_list& words) { int n = 1; for (const auto& pair ...
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords))...
Generate an equivalent Go version of this C++ code.
#include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> #include <utility> #include <vector> class nest_tree; bool operator==(const nest_tree&, const nest_tree&); class nest_tree { public: explicit nest_tree(const std::string& name) : name_(name) {} nest_tree& add_child(con...
package main import ( "fmt" "io" "os" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.Fprin...
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
Keep all operations the same but rewrite the snippet in Go.
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
Change the programming language of this snippet from C++ to Go without modifying what it does.
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { ...
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" "strings" ) func main() { limit := 2700 primes := rcu.Primes(limit) s := new(big.Int) for b := 2; b <= 36; b++ { var rPrimes []int for _, p := range primes { s.SetString(strings.Repeat("1", p), b) ...
Port the following code from C++ to Go with equivalent syntax and logic.
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { ...
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" "strings" ) func main() { limit := 2700 primes := rcu.Primes(limit) s := new(big.Int) for b := 2; b <= 36; b++ { var rPrimes []int for _, p := range primes { s.SetString(strings.Repeat("1", p), b) ...
Produce a functionally identical Go code for the snippet given in C++.
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod;...
package main import ( "fmt" "math/big" ) func main() { zero := big.NewInt(0) one := big.NewInt(1) for k := int64(2); k <= 10; k += 2 { bk := big.NewInt(k) fmt.Println("The first 50 Curzon numbers using a base of", k, ":") count := 0 n := int64(1) pow := big....