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. |
import <iostream>;
|
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
Port the provided C++ code into Go while preserving the original functionality. |
import <iostream>;
|
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #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;
}
| 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
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #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;
};
| 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())
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #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;
}
| 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))
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #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;
}
| 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))
}
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | T* foo = new(arena) T;
| 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)
}
|
Change the following C++ code into Go without altering its purpose. | T* foo = new(arena) T;
| 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)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | T* foo = new(arena) T;
| 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)
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #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;
}
| 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)
}
|
Generate an equivalent Go version of this C++ code. | #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;
}
| 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)
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #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;
}
| 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)
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #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;
}
| 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)
}
|
Write the same code in Go as shown below in C++. | #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;
}
| 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])
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #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>";
}
| 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")
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #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 ;
}
| 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)
}
}
}
|
Produce a functionally identical Go code for the snippet given in C++. | auto strA = R"(this is
a newline-separated
raw string)";
| ch := 'z'
ch = 122
ch = '\x7a'
ch = '\u007a'
ch = '\U0000007a'
ch = '\172'
|
Convert this C++ block to Go, preserving its control flow and logic. | #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;
}
| 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)
}
}
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #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);
}
| 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)
}
|
Port the provided C++ code into Go while preserving the original functionality. | #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;
}
| 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)
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #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;
}
| 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
}
|
Produce a functionally identical Go code for the snippet given in C++. | #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;
}
| 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)
}
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
| const (
apple = iota
banana
cherry
)
|
Port the provided C++ code into Go while preserving the original functionality. | #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;
}
| 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()
}
|
Keep all operations the same but rewrite the snippet in Go. | #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");
}
| 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, ", "))
}
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #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;
}
|
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]
}
|
Generate an equivalent Go version of this C++ code. | #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;
}
|
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]
}
|
Port the provided C++ code into Go while preserving the original functionality. | #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;
}
| 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()
}
}
|
Write a version of this C++ function in Go with identical behavior. | #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;
}
| 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
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #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;
}
| 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)
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #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;
}
| 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
}
|
Port the provided C++ code into Go while preserving the original functionality. | #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';
}
| 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)
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. |
#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";
}
| 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])
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. |
#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";
}
| 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])
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #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;
}
}
}
| 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
}
}
|
Produce a functionally identical Go code for the snippet given in C++. | #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";
}
| 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++
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? |
#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;
}
| 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")
}
|
Convert this C++ block to Go, preserving its control flow and logic. |
#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;
}
| 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")
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #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;
}
| 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)
}
}
}
}
|
Produce a functionally identical Go code for the snippet given in C++. | #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;
}
| 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)
}
|
Produce a functionally identical Go code for the snippet given in C++. | #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;
}
| 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)
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #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" );
}
| 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)))
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | int meaning_of_life();
|
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
|
Write the same algorithm in Go as shown in this C++ implementation. | int meaning_of_life();
|
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #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;
}
| 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("./")
}
|
Change the following C++ code into Go without altering its purpose. | #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';
}
| 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)
}
}
|
Write the same code in Go as shown below in C++. | #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;
}
| 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)
}
|
Translate this program into Go but keep the logic exactly as in C++. | #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;
}
| 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)
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #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;
}
| 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])
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #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;
}
| 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
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #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);
}
| 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)
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #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);
}
| 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))
}
|
Write the same code in Go as shown below in C++. | #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;
}
| 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")
}
}
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | while (true)
std::cout << "SPAM\n";
| package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #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;
}
| 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)
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #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;
}
| 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)
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <cassert>
#include <iomanip>
#include <iostream>
int largest_proper_divisor(int n) {
assert(n > 0);
if ((n & 1) == 0)
return n >> 1;
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return n / p;
}
return 1;
}
int main() {
for (int n = 1; n < 101; ++n) {
std::cout << std::setw(2) << largest_proper_divisor(n)
<< (n % 10 == 0 ? '\n' : ' ');
}
}
| package main
import "fmt"
func largestProperDivisor(n int) int {
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return n / i
}
}
return 1
}
func main() {
fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
fmt.Print(" 1 ")
for n := 2; n <= 100; n++ {
if n%2 == 0 {
fmt.Printf("%2d ", n/2)
} else {
fmt.Printf("%2d ", largestProperDivisor(n))
}
if n%10 == 0 {
fmt.Println()
}
}
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using namespace std;
class MTF
{
public:
string encode( string str )
{
fillSymbolTable();
vector<int> output;
for( string::iterator it = str.begin(); it != str.end(); it++ )
{
for( int i = 0; i < 26; i++ )
{
if( *it == symbolTable[i] )
{
output.push_back( i );
moveToFront( i );
break;
}
}
}
string r;
for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
{
ostringstream ss;
ss << *it;
r += ss.str() + " ";
}
return r;
}
string decode( string str )
{
fillSymbolTable();
istringstream iss( str ); vector<int> output;
copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );
string r;
for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
{
r.append( 1, symbolTable[*it] );
moveToFront( *it );
}
return r;
}
private:
void moveToFront( int i )
{
char t = symbolTable[i];
for( int z = i - 1; z >= 0; z-- )
symbolTable[z + 1] = symbolTable[z];
symbolTable[0] = t;
}
void fillSymbolTable()
{
for( int x = 0; x < 26; x++ )
symbolTable[x] = x + 'a';
}
char symbolTable[26];
};
int main()
{
MTF mtf;
string a, str[] = { "broood", "bananaaa", "hiphophiphop" };
for( int x = 0; x < 3; x++ )
{
a = str[x];
cout << a << " -> encoded = ";
a = mtf.encode( a );
cout << a << "; decoded = " << mtf.decode( a ) << endl;
}
return 0;
}
| package main
import (
"bytes"
"fmt"
)
type symbolTable string
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
}
func (symbols symbolTable) decode(seq []byte) string {
chars := make([]byte, len(seq))
pad := []byte(symbols)
for i, x := range seq {
c := pad[x]
chars[i] = c
copy(pad[1:], pad[:x])
pad[0] = c
}
return string(chars)
}
func main() {
m := symbolTable("abcdefghijklmnopqrstuvwxyz")
for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
enc := m.encode(s)
dec := m.decode(enc)
fmt.Println(s, enc, dec)
if dec != s {
panic("Whoops!")
}
}
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <array>
#include <cstdio>
#include <numeric>
void PrintContainer(const auto& vec)
{
int count = 0;
for(auto value : vec)
{
printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' ');
}
}
int main()
{
auto cube = [](auto x){return x * x * x;};
std::array<int, 50> a;
std::iota(a.begin(), a.end(), 0);
std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);
PrintContainer(a);
}
| package main
import (
"fmt"
"rcu"
)
func main() {
fmt.Println("Cumulative sums of the first 50 cubes:")
sum := 0
for n := 0; n < 50; n++ {
sum += n * n * n
fmt.Printf("%9s ", rcu.Commatize(sum))
if n%10 == 9 {
fmt.Println()
}
}
fmt.Println()
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <complex>
#include <math.h>
#include <iostream>
template<class Type>
struct Precision
{
public:
static Type GetEps()
{
return eps;
}
static void SetEps(Type e)
{
eps = e;
}
private:
static Type eps;
};
template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);
template<class DigType>
bool IsDoubleEqual(DigType d1, DigType d2)
{
return (fabs(d1 - d2) < Precision<DigType>::GetEps());
}
template<class DigType>
DigType IntegerPart(DigType value)
{
return (value > 0) ? floor(value) : ceil(value);
}
template<class DigType>
DigType FractionPart(DigType value)
{
return fabs(IntegerPart<DigType>(value) - value);
}
template<class Type>
bool IsInteger(const Type& value)
{
return false;
}
#define GEN_CHECK_INTEGER(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
return true; \
}
#define GEN_CHECK_CMPL_INTEGER(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return value.imag() == zero; \
}
#define GEN_CHECK_REAL(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(FractionPart<type>(value), zero); \
}
#define GEN_CHECK_CMPL_REAL(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(value.imag(), zero); \
}
#define GEN_INTEGER(type) \
GEN_CHECK_INTEGER(type) \
GEN_CHECK_CMPL_INTEGER(type)
#define GEN_REAL(type) \
GEN_CHECK_REAL(type) \
GEN_CHECK_CMPL_REAL(type)
GEN_INTEGER(char)
GEN_INTEGER(unsigned char)
GEN_INTEGER(short)
GEN_INTEGER(unsigned short)
GEN_INTEGER(int)
GEN_INTEGER(unsigned int)
GEN_INTEGER(long)
GEN_INTEGER(unsigned long)
GEN_INTEGER(long long)
GEN_INTEGER(unsigned long long)
GEN_REAL(float)
GEN_REAL(double)
GEN_REAL(long double)
template<class Type>
inline void TestValue(const Type& value)
{
std::cout << "Value: " << value << " of type: " << typeid(Type).name() << " is integer - " << std::boolalpha << IsInteger(value) << std::endl;
}
int main()
{
char c = -100;
unsigned char uc = 200;
short s = c;
unsigned short us = uc;
int i = s;
unsigned int ui = us;
long long ll = i;
unsigned long long ull = ui;
std::complex<unsigned int> ci1(2, 0);
std::complex<int> ci2(2, 4);
std::complex<int> ci3(-2, 4);
std::complex<unsigned short> cs1(2, 0);
std::complex<short> cs2(2, 4);
std::complex<short> cs3(-2, 4);
std::complex<double> cd1(2, 0);
std::complex<float> cf1(2, 4);
std::complex<double> cd2(-2, 4);
float f1 = 1.0;
float f2 = -2.0;
float f3 = -2.4f;
float f4 = 1.23e-5f;
float f5 = 1.23e-10f;
double d1 = f5;
TestValue(c);
TestValue(uc);
TestValue(s);
TestValue(us);
TestValue(i);
TestValue(ui);
TestValue(ll);
TestValue(ull);
TestValue(ci1);
TestValue(ci2);
TestValue(ci3);
TestValue(cs1);
TestValue(cs2);
TestValue(cs3);
TestValue(cd1);
TestValue(cd2);
TestValue(cf1);
TestValue(f1);
TestValue(f2);
TestValue(f3);
TestValue(f4);
TestValue(f5);
std::cout << "Set float precision: 1e-15f\n";
Precision<float>::SetEps(1e-15f);
TestValue(f5);
TestValue(d1);
return 0;
}
| package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
)
func Float64IsInt(f float64) bool {
_, frac := math.Modf(f)
return frac == 0
}
func Float32IsInt(f float32) bool {
return Float64IsInt(float64(f))
}
func Complex128IsInt(c complex128) bool {
return imag(c) == 0 && Float64IsInt(real(c))
}
func Complex64IsInt(c complex64) bool {
return imag(c) == 0 && Float64IsInt(float64(real(c)))
}
type hasIsInt interface {
IsInt() bool
}
var bigIntT = reflect.TypeOf((*big.Int)(nil))
func IsInt(i interface{}) bool {
if ci, ok := i.(hasIsInt); ok {
return ci.IsInt()
}
switch v := reflect.ValueOf(i); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return true
case reflect.Float32, reflect.Float64:
return Float64IsInt(v.Float())
case reflect.Complex64, reflect.Complex128:
return Complex128IsInt(v.Complex())
case reflect.String:
if r, ok := new(big.Rat).SetString(v.String()); ok {
return r.IsInt()
}
case reflect.Ptr:
if v.Type() == bigIntT {
return true
}
}
return false
}
type intbased int16
type complexbased complex64
type customIntegerType struct {
}
func (customIntegerType) IsInt() bool { return true }
func (customIntegerType) String() string { return "<…>" }
func main() {
hdr := fmt.Sprintf("%27s %-6s %s\n", "Input", "IsInt", "Type")
show2 := func(t bool, i interface{}, args ...interface{}) {
istr := fmt.Sprint(i)
fmt.Printf("%27s %-6t %T ", istr, t, i)
fmt.Println(args...)
}
show := func(i interface{}, args ...interface{}) {
show2(IsInt(i), i, args...)
}
fmt.Print("Using Float64IsInt with float64:\n", hdr)
neg1 := -1.
for _, f := range []float64{
0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,
math.Pi,
math.MinInt64, math.MaxUint64,
math.SmallestNonzeroFloat64, math.MaxFloat64,
math.NaN(), math.Inf(1), math.Inf(-1),
} {
show2(Float64IsInt(f), f)
}
fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr)
for _, c := range []complex128{
3, 1i, 0i, 3.4,
} {
show2(Complex128IsInt(c), c)
}
fmt.Println("\nUsing reflection:")
fmt.Print(hdr)
show("hello")
show(math.MaxFloat64)
show("9e100")
f := new(big.Float)
show(f)
f.SetString("1e-3000")
show(f)
show("(4+0i)", "(complex strings not parsed)")
show(4 + 0i)
show(rune('§'), "or rune")
show(byte('A'), "or byte")
var t1 intbased = 5200
var t2a, t2b complexbased = 5 + 0i, 5 + 1i
show(t1)
show(t2a)
show(t2b)
x := uintptr(unsafe.Pointer(&t2b))
show(x)
show(math.MinInt32)
show(uint64(math.MaxUint64))
b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0)
show(b)
r := new(big.Rat)
show(r)
r.SetString("2/3")
show(r)
show(r.SetFrac(b, new(big.Int).SetInt64(9)))
show("12345/5")
show(new(customIntegerType))
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | system("pause");
| package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <vector>
#include <list>
#include <algorithm>
#include <iostream>
template <typename T>
struct Node {
T value;
Node* prev_node;
};
template <typename Container>
Container lis(const Container& values) {
using E = typename Container::value_type;
using NodePtr = Node<E>*;
using ConstNodePtr = const NodePtr;
std::vector<NodePtr> pileTops;
std::vector<Node<E>> nodes(values.size());
auto cur_node = std::begin(nodes);
for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)
{
auto node = &*cur_node;
node->value = *cur_value;
auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,
[](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });
if (lb != pileTops.begin())
node->prev_node = *std::prev(lb);
if (lb == pileTops.end())
pileTops.push_back(node);
else
*lb = node;
}
Container result(pileTops.size());
auto r = std::rbegin(result);
for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)
*r = node->value;
return result;
}
template <typename Container>
void show_lis(const Container& values)
{
auto&& result = lis(values);
for (auto& r : result) {
std::cout << r << ' ';
}
std::cout << std::endl;
}
int main()
{
show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });
show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });
}
| package main
import (
"fmt"
"sort"
)
type Node struct {
val int
back *Node
}
func lis (n []int) (result []int) {
var pileTops []*Node
for _, x := range n {
j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
node := &Node{ x, nil }
if j != 0 { node.back = pileTops[j-1] }
if j != len(pileTops) {
pileTops[j] = node
} else {
pileTops = append(pileTops, node)
}
}
if len(pileTops) == 0 { return []int{} }
for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
result = append(result, node.val)
}
for i := 0; i < len(result)/2; i++ {
result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
}
return
}
func main() {
for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
}
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
const int luckySize = 60000;
std::vector<int> luckyEven(luckySize);
std::vector<int> luckyOdd(luckySize);
void init() {
for (int i = 0; i < luckySize; ++i) {
luckyEven[i] = i * 2 + 2;
luckyOdd[i] = i * 2 + 1;
}
}
void filterLuckyEven() {
for (size_t n = 2; n < luckyEven.size(); ++n) {
int m = luckyEven[n - 1];
int end = (luckyEven.size() / m) * m - 1;
for (int j = end; j >= m - 1; j -= m) {
std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);
luckyEven.pop_back();
}
}
}
void filterLuckyOdd() {
for (size_t n = 2; n < luckyOdd.size(); ++n) {
int m = luckyOdd[n - 1];
int end = (luckyOdd.size() / m) * m - 1;
for (int j = end; j >= m - 1; j -= m) {
std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);
luckyOdd.pop_back();
}
}
}
void printBetween(size_t j, size_t k, bool even) {
std::ostream_iterator<int> out_it{ std::cout, ", " };
if (even) {
size_t max = luckyEven.back();
if (j > max || k > max) {
std::cerr << "At least one are is too big\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky even numbers between " << j << " and " << k << " are: ";
std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {
return j <= n && n <= k;
});
} else {
size_t max = luckyOdd.back();
if (j > max || k > max) {
std::cerr << "At least one are is too big\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky numbers between " << j << " and " << k << " are: ";
std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {
return j <= n && n <= k;
});
}
std::cout << '\n';
}
void printRange(size_t j, size_t k, bool even) {
std::ostream_iterator<int> out_it{ std::cout, ", " };
if (even) {
if (k >= luckyEven.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky even numbers " << j << " to " << k << " are: ";
std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);
} else {
if (k >= luckyOdd.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky numbers " << j << " to " << k << " are: ";
std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);
}
}
void printSingle(size_t j, bool even) {
if (even) {
if (j >= luckyEven.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky even number " << j << "=" << luckyEven[j - 1] << '\n';
} else {
if (j >= luckyOdd.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky number " << j << "=" << luckyOdd[j - 1] << '\n';
}
}
void help() {
std::cout << "./lucky j [k] [--lucky|--evenLucky]\n";
std::cout << "\n";
std::cout << " argument(s) | what is displayed\n";
std::cout << "==============================================\n";
std::cout << "-j=m | mth lucky number\n";
std::cout << "-j=m --lucky | mth lucky number\n";
std::cout << "-j=m --evenLucky | mth even lucky number\n";
std::cout << "-j=m -k=n | mth through nth (inclusive) lucky numbers\n";
std::cout << "-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n";
std::cout << "-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n";
std::cout << "-j=m -k=-n | all lucky numbers in the range [m, n]\n";
std::cout << "-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n";
std::cout << "-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n";
}
int main(int argc, char **argv) {
bool evenLucky = false;
int j = 0;
int k = 0;
if (argc < 2) {
help();
exit(EXIT_FAILURE);
}
bool good = false;
for (int i = 1; i < argc; ++i) {
if ('-' == argv[i][0]) {
if ('-' == argv[i][1]) {
if (0 == strcmp("--lucky", argv[i])) {
evenLucky = false;
} else if (0 == strcmp("--evenLucky", argv[i])) {
evenLucky = true;
} else {
std::cerr << "Unknown long argument: [" << argv[i] << "]\n";
exit(EXIT_FAILURE);
}
} else {
if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {
good = true;
j = atoi(&argv[i][3]);
} else if ('k' == argv[i][1] && '=' == argv[i][2]) {
k = atoi(&argv[i][3]);
} else {
std::cerr << "Unknown short argument: " << argv[i] << '\n';
exit(EXIT_FAILURE);
}
}
} else {
std::cerr << "Unknown argument: " << argv[i] << '\n';
exit(EXIT_FAILURE);
}
}
if (!good) {
help();
exit(EXIT_FAILURE);
}
init();
filterLuckyEven();
filterLuckyOdd();
if (k > 0) {
printRange(j, k, evenLucky);
} else if (k < 0) {
printBetween(j, -k, evenLucky);
} else {
printSingle(j, evenLucky);
}
return 0;
}
| package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
)
const luckySize = 60000
var luckyOdd = make([]int, luckySize)
var luckyEven = make([]int, luckySize)
func init() {
for i := 0; i < luckySize; i++ {
luckyOdd[i] = i*2 + 1
luckyEven[i] = i*2 + 2
}
}
func filterLuckyOdd() {
for n := 2; n < len(luckyOdd); n++ {
m := luckyOdd[n-1]
end := (len(luckyOdd)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyOdd[j:], luckyOdd[j+1:])
luckyOdd = luckyOdd[:len(luckyOdd)-1]
}
}
}
func filterLuckyEven() {
for n := 2; n < len(luckyEven); n++ {
m := luckyEven[n-1]
end := (len(luckyEven)/m)*m - 1
for j := end; j >= m-1; j -= m {
copy(luckyEven[j:], luckyEven[j+1:])
luckyEven = luckyEven[:len(luckyEven)-1]
}
}
}
func printSingle(j int, odd bool) error {
if odd {
if j >= len(luckyOdd) {
return fmt.Errorf("the argument, %d, is too big", j)
}
fmt.Println("Lucky number", j, "=", luckyOdd[j-1])
} else {
if j >= len(luckyEven) {
return fmt.Errorf("the argument, %d, is too big", j)
}
fmt.Println("Lucky even number", j, "=", luckyEven[j-1])
}
return nil
}
func printRange(j, k int, odd bool) error {
if odd {
if k >= len(luckyOdd) {
return fmt.Errorf("the argument, %d, is too big", k)
}
fmt.Println("Lucky numbers", j, "to", k, "are:")
fmt.Println(luckyOdd[j-1 : k])
} else {
if k >= len(luckyEven) {
return fmt.Errorf("the argument, %d, is too big", k)
}
fmt.Println("Lucky even numbers", j, "to", k, "are:")
fmt.Println(luckyEven[j-1 : k])
}
return nil
}
func printBetween(j, k int, odd bool) error {
var r []int
if odd {
max := luckyOdd[len(luckyOdd)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument, %d or %d, is too big", j, k)
}
for _, num := range luckyOdd {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky numbers between", j, "and", k, "are:")
fmt.Println(r)
} else {
max := luckyEven[len(luckyEven)-1]
if j > max || k > max {
return fmt.Errorf("at least one argument, %d or %d, is too big", j, k)
}
for _, num := range luckyEven {
if num < j {
continue
}
if num > k {
break
}
r = append(r, num)
}
fmt.Println("Lucky even numbers between", j, "and", k, "are:")
fmt.Println(r)
}
return nil
}
func main() {
nargs := len(os.Args)
if nargs < 2 || nargs > 4 {
log.Fatal("there must be between 1 and 3 command line arguments")
}
filterLuckyOdd()
filterLuckyEven()
j, err := strconv.Atoi(os.Args[1])
if err != nil || j < 1 {
log.Fatalf("first argument, %s, must be a positive integer", os.Args[1])
}
if nargs == 2 {
if err := printSingle(j, true); err != nil {
log.Fatal(err)
}
return
}
if nargs == 3 {
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatalf("second argument, %s, must be an integer", os.Args[2])
}
if k >= 0 {
if j > k {
log.Fatalf("second argument, %d, can't be less than first, %d", k, j)
}
if err := printRange(j, k, true); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j)
}
if err := printBetween(j, l, true); err != nil {
log.Fatal(err)
}
}
return
}
var odd bool
switch lucky := strings.ToLower(os.Args[3]); lucky {
case "lucky":
odd = true
case "evenlucky":
odd = false
default:
log.Fatalf("third argument, %s, is invalid", os.Args[3])
}
if os.Args[2] == "," {
if err := printSingle(j, odd); err != nil {
log.Fatal(err)
}
return
}
k, err := strconv.Atoi(os.Args[2])
if err != nil {
log.Fatal("second argument must be an integer or a comma")
}
if k >= 0 {
if j > k {
log.Fatalf("second argument, %d, can't be less than first, %d", k, j)
}
if err := printRange(j, k, odd); err != nil {
log.Fatal(err)
}
} else {
l := -k
if j > l {
log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j)
}
if err := printBetween(j, l, odd); err != nil {
log.Fatal(err)
}
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace detail {
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(end)
{ }
template <typename Lambda>
bool next(Lambda istoken)
{
if (_tbegin == _end) {
return false;
}
_tbegin = _tend;
for (; _tend != _end && !istoken(*_tend); ++_tend) {
if (*_tend == '\\' && std::next(_tend) != _end) {
++_tend;
}
}
if (_tend == _tbegin) {
_tend++;
}
return _tbegin != _end;
}
ForwardIterator begin() const { return _tbegin; }
ForwardIterator end() const { return _tend; }
bool operator==(char c) { return *_tbegin == c; }
};
template <typename List>
void append_all(List & lista, const List & listb)
{
if (listb.size() == 1) {
for (auto & a : lista) {
a += listb.back();
}
} else {
List tmp;
for (auto & a : lista) {
for (auto & b : listb) {
tmp.push_back(a + b);
}
}
lista = std::move(tmp);
}
}
template <typename String, typename List, typename Tokenizer>
List expand(Tokenizer & token)
{
std::vector<List> alts{ { String() } };
while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {
if (token == '{') {
append_all(alts.back(), expand<String, List>(token));
} else if (token == ',') {
alts.push_back({ String() });
} else if (token == '}') {
if (alts.size() == 1) {
for (auto & a : alts.back()) {
a = '{' + a + '}';
}
return alts.back();
} else {
for (std::size_t i = 1; i < alts.size(); i++) {
alts.front().insert(alts.front().end(),
std::make_move_iterator(std::begin(alts[i])),
std::make_move_iterator(std::end(alts[i])));
}
return std::move(alts.front());
}
} else {
for (auto & a : alts.back()) {
a.append(token.begin(), token.end());
}
}
}
List result{ String{ '{' } };
append_all(result, alts.front());
for (std::size_t i = 1; i < alts.size(); i++) {
for (auto & a : result) {
a += ',';
}
append_all(result, alts[i]);
}
return result;
}
}
template <
typename ForwardIterator,
typename String = std::basic_string<
typename std::iterator_traits<ForwardIterator>::value_type
>,
typename List = std::vector<String>
>
List expand(ForwardIterator begin, ForwardIterator end)
{
detail::tokenizer<ForwardIterator> token(begin, end);
List list{ String() };
while (token.next([](char c) { return c == '{'; })) {
if (token == '{') {
detail::append_all(list, detail::expand<String, List>(token));
} else {
for (auto & a : list) {
a.append(token.begin(), token.end());
}
}
}
return list;
}
template <
typename Range,
typename String = std::basic_string<typename Range::value_type>,
typename List = std::vector<String>
>
List expand(const Range & range)
{
using Iterator = typename Range::const_iterator;
return expand<Iterator, String, List>(std::begin(range), std::end(range));
}
int main()
{
for (std::string string : {
R"(~/{Downloads,Pictures}/*.{jpg,gif,png})",
R"(It{{em,alic}iz,erat}e{d,}, please.)",
R"({,{,gotta have{ ,\, again\, }}more }cowbell!)",
R"({}} some {\\{edge,edgy} }{ cases, here\\\})",
R"(a{b{1,2}c)",
R"(a{1,2}b}c)",
R"(a{1,{2},3}b)",
R"(a{b{1,2}c{}})",
R"(more{ darn{ cowbell,},})",
R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)",
R"({a,{\,b}c)",
R"(a{b,{{c}})",
R"({a{\}b,c}d)",
R"({a,b{{1,2}e}f)",
R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})",
R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)",
}) {
std::cout << string << '\n';
for (auto expansion : expand(string)) {
std::cout << " " << expansion << '\n';
}
std::cout << '\n';
}
return 0;
}
| package expand
type Expander interface {
Expand() []string
}
type Text string
func (t Text) Expand() []string { return []string{string(t)} }
type Alternation []Expander
func (alt Alternation) Expand() []string {
var out []string
for _, e := range alt {
out = append(out, e.Expand()...)
}
return out
}
type Sequence []Expander
func (seq Sequence) Expand() []string {
if len(seq) == 0 {
return nil
}
out := seq[0].Expand()
for _, e := range seq[1:] {
out = combine(out, e.Expand())
}
return out
}
func combine(al, bl []string) []string {
out := make([]string, 0, len(al)*len(bl))
for _, a := range al {
for _, b := range bl {
out = append(out, a+b)
}
}
return out
}
const (
escape = '\\'
altStart = '{'
altEnd = '}'
altSep = ','
)
type piT struct{ pos, cnt, depth int }
type Brace string
func Expand(s string) []string { return Brace(s).Expand() }
func (b Brace) Expand() []string { return b.Expander().Expand() }
func (b Brace) Expander() Expander {
s := string(b)
var posInfo []piT
var stack []int
removePosInfo := func(i int) {
end := len(posInfo) - 1
copy(posInfo[i:end], posInfo[i+1:])
posInfo = posInfo[:end]
}
inEscape := false
for i, r := range s {
if inEscape {
inEscape = false
continue
}
switch r {
case escape:
inEscape = true
case altStart:
stack = append(stack, len(posInfo))
posInfo = append(posInfo, piT{i, 0, len(stack)})
case altEnd:
if len(stack) == 0 {
continue
}
si := len(stack) - 1
pi := stack[si]
if posInfo[pi].cnt == 0 {
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == len(stack) {
removePosInfo(pi)
} else {
pi++
}
}
} else {
posInfo = append(posInfo, piT{i, -2, len(stack)})
}
stack = stack[:si]
case altSep:
if len(stack) == 0 {
continue
}
posInfo = append(posInfo, piT{i, -1, len(stack)})
posInfo[stack[len(stack)-1]].cnt++
}
}
for len(stack) > 0 {
si := len(stack) - 1
pi := stack[si]
depth := posInfo[pi].depth
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == depth {
removePosInfo(pi)
} else {
pi++
}
}
stack = stack[:si]
}
return buildExp(s, 0, posInfo)
}
func buildExp(s string, off int, info []piT) Expander {
if len(info) == 0 {
return Text(s)
}
var seq Sequence
i := 0
var dj, j, depth int
for dk, piK := range info {
k := piK.pos - off
switch s[k] {
case altStart:
if depth == 0 {
dj = dk
j = k
depth = piK.depth
}
case altEnd:
if piK.depth != depth {
continue
}
if j > i {
seq = append(seq, Text(s[i:j]))
}
alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])
seq = append(seq, alt)
i = k + 1
depth = 0
}
}
if j := len(s); j > i {
seq = append(seq, Text(s[i:j]))
}
if len(seq) == 1 {
return seq[0]
}
return seq
}
func buildAlt(s string, depth, off int, info []piT) Alternation {
var alt Alternation
i := 0
var di int
for dk, piK := range info {
if piK.depth != depth {
continue
}
if k := piK.pos - off; s[k] == altSep {
sub := buildExp(s[i:k], i+off, info[di:dk])
alt = append(alt, sub)
i = k + 1
di = dk + 1
}
}
sub := buildExp(s[i:], i+off, info[di:])
alt = append(alt, sub)
return alt
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <array>
#include <iostream>
#include <vector>
constexpr int MAX = 12;
static std::vector<char> sp;
static std::array<int, MAX> count;
static int pos = 0;
int factSum(int n) {
int s = 0;
int x = 0;
int f = 1;
while (x < n) {
f *= ++x;
s += f;
}
return s;
}
bool r(int n) {
if (n == 0) {
return false;
}
char c = sp[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1)) {
return false;
}
}
sp[pos++] = c;
return true;
}
void superPerm(int n) {
pos = n;
int len = factSum(n);
if (len > 0) {
sp.resize(len);
}
for (size_t i = 0; i <= n; i++) {
count[i] = i;
}
for (size_t i = 1; i <= n; i++) {
sp[i - 1] = '0' + i;
}
while (r(n)) {}
}
int main() {
for (size_t n = 0; n < MAX; n++) {
superPerm(n);
std::cout << "superPerm(" << n << ") len = " << sp.size() << '\n';
}
return 0;
}
| package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
)
func factSum(n int) int {
s := 0
for x, f := 0, 1; x < n; {
x++
f *= x
s += f
}
return s
}
func r(n int) bool {
if n == 0 {
return false
}
c := super[pos-n]
cnt[n]--
if cnt[n] == 0 {
cnt[n] = n
if !r(n - 1) {
return false
}
}
super[pos] = c
pos++
return true
}
func superperm(n int) {
pos = n
le := factSum(n)
super = make([]byte, le)
for i := 0; i <= n; i++ {
cnt[i] = i
}
for i := 1; i <= n; i++ {
super[i-1] = byte(i) + '0'
}
for r(n) {
}
}
func main() {
for n := 0; n < max; n++ {
fmt.Printf("superperm(%2d) ", n)
superperm(n)
fmt.Printf("len = %d\n", len(super))
}
}
|
Generate an equivalent Go version of this C++ code. | #ifndef INTERACTION_H
#define INTERACTION_H
#include <QWidget>
class QPushButton ;
class QLineEdit ;
class QVBoxLayout ;
class MyWidget : public QWidget {
Q_OBJECT
public :
MyWidget( QWidget *parent = 0 ) ;
private :
QLineEdit *entryField ;
QPushButton *increaseButton ;
QPushButton *randomButton ;
QVBoxLayout *myLayout ;
private slots :
void doIncrement( ) ;
void findRandomNumber( ) ;
} ;
#endif
| package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0")
entry.Connect("activate", func() {
str, _ := entry.GetText()
validateInput(window, str)
})
ib, err := gtk.ButtonNewWithLabel("Increment")
check(err, "Unable to create increment button:")
ib.Connect("clicked", func() {
str, _ := entry.GetText()
if i, ok := validateInput(window, str); ok {
entry.SetText(strconv.FormatInt(i+1, 10))
}
})
rb, err := gtk.ButtonNewWithLabel("Random")
check(err, "Unable to create random button:")
rb.Connect("clicked", func() {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO,
"Set random value",
)
answer := dialog.Run()
dialog.Destroy()
if answer == gtk.RESPONSE_YES {
entry.SetText(strconv.Itoa(rand.Intn(10000)))
}
})
box.PackStart(label, false, false, 2)
box.PackStart(entry, false, false, 2)
box.PackStart(ib, false, false, 2)
box.PackStart(rb, false, false, 2)
window.Add(box)
window.ShowAll()
gtk.Main()
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <random>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
mt19937 engine;
unsigned int one_of_n(unsigned int n) {
unsigned int choice;
for(unsigned int i = 0; i < n; ++i) {
uniform_int_distribution<unsigned int> distribution(0, i);
if(!distribution(engine))
choice = i;
}
return choice;
}
int main() {
engine = mt19937(random_device()());
unsigned int results[10] = {0};
for(unsigned int i = 0; i < 1000000; ++i)
results[one_of_n(10)]++;
ostream_iterator<unsigned int> out_it(cout, " ");
copy(results, results+10, out_it);
cout << '\n';
}
| package main
import (
"bufio"
"fmt"
"io"
"math/rand"
"time"
)
func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
br := bufio.NewReader(r)
s, err = br.ReadString('\n')
if err != nil {
return
}
ln = 1
lnLast := 1.
var sLast string
for {
sLast, err = br.ReadString('\n')
if err == io.EOF {
return s, ln, nil
}
if err != nil {
break
}
lnLast++
if rand.Float64() < 1/lnLast {
s = sLast
ln = int(lnLast)
}
}
return
}
func oneOfN(n int, file io.Reader) int {
_, ln, err := choseLineRandomly(file)
if err != nil {
panic(err)
}
return ln
}
type simReader int
func (r *simReader) Read(b []byte) (int, error) {
if *r <= 0 {
return 0, io.EOF
}
b[0] = '\n'
*r--
return 1, nil
}
func main() {
n := 10
freq := make([]int, n)
rand.Seed(time.Now().UnixNano())
for times := 0; times < 1e6; times++ {
sr := simReader(n)
freq[oneOfN(n, &sr)-1]++
}
fmt.Println(freq)
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
std::map<char, int> _map;
std::vector<std::string> _result;
size_t longest = 0;
void make_sequence( std::string n ) {
_map.clear();
for( std::string::iterator i = n.begin(); i != n.end(); i++ )
_map.insert( std::make_pair( *i, _map[*i]++ ) );
std::string z;
for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {
char c = ( *i ).second + 48;
z.append( 1, c );
z.append( 1, i->first );
}
if( longest <= z.length() ) {
longest = z.length();
if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {
_result.push_back( z );
make_sequence( z );
}
}
}
int main( int argc, char* argv[] ) {
std::vector<std::string> tests;
tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" );
for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {
make_sequence( *i );
std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n";
for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {
std::cout << *j << "\n";
}
std::cout << "\n\n";
}
return 0;
}
| package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
seqMaxLen = [][]string{s}
}
}
fmt.Println("Max sequence length:", maxLen)
fmt.Println("Sequences:", len(seqMaxLen))
for _, seq := range seqMaxLen {
fmt.Println("Sequence:")
for _, t := range seq {
fmt.Println(t)
}
}
}
func seq(n int) []string {
s := strconv.Itoa(n)
ss := []string{s}
for {
dSeq := sortD(s)
d := dSeq[0]
nd := 1
s = ""
for i := 1; ; i++ {
if i == len(dSeq) {
s = fmt.Sprintf("%s%d%c", s, nd, d)
break
}
if dSeq[i] == d {
nd++
} else {
s = fmt.Sprintf("%s%d%c", s, nd, d)
d = dSeq[i]
nd = 1
}
}
for _, s0 := range ss {
if s == s0 {
return ss
}
}
ss = append(ss, s)
}
panic("unreachable")
}
func sortD(s string) []rune {
r := make([]rune, len(s))
for i, d := range s {
j := 0
for ; j < i; j++ {
if d > r[j] {
copy(r[j+1:], r[j:i])
break
}
}
r[j] = d
}
return r
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <iostream>
#include <string>
#include <cstdint>
typedef std::uint64_t integer;
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;
integer number;
};
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "billionth", 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(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 number_name(integer n, bool ordinal) {
std::string result;
if (n < 20)
result = get_name(small[n], ordinal);
else if (n < 100) {
if (n % 10 == 0) {
result = get_name(tens[n/10 - 2], ordinal);
} else {
result = get_name(tens[n/10 - 2], false);
result += "-";
result += get_name(small[n % 10], ordinal);
}
} else {
const named_number& num = get_named_number(n);
integer p = num.number;
result = number_name(n/p, false);
result += " ";
if (n % p == 0) {
result += get_name(num, ordinal);
} else {
result += get_name(num, false);
result += " ";
result += number_name(n % p, ordinal);
}
}
return result;
}
void test_ordinal(integer n) {
std::cout << n << ": " << number_name(n, true) << '\n';
}
int main() {
test_ordinal(1);
test_ordinal(2);
test_ordinal(3);
test_ordinal(4);
test_ordinal(5);
test_ordinal(11);
test_ordinal(15);
test_ordinal(21);
test_ordinal(42);
test_ordinal(65);
test_ordinal(98);
test_ordinal(100);
test_ordinal(101);
test_ordinal(272);
test_ordinal(300);
test_ordinal(750);
test_ordinal(23456);
test_ordinal(7891233);
test_ordinal(8007006005004003LL);
return 0;
}
| import (
"fmt"
"strings"
)
func main() {
for _, n := range []int64{
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
} {
fmt.Println(sayOrdinal(n))
}
}
var irregularOrdinals = map[string]string{
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
func sayOrdinal(n int64) string {
s := say(n)
i := strings.LastIndexAny(s, " -")
i++
if x, ok := irregularOrdinals[s[i:]]; ok {
s = s[:i] + x
} else if s[len(s)-1] == 'y' {
s = s[:i] + s[i:len(s)-1] + "ieth"
} else {
s = s[:i] + s[i:] + "th"
}
return s
}
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
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <iostream>
typedef unsigned long long bigint;
using namespace std;
class sdn
{
public:
bool check( bigint n )
{
int cc = digitsCount( n );
return compare( n, cc );
}
void displayAll( bigint s )
{
for( bigint y = 1; y < s; y++ )
if( check( y ) )
cout << y << " is a Self-Describing Number." << endl;
}
private:
bool compare( bigint n, int cc )
{
bigint a;
while( cc )
{
cc--; a = n % 10;
if( dig[cc] != a ) return false;
n -= a; n /= 10;
}
return true;
}
int digitsCount( bigint n )
{
int cc = 0; bigint a;
memset( dig, 0, sizeof( dig ) );
while( n )
{
a = n % 10; dig[a]++;
cc++ ; n -= a; n /= 10;
}
return cc;
}
int dig[10];
};
int main( int argc, char* argv[] )
{
sdn s;
s. displayAll( 1000000000000 );
cout << endl << endl; system( "pause" );
bigint n;
while( true )
{
system( "cls" );
cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n;
if( !n ) return 0;
if( s.check( n ) ) cout << n << " is";
else cout << n << " is NOT";
cout << " a Self-Describing Number!" << endl << endl;
system( "pause" );
}
return 0;
}
| package main
import (
"fmt"
"strconv"
"strings"
)
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <iostream>
#include <tuple>
#include <vector>
std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);
std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {
if (pos > minLen || seq[0] > n) return { minLen, 0 };
else if (seq[0] == n) return { pos, 1 };
else if (pos < minLen) return tryPerm(0, pos, seq, n, minLen);
else return { minLen, 0 };
}
std::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) {
if (i > pos) return { minLen, 0 };
std::vector<int> seq2{ seq[0] + seq[i] };
seq2.insert(seq2.end(), seq.cbegin(), seq.cend());
auto res1 = checkSeq(pos + 1, seq2, n, minLen);
auto res2 = tryPerm(i + 1, pos, seq, n, res1.first);
if (res2.first < res1.first) return res2;
else if (res2.first == res1.first) return { res2.first, res1.second + res2.second };
else throw std::runtime_error("tryPerm exception");
}
std::pair<int, int> initTryPerm(int x) {
return tryPerm(0, 0, { 1 }, x, 12);
}
void findBrauer(int num) {
auto res = initTryPerm(num);
std::cout << '\n';
std::cout << "N = " << num << '\n';
std::cout << "Minimum length of chains: L(n)= " << res.first << '\n';
std::cout << "Number of minimum length Brauer chains: " << res.second << '\n';
}
int main() {
std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };
for (int i : nums) {
findBrauer(i);
}
return 0;
}
| package main
import "fmt"
var example []int
func reverse(s []int) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func checkSeq(pos, n, minLen int, seq []int) (int, int) {
switch {
case pos > minLen || seq[0] > n:
return minLen, 0
case seq[0] == n:
example = seq
return pos, 1
case pos < minLen:
return tryPerm(0, pos, n, minLen, seq)
default:
return minLen, 0
}
}
func tryPerm(i, pos, n, minLen int, seq []int) (int, int) {
if i > pos {
return minLen, 0
}
seq2 := make([]int, len(seq)+1)
copy(seq2[1:], seq)
seq2[0] = seq[0] + seq[i]
res11, res12 := checkSeq(pos+1, n, minLen, seq2)
res21, res22 := tryPerm(i+1, pos, n, res11, seq)
switch {
case res21 < res11:
return res21, res22
case res21 == res11:
return res21, res12 + res22
default:
fmt.Println("Error in tryPerm")
return 0, 0
}
}
func initTryPerm(x, minLen int) (int, int) {
return tryPerm(0, 0, x, minLen, []int{1})
}
func findBrauer(num, minLen, nbLimit int) {
actualMin, brauer := initTryPerm(num, minLen)
fmt.Println("\nN =", num)
fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin)
fmt.Println("Number of minimum length Brauer chains :", brauer)
if brauer > 0 {
reverse(example)
fmt.Println("Brauer example :", example)
}
example = nil
if num <= nbLimit {
nonBrauer := findNonBrauer(num, actualMin+1, brauer)
fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer)
if nonBrauer > 0 {
fmt.Println("Non-Brauer example :", example)
}
example = nil
} else {
println("Non-Brauer analysis suppressed")
}
}
func isAdditionChain(a []int) bool {
for i := 2; i < len(a); i++ {
if a[i] > a[i-1]*2 {
return false
}
ok := false
jloop:
for j := i - 1; j >= 0; j-- {
for k := j; k >= 0; k-- {
if a[j]+a[k] == a[i] {
ok = true
break jloop
}
}
}
if !ok {
return false
}
}
if example == nil && !isBrauer(a) {
example = make([]int, len(a))
copy(example, a)
}
return true
}
func isBrauer(a []int) bool {
for i := 2; i < len(a); i++ {
ok := false
for j := i - 1; j >= 0; j-- {
if a[i-1]+a[j] == a[i] {
ok = true
break
}
}
if !ok {
return false
}
}
return true
}
func nextChains(index, le int, seq []int, pcount *int) {
for {
if index < le-1 {
nextChains(index+1, le, seq, pcount)
}
if seq[index]+le-1-index >= seq[le-1] {
return
}
seq[index]++
for i := index + 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
if isAdditionChain(seq) {
(*pcount)++
}
}
}
func findNonBrauer(num, le, brauer int) int {
seq := make([]int, le)
seq[0] = 1
seq[le-1] = num
for i := 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
count := 0
if isAdditionChain(seq) {
count = 1
}
nextChains(2, le, seq, &count)
return count - brauer
}
func main() {
nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
fmt.Println("Searching for Brauer chains up to a minimum length of 12:")
for _, num := range nums {
findBrauer(num, 12, 79)
}
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. |
#include <iostream>
using namespace std;
int main()
{
long long int a = 30'00'000;
std::cout <<"And with the ' in C++ 14 : "<< a << endl;
return 0;
}
| package main
import "fmt"
func main() {
integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}
for _, integer := range integers {
fmt.Printf("%d ", integer)
}
floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}
for _, float := range floats {
fmt.Printf("%g ", float)
}
fmt.Println()
}
|
Write a version of this C++ function in Go with identical behavior. | template <typename Function>
void repeat(Function f, unsigned int n) {
for(unsigned int i=n; 0<i; i--)
f();
}
| package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <locale>
class Sparkline {
public:
Sparkline(std::wstring &cs) : charset( cs ){
}
virtual ~Sparkline(){
}
void print(std::string spark){
const char *delim = ", ";
std::vector<float> data;
std::string::size_type last = spark.find_first_not_of(delim, 0);
std::string::size_type pos = spark.find_first_of(delim, last);
while( pos != std::string::npos || last != std::string::npos ){
std::string tok = spark.substr(last, pos-last);
std::stringstream ss(tok);
float entry;
ss >> entry;
data.push_back( entry );
last = spark.find_first_not_of(delim, pos);
pos = spark.find_first_of(delim, last);
}
float min = *std::min_element( data.begin(), data.end() );
float max = *std::max_element( data.begin(), data.end() );
float skip = (charset.length()-1) / (max - min);
std::wcout<<L"Min: "<<min<<L"; Max: "<<max<<L"; Range: "<<(max-min)<<std::endl;
std::vector<float>::const_iterator it;
for(it = data.begin(); it != data.end(); it++){
float v = ( (*it) - min ) * skip;
std::wcout<<charset[ (int)floor( v ) ];
}
std::wcout<<std::endl;
}
private:
std::wstring &charset;
};
int main( int argc, char **argv ){
std::wstring charset = L"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
std::locale::global(std::locale("en_US.utf8"));
Sparkline sl(charset);
sl.print("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1");
sl.print("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5");
return 0;
}
| package main
import (
"bufio"
"errors"
"fmt"
"math"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
fmt.Println("Numbers please separated by space/commas:")
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s, n, min, max, err := spark(sc.Text())
if err != nil {
fmt.Println(err)
return
}
if n == 1 {
fmt.Println("1 value =", min)
} else {
fmt.Println(n, "values. Min:", min, "Max:", max)
}
fmt.Println(s)
}
var sep = regexp.MustCompile(`[\s,]+`)
func spark(s0 string) (sp string, n int, min, max float64, err error) {
ss := sep.Split(s0, -1)
n = len(ss)
vs := make([]float64, n)
var v float64
min = math.Inf(1)
max = math.Inf(-1)
for i, s := range ss {
switch v, err = strconv.ParseFloat(s, 64); {
case err != nil:
case math.IsNaN(v):
err = errors.New("NaN not supported.")
case math.IsInf(v, 0):
err = errors.New("Inf not supported.")
default:
if v < min {
min = v
}
if v > max {
max = v
}
vs[i] = v
continue
}
return
}
if min == max {
sp = strings.Repeat("▄", n)
} else {
rs := make([]rune, n)
f := 8 / (max - min)
for j, v := range vs {
i := rune(f * (v - min))
if i > 7 {
i = 7
}
rs[j] = '▁' + i
}
sp = string(rs)
}
return
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <iostream>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
std::cout << mul_inv(42, 2017) << std::endl;
return 0;
}
| package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewInt(42)
m := big.NewInt(2017)
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <cmath>
#include <fstream>
#include <iostream>
bool sunflower(const char* filename) {
std::ofstream out(filename);
if (!out)
return false;
constexpr int size = 600;
constexpr int seeds = 5 * size;
constexpr double pi = 3.14159265359;
constexpr double phi = 1.61803398875;
out << "<svg xmlns='http:
out << "' height='" << size << "' style='stroke:gold'>\n";
out << "<rect width='100%' height='100%' fill='black'/>\n";
out << std::setprecision(2) << std::fixed;
for (int i = 1; i <= seeds; ++i) {
double r = 2 * std::pow(i, phi)/seeds;
double theta = 2 * pi * phi * i;
double x = r * std::sin(theta) + size/2;
double y = r * std::cos(theta) + size/2;
double radius = std::sqrt(i)/13;
out << "<circle cx='" << x << "' cy='" << y << "' r='" << radius << "'/>\n";
}
out << "</svg>\n";
return true;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " filename\n";
return EXIT_FAILURE;
}
if (!sunflower(argv[1])) {
std::cerr << "image generation failed\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| package main
import (
"github.com/fogleman/gg"
"math"
)
func main() {
dc := gg.NewContext(400, 400)
dc.SetRGB(1, 1, 1)
dc.Clear()
dc.SetRGB(0, 0, 1)
c := (math.Sqrt(5) + 1) / 2
numberOfSeeds := 3000
for i := 0; i <= numberOfSeeds; i++ {
fi := float64(i)
fn := float64(numberOfSeeds)
r := math.Pow(fi, c) / fn
angle := 2 * math.Pi * c * fi
x := r*math.Sin(angle) + 200
y := r*math.Cos(angle) + 200
fi /= fn / 5
dc.DrawCircle(x, y, fi)
}
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("sunflower_fractal.png")
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <iostream>
#include <numeric>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
std::vector<int> demand = { 30, 20, 70, 30, 60 };
std::vector<int> supply = { 50, 60, 50, 50 };
std::vector<std::vector<int>> costs = {
{16, 16, 13, 22, 17},
{14, 14, 13, 19, 15},
{19, 19, 20, 23, 50},
{50, 12, 50, 15, 11}
};
int nRows = supply.size();
int nCols = demand.size();
std::vector<bool> rowDone(nRows, false);
std::vector<bool> colDone(nCols, false);
std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));
std::vector<int> diff(int j, int len, bool isRow) {
int min1 = INT_MAX;
int min2 = INT_MAX;
int minP = -1;
for (int i = 0; i < len; i++) {
if (isRow ? colDone[i] : rowDone[i]) {
continue;
}
int c = isRow
? costs[j][i]
: costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
minP = i;
} else if (c < min2) {
min2 = c;
}
}
return { min2 - min1, min1, minP };
}
std::vector<int> maxPenalty(int len1, int len2, bool isRow) {
int md = INT_MIN;
int pc = -1;
int pm = -1;
int mc = -1;
for (int i = 0; i < len1; i++) {
if (isRow ? rowDone[i] : colDone[i]) {
continue;
}
std::vector<int> res = diff(i, len2, isRow);
if (res[0] > md) {
md = res[0];
pm = i;
mc = res[1];
pc = res[2];
}
}
return isRow
? std::vector<int> { pm, pc, mc, md }
: std::vector<int>{ pc, pm, mc, md };
}
std::vector<int> nextCell() {
auto res1 = maxPenalty(nRows, nCols, true);
auto res2 = maxPenalty(nCols, nRows, false);
if (res1[3] == res2[3]) {
return res1[2] < res2[2]
? res1
: res2;
}
return res1[3] > res2[3]
? res2
: res1;
}
int main() {
int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });
int totalCost = 0;
while (supplyLeft > 0) {
auto cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = std::min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0) {
colDone[c] = true;
}
supply[r] -= quantity;
if (supply[r] == 0) {
rowDone[r] = true;
}
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
for (auto &a : result) {
std::cout << a << '\n';
}
std::cout << "Total cost: " << totalCost;
return 0;
}
| #include <stdio.h>
#include <limits.h>
#define TRUE 1
#define FALSE 0
#define N_ROWS 5
#define N_COLS 5
typedef int bool;
int supply[N_ROWS] = { 461, 277, 356, 488, 393 };
int demand[N_COLS] = { 278, 60, 461, 116, 1060 };
int costs[N_ROWS][N_COLS] = {
{ 46, 74, 9, 28, 99 },
{ 12, 75, 6, 36, 48 },
{ 35, 199, 4, 5, 71 },
{ 61, 81, 44, 88, 9 },
{ 85, 60, 14, 25, 79 }
};
int main() {
printf(" A B C D E\n");
for (i = 0; i < N_ROWS; ++i) {
printf("%c", 'V' + i);
for (j = 0; j < N_COLS; ++j) printf(" %3d", results[i][j]);
printf("\n");
}
printf("\nTotal cost = %d\n", total_cost);
return 0;
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
std::map<std::string, double> atomicMass = {
{"H", 1.008},
{"He", 4.002602},
{"Li", 6.94},
{"Be", 9.0121831},
{"B", 10.81},
{"C", 12.011},
{"N", 14.007},
{"O", 15.999},
{"F", 18.998403163},
{"Ne", 20.1797},
{"Na", 22.98976928},
{"Mg", 24.305},
{"Al", 26.9815385},
{"Si", 28.085},
{"P", 30.973761998},
{"S", 32.06},
{"Cl", 35.45},
{"Ar", 39.948},
{"K", 39.0983},
{"Ca", 40.078},
{"Sc", 44.955908},
{"Ti", 47.867},
{"V", 50.9415},
{"Cr", 51.9961},
{"Mn", 54.938044},
{"Fe", 55.845},
{"Co", 58.933194},
{"Ni", 58.6934},
{"Cu", 63.546},
{"Zn", 65.38},
{"Ga", 69.723},
{"Ge", 72.630},
{"As", 74.921595},
{"Se", 78.971},
{"Br", 79.904},
{"Kr", 83.798},
{"Rb", 85.4678},
{"Sr", 87.62},
{"Y", 88.90584},
{"Zr", 91.224},
{"Nb", 92.90637},
{"Mo", 95.95},
{"Ru", 101.07},
{"Rh", 102.90550},
{"Pd", 106.42},
{"Ag", 107.8682},
{"Cd", 112.414},
{"In", 114.818},
{"Sn", 118.710},
{"Sb", 121.760},
{"Te", 127.60},
{"I", 126.90447},
{"Xe", 131.293},
{"Cs", 132.90545196},
{"Ba", 137.327},
{"La", 138.90547},
{"Ce", 140.116},
{"Pr", 140.90766},
{"Nd", 144.242},
{"Pm", 145},
{"Sm", 150.36},
{"Eu", 151.964},
{"Gd", 157.25},
{"Tb", 158.92535},
{"Dy", 162.500},
{"Ho", 164.93033},
{"Er", 167.259},
{"Tm", 168.93422},
{"Yb", 173.054},
{"Lu", 174.9668},
{"Hf", 178.49},
{"Ta", 180.94788},
{"W", 183.84},
{"Re", 186.207},
{"Os", 190.23},
{"Ir", 192.217},
{"Pt", 195.084},
{"Au", 196.966569},
{"Hg", 200.592},
{"Tl", 204.38},
{"Pb", 207.2},
{"Bi", 208.98040},
{"Po", 209},
{"At", 210},
{"Rn", 222},
{"Fr", 223},
{"Ra", 226},
{"Ac", 227},
{"Th", 232.0377},
{"Pa", 231.03588},
{"U", 238.02891},
{"Np", 237},
{"Pu", 244},
{"Am", 243},
{"Cm", 247},
{"Bk", 247},
{"Cf", 251},
{"Es", 252},
{"Fm", 257},
{"Uue", 315},
{"Ubn", 299},
};
double evaluate(std::string s) {
s += '[';
double sum = 0.0;
std::string symbol;
std::string number;
for (auto c : s) {
if ('@' <= c && c <= '[') {
int n = 1;
if (number != "") {
n = stoi(number);
}
if (symbol != "") {
sum += atomicMass[symbol] * n;
}
if (c == '[') {
break;
}
symbol = c;
number = "";
} else if ('a' <= c && c <= 'z') {
symbol += c;
} else if ('0' <= c && c <= '9') {
number += c;
} else {
std::string msg = "Unexpected symbol ";
msg += c;
msg += " in molecule";
throw std::runtime_error(msg);
}
}
return sum;
}
std::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) {
auto pos = text.find(search);
if (pos == std::string::npos) {
return text;
}
auto beg = text.substr(0, pos);
auto end = text.substr(pos + search.length());
return beg + replace + end;
}
std::string replaceParens(std::string s) {
char letter = 'a';
while (true) {
auto start = s.find("(");
if (start == std::string::npos) {
break;
}
for (size_t i = start + 1; i < s.length(); i++) {
if (s[i] == ')') {
auto expr = s.substr(start + 1, i - start - 1);
std::string symbol = "@";
symbol += letter;
auto search = s.substr(start, i + 1 - start);
s = replaceFirst(s, search, symbol);
atomicMass[symbol] = evaluate(expr);
letter++;
break;
}
if (s[i] == '(') {
start = i;
continue;
}
}
}
return s;
}
int main() {
std::vector<std::string> molecules = {
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
};
for (auto molecule : molecules) {
auto mass = evaluate(replaceParens(molecule));
std::cout << std::setw(17) << molecule << " -> " << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\n';
}
return 0;
}
| package main
import (
"fmt"
"strconv"
"strings"
)
var atomicMass = map[string]float64{
"H": 1.008,
"He": 4.002602,
"Li": 6.94,
"Be": 9.0121831,
"B": 10.81,
"C": 12.011,
"N": 14.007,
"O": 15.999,
"F": 18.998403163,
"Ne": 20.1797,
"Na": 22.98976928,
"Mg": 24.305,
"Al": 26.9815385,
"Si": 28.085,
"P": 30.973761998,
"S": 32.06,
"Cl": 35.45,
"Ar": 39.948,
"K": 39.0983,
"Ca": 40.078,
"Sc": 44.955908,
"Ti": 47.867,
"V": 50.9415,
"Cr": 51.9961,
"Mn": 54.938044,
"Fe": 55.845,
"Co": 58.933194,
"Ni": 58.6934,
"Cu": 63.546,
"Zn": 65.38,
"Ga": 69.723,
"Ge": 72.630,
"As": 74.921595,
"Se": 78.971,
"Br": 79.904,
"Kr": 83.798,
"Rb": 85.4678,
"Sr": 87.62,
"Y": 88.90584,
"Zr": 91.224,
"Nb": 92.90637,
"Mo": 95.95,
"Ru": 101.07,
"Rh": 102.90550,
"Pd": 106.42,
"Ag": 107.8682,
"Cd": 112.414,
"In": 114.818,
"Sn": 118.710,
"Sb": 121.760,
"Te": 127.60,
"I": 126.90447,
"Xe": 131.293,
"Cs": 132.90545196,
"Ba": 137.327,
"La": 138.90547,
"Ce": 140.116,
"Pr": 140.90766,
"Nd": 144.242,
"Pm": 145,
"Sm": 150.36,
"Eu": 151.964,
"Gd": 157.25,
"Tb": 158.92535,
"Dy": 162.500,
"Ho": 164.93033,
"Er": 167.259,
"Tm": 168.93422,
"Yb": 173.054,
"Lu": 174.9668,
"Hf": 178.49,
"Ta": 180.94788,
"W": 183.84,
"Re": 186.207,
"Os": 190.23,
"Ir": 192.217,
"Pt": 195.084,
"Au": 196.966569,
"Hg": 200.592,
"Tl": 204.38,
"Pb": 207.2,
"Bi": 208.98040,
"Po": 209,
"At": 210,
"Rn": 222,
"Fr": 223,
"Ra": 226,
"Ac": 227,
"Th": 232.0377,
"Pa": 231.03588,
"U": 238.02891,
"Np": 237,
"Pu": 244,
"Am": 243,
"Cm": 247,
"Bk": 247,
"Cf": 251,
"Es": 252,
"Fm": 257,
"Uue": 315,
"Ubn": 299,
}
func replaceParens(s string) string {
var letter byte = 'a'
for {
start := strings.IndexByte(s, '(')
if start == -1 {
break
}
restart:
for i := start + 1; i < len(s); i++ {
if s[i] == ')' {
expr := s[start+1 : i]
symbol := fmt.Sprintf("@%c", letter)
s = strings.Replace(s, s[start:i+1], symbol, 1)
atomicMass[symbol] = evaluate(expr)
letter++
break
}
if s[i] == '(' {
start = i
goto restart
}
}
}
return s
}
func evaluate(s string) float64 {
s += string('[')
var symbol, number string
sum := 0.0
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c >= '@' && c <= '[':
n := 1
if number != "" {
n, _ = strconv.Atoi(number)
}
if symbol != "" {
sum += atomicMass[symbol] * float64(n)
}
if c == '[' {
break
}
symbol = string(c)
number = ""
case c >= 'a' && c <= 'z':
symbol += string(c)
case c >= '0' && c <= '9':
number += string(c)
default:
panic(fmt.Sprintf("Unexpected symbol %c in molecule", c))
}
}
return sum
}
func main() {
molecules := []string{
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3",
"C6H4O2(OH)4", "C27H46O", "Uue",
}
for _, molecule := range molecules {
mass := evaluate(replaceParens(molecule))
fmt.Printf("%17s -> %7.3f\n", molecule, mass)
}
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <iostream>
#include <vector>
using namespace std;
vector<int> UpTo(int n, int offset = 0)
{
vector<int> retval(n);
for (int ii = 0; ii < n; ++ii)
retval[ii] = ii + offset;
return retval;
}
struct JohnsonTrotterState_
{
vector<int> values_;
vector<int> positions_;
vector<bool> directions_;
int sign_;
JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}
int LargestMobile() const
{
for (int r = values_.size(); r > 0; --r)
{
const int loc = positions_[r] + (directions_[r] ? 1 : -1);
if (loc >= 0 && loc < values_.size() && values_[loc] < r)
return r;
}
return 0;
}
bool IsComplete() const { return LargestMobile() == 0; }
void operator++()
{
const int r = LargestMobile();
const int rLoc = positions_[r];
const int lLoc = rLoc + (directions_[r] ? 1 : -1);
const int l = values_[lLoc];
swap(values_[lLoc], values_[rLoc]);
swap(positions_[l], positions_[r]);
sign_ = -sign_;
for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)
*pd = !*pd;
}
};
int main(void)
{
JohnsonTrotterState_ state(4);
do
{
for (auto v : state.values_)
cout << v << " ";
cout << "\n";
++state;
} while (!state.IsComplete());
}
| package permute
func Iter(p []int) func() int {
f := pf(len(p))
return func() int {
return f(p)
}
}
func pf(n int) func([]int) int {
sign := 1
switch n {
case 0, 1:
return func([]int) (s int) {
s = sign
sign = 0
return
}
default:
p0 := pf(n - 1)
i := n
var d int
return func(p []int) int {
switch {
case sign == 0:
case i == n:
i--
sign = p0(p[:i])
d = -1
case i == 0:
i++
sign *= p0(p[1:])
d = 1
if sign == 0 {
p[0], p[1] = p[1], p[0]
}
default:
p[i], p[i-1] = p[i-1], p[i]
sign = -sign
i += d
}
return sign
}
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <iomanip>
#include <iostream>
int digit_sum(int n) {
int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
int main() {
for (int n = 1; n <= 70; ++n) {
for (int m = 1;; ++m) {
if (digit_sum(m * n) == n) {
std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' ');
break;
}
}
}
}
| package main
import "rcu"
func main() {
var res []int
for n := 1; n <= 70; n++ {
m := 1
for rcu.DigitSum(m*n, 10) != n {
m++
}
res = append(res, m)
}
rcu.PrintTable(res, 7, 10, true)
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <iomanip>
#include <iostream>
int digit_sum(int n) {
int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
int main() {
for (int n = 1; n <= 70; ++n) {
for (int m = 1;; ++m) {
if (digit_sum(m * n) == n) {
std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' ');
break;
}
}
}
}
| package main
import "rcu"
func main() {
var res []int
for n := 1; n <= 70; n++ {
m := 1
for rcu.DigitSum(m*n, 10) != n {
m++
}
res = append(res, m)
}
rcu.PrintTable(res, 7, 10, true)
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <iostream>
#include <vector>
constexpr int N = 2200;
constexpr int N2 = 2 * N * N;
int main() {
using namespace std;
vector<bool> found(N + 1);
vector<bool> aabb(N2 + 1);
int s = 3;
for (int a = 1; a < N; ++a) {
int aa = a * a;
for (int b = 1; b < N; ++b) {
aabb[aa + b * b] = true;
}
}
for (int c = 1; c <= N; ++c) {
int s1 = s;
s += 2;
int s2 = s;
for (int d = c + 1; d <= N; ++d) {
if (aabb[s1]) {
found[d] = true;
}
s1 += s2;
s2 += 2;
}
}
cout << "The values of d <= " << N << " which can't be represented:" << endl;
for (int d = 1; d <= N; ++d) {
if (!found[d]) {
cout << d << " ";
}
}
cout << endl;
return 0;
}
| package main
import "fmt"
const (
N = 2200
N2 = N * N * 2
)
func main() {
s := 3
var s1, s2 int
var r [N + 1]bool
var ab [N2 + 1]bool
for a := 1; a <= N; a++ {
a2 := a * a
for b := a; b <= N; b++ {
ab[a2 + b * b] = true
}
}
for c := 1; c <= N; c++ {
s1 = s
s += 2
s2 = s
for d := c + 1; d <= N; d++ {
if ab[s1] {
r[d] = true
}
s1 += s2
s2 += 2
}
}
for d := 1; d <= N; d++ {
if !r[d] {
fmt.Printf("%d ", d)
}
}
fmt.Println()
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <iostream>
using namespace std;
bool steady(int n) {
int mask = 1;
for (int d = n; d != 0; d /= 10)
mask *= 10;
return (n * n) % mask == n;
}
int main() {
for (int i = 1; i < 10000; i++)
if (steady(i)) printf("%4d^2 = %8d\n", i, i * i);
}
| package main
import (
"fmt"
"rcu"
"strconv"
"strings"
)
func contains(list []int, s int) bool {
for _, e := range list {
if e == s {
return true
}
}
return false
}
func main() {
fmt.Println("Steady squares under 10,000:")
finalDigits := []int{1, 5, 6}
for i := 1; i < 10000; i++ {
if !contains(finalDigits, i%10) {
continue
}
sq := i * i
sqs := strconv.Itoa(sq)
is := strconv.Itoa(i)
if strings.HasSuffix(sqs, is) {
fmt.Printf("%5s -> %10s\n", rcu.Commatize(i), rcu.Commatize(sq))
}
}
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <exception>
#include <iostream>
using ulong = unsigned long;
class MiddleSquare {
private:
ulong state;
ulong div, mod;
public:
MiddleSquare() = delete;
MiddleSquare(ulong start, ulong length) {
if (length % 2) throw std::invalid_argument("length must be even");
div = mod = 1;
for (ulong i=0; i<length/2; i++) div *= 10;
for (ulong i=0; i<length; i++) mod *= 10;
state = start % mod;
}
ulong next() {
return state = state * state / div % mod;
}
};
int main() {
MiddleSquare msq(675248, 6);
for (int i=0; i<5; i++)
std::cout << msq.next() << std::endl;
return 0;
}
| package main
import "fmt"
func random(seed int) int {
return seed * seed / 1e3 % 1e6
}
func main() {
seed := 675248
for i := 1; i <= 5; i++ {
seed = random(seed)
fmt.Println(seed)
}
}
|
Write the same code in Go as shown below in C++. | #include <exception>
#include <iostream>
using ulong = unsigned long;
class MiddleSquare {
private:
ulong state;
ulong div, mod;
public:
MiddleSquare() = delete;
MiddleSquare(ulong start, ulong length) {
if (length % 2) throw std::invalid_argument("length must be even");
div = mod = 1;
for (ulong i=0; i<length/2; i++) div *= 10;
for (ulong i=0; i<length; i++) mod *= 10;
state = start % mod;
}
ulong next() {
return state = state * state / div % mod;
}
};
int main() {
MiddleSquare msq(675248, 6);
for (int i=0; i<5; i++)
std::cout << msq.next() << std::endl;
return 0;
}
| package main
import "fmt"
func random(seed int) int {
return seed * seed / 1e3 % 1e6
}
func main() {
seed := 675248
for i := 1; i <= 5; i++ {
seed = random(seed)
fmt.Println(seed)
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <map>
std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) {
std::map<uint32_t, uint32_t> result;
for (uint32_t i = 1; i <= faces; ++i)
result.emplace(i, 1);
for (uint32_t d = 2; d <= dice; ++d) {
std::map<uint32_t, uint32_t> tmp;
for (const auto& p : result) {
for (uint32_t i = 1; i <= faces; ++i)
tmp[p.first + i] += p.second;
}
tmp.swap(result);
}
return result;
}
double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) {
auto totals1 = get_totals(dice1, faces1);
auto totals2 = get_totals(dice2, faces2);
double wins = 0;
for (const auto& p1 : totals1) {
for (const auto& p2 : totals2) {
if (p2.first >= p1.first)
break;
wins += p1.second * p2.second;
}
}
double total = std::pow(faces1, dice1) * std::pow(faces2, dice2);
return wins/total;
}
int main() {
std::cout << std::setprecision(10);
std::cout << probability(9, 4, 6, 6) << '\n';
std::cout << probability(5, 10, 6, 7) << '\n';
return 0;
}
| package main
import(
"math"
"fmt"
)
func minOf(x, y uint) uint {
if x < y {
return x
}
return y
}
func throwDie(nSides, nDice, s uint, counts []uint) {
if nDice == 0 {
counts[s]++
return
}
for i := uint(1); i <= nSides; i++ {
throwDie(nSides, nDice - 1, s + i, counts)
}
}
func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
len1 := (nSides1 + 1) * nDice1
c1 := make([]uint, len1)
throwDie(nSides1, nDice1, 0, c1)
len2 := (nSides2 + 1) * nDice2
c2 := make([]uint, len2)
throwDie(nSides2, nDice2, 0, c2)
p12 := math.Pow(float64(nSides1), float64(nDice1)) *
math.Pow(float64(nSides2), float64(nDice2))
tot := 0.0
for i := uint(0); i < len1; i++ {
for j := uint(0); j < minOf(i, len2); j++ {
tot += float64(c1[i] * c2[j]) / p12
}
}
return tot
}
func main() {
fmt.Println(beatingProbability(4, 9, 6, 6))
fmt.Println(beatingProbability(10, 5, 7, 6))
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <array>
#include <iostream>
int main()
{
double x = 2.0;
double xi = 0.5;
double y = 4.0;
double yi = 0.25;
double z = x + y;
double zi = 1.0 / ( x + y );
const std::array values{x, y, z};
const std::array inverses{xi, yi, zi};
auto multiplier = [](double a, double b)
{
return [=](double m){return a * b * m;};
};
for(size_t i = 0; i < values.size(); ++i)
{
auto new_function = multiplier(values[i], inverses[i]);
double value = new_function(i + 1.0);
std::cout << value << "\n";
}
}
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
for _, mf := range mfs {
fmt.Println(mf(1))
}
}
func multiplier(n1, n2 float64) func(float64) float64 {
n1n2 := n1 * n2
return func(m float64) float64 {
return n1n2 * m
}
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <array>
#include <iostream>
int main()
{
double x = 2.0;
double xi = 0.5;
double y = 4.0;
double yi = 0.25;
double z = x + y;
double zi = 1.0 / ( x + y );
const std::array values{x, y, z};
const std::array inverses{xi, yi, zi};
auto multiplier = [](double a, double b)
{
return [=](double m){return a * b * m;};
};
for(size_t i = 0; i < values.size(); ++i)
{
auto new_function = multiplier(values[i], inverses[i]);
double value = new_function(i + 1.0);
std::cout << value << "\n";
}
}
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
for _, mf := range mfs {
fmt.Println(mf(1))
}
}
func multiplier(n1, n2 float64) func(float64) float64 {
n1n2 := n1 * n2
return func(m float64) float64 {
return n1n2 * m
}
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <regex>
#include <tuple>
#include <set>
#include <array>
using namespace std;
class Board
{
public:
vector<vector<char>> sData, dData;
int px, py;
Board(string b)
{
regex pattern("([^\\n]+)\\n?");
sregex_iterator end, iter(b.begin(), b.end(), pattern);
int w = 0;
vector<string> data;
for(; iter != end; ++iter){
data.push_back((*iter)[1]);
w = max(w, (*iter)[1].length());
}
for(int v = 0; v < data.size(); ++v){
vector<char> sTemp, dTemp;
for(int u = 0; u < w; ++u){
if(u > data[v].size()){
sTemp.push_back(' ');
dTemp.push_back(' ');
}else{
char s = ' ', d = ' ', c = data[v][u];
if(c == '#')
s = '#';
else if(c == '.' || c == '*' || c == '+')
s = '.';
if(c == '@' || c == '+'){
d = '@';
px = u;
py = v;
}else if(c == '$' || c == '*')
d = '*';
sTemp.push_back(s);
dTemp.push_back(d);
}
}
sData.push_back(sTemp);
dData.push_back(dTemp);
}
}
bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)
{
if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ')
return false;
data[y][x] = ' ';
data[y+dy][x+dx] = '@';
return true;
}
bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)
{
if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')
return false;
data[y][x] = ' ';
data[y+dy][x+dx] = '@';
data[y+2*dy][x+2*dx] = '*';
return true;
}
bool isSolved(const vector<vector<char>> &data)
{
for(int v = 0; v < data.size(); ++v)
for(int u = 0; u < data[v].size(); ++u)
if((sData[v][u] == '.') ^ (data[v][u] == '*'))
return false;
return true;
}
string solve()
{
set<vector<vector<char>>> visited;
queue<tuple<vector<vector<char>>, string, int, int>> open;
open.push(make_tuple(dData, "", px, py));
visited.insert(dData);
array<tuple<int, int, char, char>, 4> dirs;
dirs[0] = make_tuple(0, -1, 'u', 'U');
dirs[1] = make_tuple(1, 0, 'r', 'R');
dirs[2] = make_tuple(0, 1, 'd', 'D');
dirs[3] = make_tuple(-1, 0, 'l', 'L');
while(open.size() > 0){
vector<vector<char>> temp, cur = get<0>(open.front());
string cSol = get<1>(open.front());
int x = get<2>(open.front());
int y = get<3>(open.front());
open.pop();
for(int i = 0; i < 4; ++i){
temp = cur;
int dx = get<0>(dirs[i]);
int dy = get<1>(dirs[i]);
if(temp[y+dy][x+dx] == '*'){
if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){
if(isSolved(temp))
return cSol + get<3>(dirs[i]);
open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));
visited.insert(temp);
}
}else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){
if(isSolved(temp))
return cSol + get<2>(dirs[i]);
open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));
visited.insert(temp);
}
}
}
return "No solution";
}
};
int main()
{
string level =
"#######\n"
"# #\n"
"# #\n"
"#. # #\n"
"#. $$ #\n"
"#.$$ #\n"
"#.# @#\n"
"#######";
Board b(level);
cout << level << endl << endl << b.solve() << endl;
return 0;
}
| package main
import (
"fmt"
"strings"
)
func main() {
level := `
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######`
fmt.Printf("level:%s\n", level)
fmt.Printf("solution:\n%s\n", solve(level))
}
func solve(board string) string {
buffer = make([]byte, len(board))
width := strings.Index(board[1:], "\n") + 1
dirs := []struct {
move, push string
dPos int
}{
{"u", "U", -width},
{"r", "R", 1},
{"d", "D", width},
{"l", "L", -1},
}
visited := map[string]bool{board: true}
open := []state{state{board, "", strings.Index(board, "@")}}
for len(open) > 0 {
s1 := &open[0]
open = open[1:]
for _, dir := range dirs {
var newBoard, newSol string
newPos := s1.pos + dir.dPos
switch s1.board[newPos] {
case '$', '*':
newBoard = s1.push(dir.dPos)
if newBoard == "" || visited[newBoard] {
continue
}
newSol = s1.cSol + dir.push
if strings.IndexAny(newBoard, ".+") < 0 {
return newSol
}
case ' ', '.':
newBoard = s1.move(dir.dPos)
if visited[newBoard] {
continue
}
newSol = s1.cSol + dir.move
default:
continue
}
open = append(open, state{newBoard, newSol, newPos})
visited[newBoard] = true
}
}
return "No solution"
}
type state struct {
board string
cSol string
pos int
}
var buffer []byte
func (s *state) move(dPos int) string {
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
newPos := s.pos + dPos
if buffer[newPos] == ' ' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
return string(buffer)
}
func (s *state) push(dPos int) string {
newPos := s.pos + dPos
boxPos := newPos + dPos
switch s.board[boxPos] {
case ' ', '.':
default:
return ""
}
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
if buffer[newPos] == '$' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
if buffer[boxPos] == ' ' {
buffer[boxPos] = '$'
} else {
buffer[boxPos] = '*'
}
return string(buffer)
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/gmp.hpp>
#include <iomanip>
#include <iostream>
namespace mp = boost::multiprecision;
using big_int = mp::mpz_int;
using big_float = mp::cpp_dec_float_100;
using rational = mp::mpq_rational;
big_int factorial(int n) {
big_int result = 1;
for (int i = 2; i <= n; ++i)
result *= i;
return result;
}
big_int almkvist_giullera(int n) {
return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /
(pow(factorial(n), 6) * 3);
}
int main() {
std::cout << "n | Integer portion of nth term\n"
<< "------------------------------------------------\n";
for (int n = 0; n < 10; ++n)
std::cout << n << " | " << std::setw(44) << almkvist_giullera(n)
<< '\n';
big_float epsilon(pow(big_float(10), -70));
big_float prev = 0, pi = 0;
rational sum = 0;
for (int n = 0;; ++n) {
rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));
sum += term;
pi = sqrt(big_float(1 / sum));
if (abs(pi - prev) < epsilon)
break;
prev = pi;
}
std::cout << "\nPi to 70 decimal places is:\n"
<< std::fixed << std::setprecision(70) << pi << '\n';
}
| package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/gmp.hpp>
#include <iomanip>
#include <iostream>
namespace mp = boost::multiprecision;
using big_int = mp::mpz_int;
using big_float = mp::cpp_dec_float_100;
using rational = mp::mpq_rational;
big_int factorial(int n) {
big_int result = 1;
for (int i = 2; i <= n; ++i)
result *= i;
return result;
}
big_int almkvist_giullera(int n) {
return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /
(pow(factorial(n), 6) * 3);
}
int main() {
std::cout << "n | Integer portion of nth term\n"
<< "------------------------------------------------\n";
for (int n = 0; n < 10; ++n)
std::cout << n << " | " << std::setw(44) << almkvist_giullera(n)
<< '\n';
big_float epsilon(pow(big_float(10), -70));
big_float prev = 0, pi = 0;
rational sum = 0;
for (int n = 0;; ++n) {
rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));
sum += term;
pi = sqrt(big_float(1 / sum));
if (abs(pi - prev) < epsilon)
break;
prev = pi;
}
std::cout << "\nPi to 70 decimal places is:\n"
<< std::fixed << std::setprecision(70) << pi << '\n';
}
| package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
template <typename iterator>
bool sum_of_any_subset(int n, iterator begin, iterator end) {
if (begin == end)
return false;
if (std::find(begin, end, n) != end)
return true;
int total = std::accumulate(begin, end, 0);
if (n == total)
return true;
if (n > total)
return false;
--end;
int d = n - *end;
return (d > 0 && sum_of_any_subset(d, begin, end)) ||
sum_of_any_subset(n, begin, end);
}
std::vector<int> factors(int n) {
std::vector<int> f{1};
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
f.push_back(i);
if (i * i != n)
f.push_back(n / i);
}
}
std::sort(f.begin(), f.end());
return f;
}
bool is_practical(int n) {
std::vector<int> f = factors(n);
for (int i = 1; i < n; ++i) {
if (!sum_of_any_subset(i, f.begin(), f.end()))
return false;
}
return true;
}
std::string shorten(const std::vector<int>& v, size_t n) {
std::ostringstream out;
size_t size = v.size(), i = 0;
if (n > 0 && size > 0)
out << v[i++];
for (; i < n && i < size; ++i)
out << ", " << v[i];
if (size > i + n) {
out << ", ...";
i = size - n;
}
for (; i < size; ++i)
out << ", " << v[i];
return out.str();
}
int main() {
std::vector<int> practical;
for (int n = 1; n <= 333; ++n) {
if (is_practical(n))
practical.push_back(n);
}
std::cout << "Found " << practical.size() << " practical numbers:\n"
<< shorten(practical, 10) << '\n';
for (int n : {666, 6666, 66666, 672, 720, 222222})
std::cout << n << " is " << (is_practical(n) ? "" : "not ")
<< "a practical number.\n";
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func powerset(set []int) [][]int {
if len(set) == 0 {
return [][]int{{}}
}
head := set[0]
tail := set[1:]
p1 := powerset(tail)
var p2 [][]int
for _, s := range powerset(tail) {
h := []int{head}
h = append(h, s...)
p2 = append(p2, h)
}
return append(p1, p2...)
}
func isPractical(n int) bool {
if n == 1 {
return true
}
divs := rcu.ProperDivisors(n)
subsets := powerset(divs)
found := make([]bool, n)
count := 0
for _, subset := range subsets {
sum := rcu.SumInts(subset)
if sum > 0 && sum < n && !found[sum] {
found[sum] = true
count++
if count == n-1 {
return true
}
}
}
return false
}
func main() {
fmt.Println("In the range 1..333, there are:")
var practical []int
for i := 1; i <= 333; i++ {
if isPractical(i) {
practical = append(practical, i)
}
}
fmt.Println(" ", len(practical), "practical numbers")
fmt.Println(" The first ten are", practical[0:10])
fmt.Println(" The final ten are", practical[len(practical)-10:])
fmt.Println("\n666 is practical:", isPractical(666))
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
template <typename iterator>
bool sum_of_any_subset(int n, iterator begin, iterator end) {
if (begin == end)
return false;
if (std::find(begin, end, n) != end)
return true;
int total = std::accumulate(begin, end, 0);
if (n == total)
return true;
if (n > total)
return false;
--end;
int d = n - *end;
return (d > 0 && sum_of_any_subset(d, begin, end)) ||
sum_of_any_subset(n, begin, end);
}
std::vector<int> factors(int n) {
std::vector<int> f{1};
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
f.push_back(i);
if (i * i != n)
f.push_back(n / i);
}
}
std::sort(f.begin(), f.end());
return f;
}
bool is_practical(int n) {
std::vector<int> f = factors(n);
for (int i = 1; i < n; ++i) {
if (!sum_of_any_subset(i, f.begin(), f.end()))
return false;
}
return true;
}
std::string shorten(const std::vector<int>& v, size_t n) {
std::ostringstream out;
size_t size = v.size(), i = 0;
if (n > 0 && size > 0)
out << v[i++];
for (; i < n && i < size; ++i)
out << ", " << v[i];
if (size > i + n) {
out << ", ...";
i = size - n;
}
for (; i < size; ++i)
out << ", " << v[i];
return out.str();
}
int main() {
std::vector<int> practical;
for (int n = 1; n <= 333; ++n) {
if (is_practical(n))
practical.push_back(n);
}
std::cout << "Found " << practical.size() << " practical numbers:\n"
<< shorten(practical, 10) << '\n';
for (int n : {666, 6666, 66666, 672, 720, 222222})
std::cout << n << " is " << (is_practical(n) ? "" : "not ")
<< "a practical number.\n";
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func powerset(set []int) [][]int {
if len(set) == 0 {
return [][]int{{}}
}
head := set[0]
tail := set[1:]
p1 := powerset(tail)
var p2 [][]int
for _, s := range powerset(tail) {
h := []int{head}
h = append(h, s...)
p2 = append(p2, h)
}
return append(p1, p2...)
}
func isPractical(n int) bool {
if n == 1 {
return true
}
divs := rcu.ProperDivisors(n)
subsets := powerset(divs)
found := make([]bool, n)
count := 0
for _, subset := range subsets {
sum := rcu.SumInts(subset)
if sum > 0 && sum < n && !found[sum] {
found[sum] = true
count++
if count == n-1 {
return true
}
}
}
return false
}
func main() {
fmt.Println("In the range 1..333, there are:")
var practical []int
for i := 1; i <= 333; i++ {
if isPractical(i) {
practical = append(practical, i)
}
}
fmt.Println(" ", len(practical), "practical numbers")
fmt.Println(" The first ten are", practical[0:10])
fmt.Println(" The final ten are", practical[len(practical)-10:])
fmt.Println("\n666 is practical:", isPractical(666))
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <cstdint>
#include <iostream>
#include <vector>
#include <primesieve.hpp>
void print_diffs(const std::vector<uint64_t>& vec) {
for (size_t i = 0, n = vec.size(); i != n; ++i) {
if (i != 0)
std::cout << " (" << vec[i] - vec[i - 1] << ") ";
std::cout << vec[i];
}
std::cout << '\n';
}
int main() {
std::cout.imbue(std::locale(""));
std::vector<uint64_t> asc, desc;
std::vector<std::vector<uint64_t>> max_asc, max_desc;
size_t max_asc_len = 0, max_desc_len = 0;
uint64_t prime;
const uint64_t limit = 1000000;
for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {
size_t alen = asc.size();
if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])
asc.erase(asc.begin(), asc.end() - 1);
asc.push_back(prime);
if (asc.size() >= max_asc_len) {
if (asc.size() > max_asc_len) {
max_asc_len = asc.size();
max_asc.clear();
}
max_asc.push_back(asc);
}
size_t dlen = desc.size();
if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])
desc.erase(desc.begin(), desc.end() - 1);
desc.push_back(prime);
if (desc.size() >= max_desc_len) {
if (desc.size() > max_desc_len) {
max_desc_len = desc.size();
max_desc.clear();
}
max_desc.push_back(desc);
}
}
std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n";
for (const auto& v : max_asc)
print_diffs(v);
std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n";
for (const auto& v : max_desc)
print_diffs(v);
return 0;
}
| package main
import (
"fmt"
"rcu"
)
const LIMIT = 999999
var primes = rcu.Primes(LIMIT)
func longestSeq(dir string) {
pd := 0
longSeqs := [][]int{{2}}
currSeq := []int{2}
for i := 1; i < len(primes); i++ {
d := primes[i] - primes[i-1]
if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
currSeq = []int{primes[i-1], primes[i]}
} else {
currSeq = append(currSeq, primes[i])
}
pd = d
}
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
for _, ls := range longSeqs {
var diffs []int
for i := 1; i < len(ls); i++ {
diffs = append(diffs, ls[i]-ls[i-1])
}
for i := 0; i < len(ls)-1; i++ {
fmt.Print(ls[i], " (", diffs[i], ") ")
}
fmt.Println(ls[len(ls)-1])
}
fmt.Println()
}
func main() {
fmt.Println("For primes < 1 million:\n")
for _, dir := range []string{"ascending", "descending"} {
longestSeq(dir)
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <set>
#include <primesieve.hpp>
class erdos_prime_generator {
public:
erdos_prime_generator() {}
uint64_t next();
private:
bool erdos(uint64_t p) const;
primesieve::iterator iter_;
std::set<uint64_t> primes_;
};
uint64_t erdos_prime_generator::next() {
uint64_t prime;
for (;;) {
prime = iter_.next_prime();
primes_.insert(prime);
if (erdos(prime))
break;
}
return prime;
}
bool erdos_prime_generator::erdos(uint64_t p) const {
for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {
if (primes_.find(p - f) != primes_.end())
return false;
}
return true;
}
int main() {
std::wcout.imbue(std::locale(""));
erdos_prime_generator epgen;
const int max_print = 2500;
const int max_count = 7875;
uint64_t p;
std::wcout << L"Erd\x151s primes less than " << max_print << L":\n";
for (int count = 1; count <= max_count; ++count) {
p = epgen.next();
if (p < max_print)
std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' ');
}
std::wcout << L"\n\nThe " << max_count << L"th Erd\x151s prime is " << p << L".\n";
return 0;
}
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 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
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
|
Generate an equivalent Go version of this C++ code. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <set>
#include <primesieve.hpp>
class erdos_prime_generator {
public:
erdos_prime_generator() {}
uint64_t next();
private:
bool erdos(uint64_t p) const;
primesieve::iterator iter_;
std::set<uint64_t> primes_;
};
uint64_t erdos_prime_generator::next() {
uint64_t prime;
for (;;) {
prime = iter_.next_prime();
primes_.insert(prime);
if (erdos(prime))
break;
}
return prime;
}
bool erdos_prime_generator::erdos(uint64_t p) const {
for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {
if (primes_.find(p - f) != primes_.end())
return false;
}
return true;
}
int main() {
std::wcout.imbue(std::locale(""));
erdos_prime_generator epgen;
const int max_print = 2500;
const int max_count = 7875;
uint64_t p;
std::wcout << L"Erd\x151s primes less than " << max_print << L":\n";
for (int count = 1; count <= max_count; ++count) {
p = epgen.next();
if (p < max_print)
std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' ');
}
std::wcout << L"\n\nThe " << max_count << L"th Erd\x151s prime is " << p << L".\n";
return 0;
}
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 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
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <set>
#include <primesieve.hpp>
class erdos_prime_generator {
public:
erdos_prime_generator() {}
uint64_t next();
private:
bool erdos(uint64_t p) const;
primesieve::iterator iter_;
std::set<uint64_t> primes_;
};
uint64_t erdos_prime_generator::next() {
uint64_t prime;
for (;;) {
prime = iter_.next_prime();
primes_.insert(prime);
if (erdos(prime))
break;
}
return prime;
}
bool erdos_prime_generator::erdos(uint64_t p) const {
for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {
if (primes_.find(p - f) != primes_.end())
return false;
}
return true;
}
int main() {
std::wcout.imbue(std::locale(""));
erdos_prime_generator epgen;
const int max_print = 2500;
const int max_count = 7875;
uint64_t p;
std::wcout << L"Erd\x151s primes less than " << max_print << L":\n";
for (int count = 1; count <= max_count; ++count) {
p = epgen.next();
if (p < max_print)
std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' ');
}
std::wcout << L"\n\nThe " << max_count << L"th Erd\x151s prime is " << p << L".\n";
return 0;
}
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 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
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
|
Write a version of this C++ function in Go with identical behavior. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <cstdlib>
#include <string>
#include <bitset>
using namespace std;
typedef bitset<4> hood_t;
struct node
{
int val;
hood_t neighbors;
};
class nSolver
{
public:
void solve(vector<string>& puzz, int max_wid)
{
if (puzz.size() < 1) return;
wid = max_wid;
hei = static_cast<int>(puzz.size()) / wid;
max = wid * hei;
int len = max, c = 0;
arr = vector<node>(len, node({ 0, 0 }));
weHave = vector<bool>(len + 1, false);
for (const auto& s : puzz)
{
if (s == "*") { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi(s.c_str());
if (arr[c].val > 0) weHave[arr[c].val] = true;
c++;
}
solveIt(); c = 0;
for (auto&& s : puzz)
{
if (s == ".")
s = std::to_string(arr[c].val);
c++;
}
}
private:
bool search(int x, int y, int w, int dr)
{
if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;
node& n = arr[x + y * wid];
n.neighbors = getNeighbors(x, y);
if (weHave[w])
{
for (int d = 0; d < 4; d++)
{
if (n.neighbors[d])
{
int a = x + dx[d], b = y + dy[d];
if (arr[a + b * wid].val == w)
if (search(a, b, w + dr, dr))
return true;
}
}
return false;
}
for (int d = 0; d < 4; d++)
{
if (n.neighbors[d])
{
int a = x + dx[d], b = y + dy[d];
if (arr[a + b * wid].val == 0)
{
arr[a + b * wid].val = w;
if (search(a, b, w + dr, dr))
return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
hood_t getNeighbors(int x, int y)
{
hood_t retval;
for (int xx = 0; xx < 4; xx++)
{
int a = x + dx[xx], b = y + dy[xx];
if (a < 0 || b < 0 || a >= wid || b >= hei)
continue;
if (arr[a + b * wid].val > -1)
retval.set(xx);
}
return retval;
}
void solveIt()
{
int x, y, z; findStart(x, y, z);
if (z == 99999) { cout << "\nCan't find start point!\n"; return; }
search(x, y, z + 1, 1);
if (z > 1) search(x, y, z - 1, -1);
}
void findStart(int& x, int& y, int& z)
{
z = 99999;
for (int b = 0; b < hei; b++)
for (int a = 0; a < wid; a++)
if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)
{
x = a; y = b;
z = arr[a + wid * b].val;
}
}
vector<int> dx = vector<int>({ -1, 1, 0, 0 });
vector<int> dy = vector<int>({ 0, 0, -1, 1 });
int wid, hei, max;
vector<node> arr;
vector<bool> weHave;
};
int main(int argc, char* argv[])
{
int wid; string p;
p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9;
istringstream iss(p); vector<string> puzz;
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));
nSolver s; s.solve(puzz, wid);
int c = 0;
for (const auto& s : puzz)
{
if (s != "*" && s != ".")
{
if (atoi(s.c_str()) < 10) cout << "0";
cout << s << " ";
}
else cout << " ";
if (++c >= wid) { cout << endl; c = 0; }
}
cout << endl << endl;
return system("pause");
}
| package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <cstdlib>
#include <string>
#include <bitset>
using namespace std;
typedef bitset<4> hood_t;
struct node
{
int val;
hood_t neighbors;
};
class nSolver
{
public:
void solve(vector<string>& puzz, int max_wid)
{
if (puzz.size() < 1) return;
wid = max_wid;
hei = static_cast<int>(puzz.size()) / wid;
max = wid * hei;
int len = max, c = 0;
arr = vector<node>(len, node({ 0, 0 }));
weHave = vector<bool>(len + 1, false);
for (const auto& s : puzz)
{
if (s == "*") { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi(s.c_str());
if (arr[c].val > 0) weHave[arr[c].val] = true;
c++;
}
solveIt(); c = 0;
for (auto&& s : puzz)
{
if (s == ".")
s = std::to_string(arr[c].val);
c++;
}
}
private:
bool search(int x, int y, int w, int dr)
{
if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;
node& n = arr[x + y * wid];
n.neighbors = getNeighbors(x, y);
if (weHave[w])
{
for (int d = 0; d < 4; d++)
{
if (n.neighbors[d])
{
int a = x + dx[d], b = y + dy[d];
if (arr[a + b * wid].val == w)
if (search(a, b, w + dr, dr))
return true;
}
}
return false;
}
for (int d = 0; d < 4; d++)
{
if (n.neighbors[d])
{
int a = x + dx[d], b = y + dy[d];
if (arr[a + b * wid].val == 0)
{
arr[a + b * wid].val = w;
if (search(a, b, w + dr, dr))
return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
hood_t getNeighbors(int x, int y)
{
hood_t retval;
for (int xx = 0; xx < 4; xx++)
{
int a = x + dx[xx], b = y + dy[xx];
if (a < 0 || b < 0 || a >= wid || b >= hei)
continue;
if (arr[a + b * wid].val > -1)
retval.set(xx);
}
return retval;
}
void solveIt()
{
int x, y, z; findStart(x, y, z);
if (z == 99999) { cout << "\nCan't find start point!\n"; return; }
search(x, y, z + 1, 1);
if (z > 1) search(x, y, z - 1, -1);
}
void findStart(int& x, int& y, int& z)
{
z = 99999;
for (int b = 0; b < hei; b++)
for (int a = 0; a < wid; a++)
if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z)
{
x = a; y = b;
z = arr[a + wid * b].val;
}
}
vector<int> dx = vector<int>({ -1, 1, 0, 0 });
vector<int> dy = vector<int>({ 0, 0, -1, 1 });
int wid, hei, max;
vector<node> arr;
vector<bool> weHave;
};
int main(int argc, char* argv[])
{
int wid; string p;
p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9;
istringstream iss(p); vector<string> puzz;
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));
nSolver s; s.solve(puzz, wid);
int c = 0;
for (const auto& s : puzz)
{
if (s != "*" && s != ".")
{
if (atoi(s.c_str()) < 10) cout << "0";
cout << s << " ";
}
else cout << " ";
if (++c >= wid) { cout << endl; c = 0; }
}
cout << endl << endl;
return system("pause");
}
| package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
var example1 = []string{
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
|
Generate an equivalent Go version of this C++ code. | #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));
};
};
}
auto Add(auto a, auto b) {
return [=](auto f) {
return [=](auto x) {
return a(f)(b(f)(x));
};
};
}
auto Multiply(auto a, auto b) {
return [=](auto f) {
return a(b(f));
};
}
auto Exp(auto a, auto b) {
return b(a);
}
auto IsZero(auto a){
return a([](auto){ return False; })(True);
}
auto Predecessor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(
[=](auto g) {
return [=](auto h){
return h(g(f));
};
}
)([=](auto){ return x; })([](auto y){ return y; });
};
};
}
auto Subtract(auto a, auto b) {
{
return b([](auto c){ return Predecessor(c); })(a);
};
}
namespace
{
auto Divr(decltype(Zero), auto) {
return Zero;
}
auto Divr(auto a, auto b) {
auto a_minus_b = Subtract(a, b);
auto isZero = IsZero(a_minus_b);
return isZero
(Zero)
(Successor(Divr(isZero(Zero)(a_minus_b), b)));
}
}
auto Divide(auto a, auto b) {
return Divr(Successor(a), b);
}
template <int N> constexpr auto ToChurch() {
if constexpr(N<=0) return Zero;
else return Successor(ToChurch<N-1>());
}
int ToInt(auto church) {
return church([](int n){ return n + 1; })(0);
}
int main() {
auto three = Successor(Successor(Successor(Zero)));
auto four = Successor(three);
auto six = ToChurch<6>();
auto ten = ToChurch<10>();
auto thousand = Exp(ten, three);
std::cout << "\n 3 + 4 = " << ToInt(Add(three, four));
std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four));
std::cout << "\n 3^4 = " << ToInt(Exp(three, four));
std::cout << "\n 4^3 = " << ToInt(Exp(four, three));
std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero));
std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three));
std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four));
std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three));
std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six));
auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));
auto looloolool = Successor(looloolooo);
std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool);
std::cout << "\n golden ratio = " <<
thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n";
}
| 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))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.